New test.
[mono.git] / mcs / class / corlib / Mono.Security.X509 / X509Certificate.cs
1 //
2 // X509Certificates.cs: Handles X.509 certificates.
3 //
4 // Author:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //
7 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
9 //
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
17 // 
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
20 // 
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
28 //
29
30 using System;
31 using System.Runtime.Serialization;
32 using System.Security.Cryptography;
33 using SSCX = System.Security.Cryptography.X509Certificates;
34 using System.Security.Permissions;
35 using System.Text;
36
37 namespace Mono.Security.X509 {
38
39         // References:
40         // a.   Internet X.509 Public Key Infrastructure Certificate and CRL Profile
41         //      http://www.ietf.org/rfc/rfc3280.txt
42         // b.   ITU ASN.1 standards (free download)
43         //      http://www.itu.int/ITU-T/studygroups/com17/languages/
44
45 #if INSIDE_CORLIB
46         internal class X509Certificate : ISerializable {
47 #elif NET_2_0
48         public class X509Certificate : ISerializable {
49 #else
50         public class X509Certificate {
51 #endif
52
53                 private ASN1 decoder;
54
55                 private byte[] m_encodedcert;
56                 private DateTime m_from;
57                 private DateTime m_until;
58                 private ASN1 issuer;
59                 private string m_issuername;
60                 private string m_keyalgo;
61                 private byte[] m_keyalgoparams;
62                 private ASN1 subject;
63                 private string m_subject;
64                 private byte[] m_publickey;
65                 private byte[] signature;
66                 private string m_signaturealgo;
67                 private byte[] m_signaturealgoparams;
68                 private byte[] certhash;
69                 private RSA _rsa;
70                 private DSA _dsa;
71                 
72                 // from http://www.ietf.org/rfc/rfc2459.txt
73                 //
74                 //Certificate  ::=  SEQUENCE  {
75                 //     tbsCertificate       TBSCertificate,
76                 //     signatureAlgorithm   AlgorithmIdentifier,
77                 //     signature            BIT STRING  }
78                 //
79                 //TBSCertificate  ::=  SEQUENCE  {
80                 //     version         [0]  Version DEFAULT v1,
81                 //     serialNumber         CertificateSerialNumber,
82                 //     signature            AlgorithmIdentifier,
83                 //     issuer               Name,
84                 //     validity             Validity,
85                 //     subject              Name,
86                 //     subjectPublicKeyInfo SubjectPublicKeyInfo,
87                 //     issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
88                 //                          -- If present, version shall be v2 or v3
89                 //     subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
90                 //                          -- If present, version shall be v2 or v3
91                 //     extensions      [3]  Extensions OPTIONAL
92                 //                          -- If present, version shall be v3 --  }
93                 private int version;
94                 private byte[] serialnumber;
95
96 //              private byte[] issuerUniqueID;
97 //              private byte[] subjectUniqueID;
98                 private X509ExtensionCollection extensions;
99
100                 private static string encoding_error = Locale.GetText ("Input data cannot be coded as a valid certificate.");
101
102
103                 // that's were the real job is!
104                 private void Parse (byte[] data) 
105                 {
106                         try {
107                                 decoder = new ASN1 (data);
108                                 // Certificate 
109                                 if (decoder.Tag != 0x30)
110                                         throw new CryptographicException (encoding_error);
111                                 // Certificate / TBSCertificate
112                                 if (decoder [0].Tag != 0x30)
113                                         throw new CryptographicException (encoding_error);
114
115                                 ASN1 tbsCertificate = decoder [0];
116
117                                 int tbs = 0;
118                                 // Certificate / TBSCertificate / Version
119                                 ASN1 v = decoder [0][tbs];
120                                 version = 1;                    // DEFAULT v1
121                                 if ((v.Tag == 0xA0) && (v.Count > 0)) {
122                                         // version (optional) is present only in v2+ certs
123                                         version += v [0].Value [0];     // zero based
124                                         tbs++;
125                                 }
126
127                                 // Certificate / TBSCertificate / CertificateSerialNumber
128                                 ASN1 sn = decoder [0][tbs++];
129                                 if (sn.Tag != 0x02) 
130                                         throw new CryptographicException (encoding_error);
131                                 serialnumber = sn.Value;
132                                 Array.Reverse (serialnumber, 0, serialnumber.Length);
133                 
134                                 // Certificate / TBSCertificate / AlgorithmIdentifier
135                                 tbs++;
136                                 // ASN1 signatureAlgo = tbsCertificate.Element (tbs++, 0x30); 
137                 
138                                 issuer = tbsCertificate.Element (tbs++, 0x30); 
139                                 m_issuername = X501.ToString (issuer);
140                 
141                                 ASN1 validity = tbsCertificate.Element (tbs++, 0x30);
142                                 ASN1 notBefore = validity [0];
143                                 m_from = ASN1Convert.ToDateTime (notBefore);
144                                 ASN1 notAfter = validity [1];
145                                 m_until = ASN1Convert.ToDateTime (notAfter);
146                 
147                                 subject = tbsCertificate.Element (tbs++, 0x30);
148                                 m_subject = X501.ToString (subject);
149                 
150                                 ASN1 subjectPublicKeyInfo = tbsCertificate.Element (tbs++, 0x30);
151                 
152                                 ASN1 algorithm = subjectPublicKeyInfo.Element (0, 0x30);
153                                 ASN1 algo = algorithm.Element (0, 0x06);
154                                 m_keyalgo = ASN1Convert.ToOid (algo);
155                                 // parameters ANY DEFINED BY algorithm OPTIONAL
156                                 // so we dont ask for a specific (Element) type and return DER
157                                 ASN1 parameters = algorithm [1];
158                                 m_keyalgoparams = ((algorithm.Count > 1) ? parameters.GetBytes () : null);
159                 
160                                 ASN1 subjectPublicKey = subjectPublicKeyInfo.Element (1, 0x03); 
161                                 // we must drop th first byte (which is the number of unused bits
162                                 // in the BITSTRING)
163                                 int n = subjectPublicKey.Length - 1;
164                                 m_publickey = new byte [n];
165                                 Buffer.BlockCopy (subjectPublicKey.Value, 1, m_publickey, 0, n);
166
167                                 // signature processing
168                                 byte[] bitstring = decoder [2].Value;
169                                 // first byte contains unused bits in first byte
170                                 signature = new byte [bitstring.Length - 1];
171                                 Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
172
173                                 algorithm = decoder [1];
174                                 algo = algorithm.Element (0, 0x06);
175                                 m_signaturealgo = ASN1Convert.ToOid (algo);
176                                 parameters = algorithm [1];
177                                 if (parameters != null)
178                                         m_signaturealgoparams = parameters.GetBytes ();
179                                 else
180                                         m_signaturealgoparams = null;
181
182                                 // Certificate / TBSCertificate / issuerUniqueID
183                                 ASN1 issuerUID = tbsCertificate.Element (tbs, 0xA1);
184                                 if (issuerUID != null) {
185                                         tbs++;
186 //                                      issuerUniqueID = issuerUID.Value;
187                                 }
188
189                                 // Certificate / TBSCertificate / subjectUniqueID
190                                 ASN1 subjectUID = tbsCertificate.Element (tbs, 0xA2);
191                                 if (subjectUID != null) {
192                                         tbs++;
193 //                                      subjectUniqueID = subjectUID.Value;
194                                 }
195
196                                 // Certificate / TBSCertificate / Extensions
197                                 ASN1 extns = tbsCertificate.Element (tbs, 0xA3);
198                                 if ((extns != null) && (extns.Count == 1))
199                                         extensions = new X509ExtensionCollection (extns [0]);
200                                 else
201                                         extensions = new X509ExtensionCollection (null);
202
203                                 // keep a copy of the original data
204                                 m_encodedcert = (byte[]) data.Clone ();
205                         }
206                         catch (Exception ex) {
207                                 throw new CryptographicException (encoding_error, ex);
208                         }
209                 }
210
211                 // constructors
212
213                 public X509Certificate (byte[] data) 
214                 {
215                         if (data != null) {
216                                 // does it looks like PEM ?
217                                 if ((data.Length > 0) && (data [0] == 0x2D)) {
218                                         try {
219                                                 data = PEM ("CERTIFICATE", data);
220                                         }
221                                         catch (Exception ex) {
222                                                 throw new CryptographicException (encoding_error, ex);
223                                         }
224                                 }
225                                 Parse (data);
226                         }
227                 }
228
229                 private byte[] GetUnsignedBigInteger (byte[] integer) 
230                 {
231                         if (integer [0] == 0x00) {
232                                 // this first byte is added so we're sure it's an unsigned integer
233                                 // however we can't feed it into RSAParameters or DSAParameters
234                                 int length = integer.Length - 1;
235                                 byte[] uinteger = new byte [length];
236                                 Buffer.BlockCopy (integer, 1, uinteger, 0, length);
237                                 return uinteger;
238                         }
239                         else
240                                 return integer;
241                 }
242
243                 // public methods
244
245                 public DSA DSA {
246                         get {
247                                 if (_dsa == null) {
248                                         DSAParameters dsaParams = new DSAParameters ();
249                                         // for DSA m_publickey contains 1 ASN.1 integer - Y
250                                         ASN1 pubkey = new ASN1 (m_publickey);
251                                         if ((pubkey == null) || (pubkey.Tag != 0x02))
252                                                 return null;
253                                         dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
254
255                                         ASN1 param = new ASN1 (m_keyalgoparams);
256                                         if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
257                                                 return null;
258                                         if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
259                                                 return null;
260                                         dsaParams.P = GetUnsignedBigInteger (param [0].Value);
261                                         dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
262                                         dsaParams.G = GetUnsignedBigInteger (param [2].Value);
263
264                                         // BUG: MS BCL 1.0 can't import a key which 
265                                         // isn't the same size as the one present in
266                                         // the container.
267                                         _dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
268                                         _dsa.ImportParameters (dsaParams);
269                                 }
270                                 return _dsa; 
271                         }
272 #if NET_2_0
273                         set {
274                                 _dsa = value;
275                                 if (value != null)
276                                         _rsa = null;
277                         }
278 #endif
279                 }
280
281                 public X509ExtensionCollection Extensions {
282                         get { return extensions; }
283                 }
284
285                 public byte[] Hash {
286                         get {
287                                 if (certhash == null) {
288                                         HashAlgorithm hash = null;
289                                         switch (m_signaturealgo) {
290                                                 case "1.2.840.113549.1.1.2":    // MD2 with RSA encryption 
291                                                         // maybe someone installed MD2 ?
292 #if INSIDE_CORLIB
293                                                         hash = HashAlgorithm.Create ("MD2");
294 #else
295                                                         hash = Mono.Security.Cryptography.MD2.Create ();
296 #endif
297                                                         break;
298                                                 case "1.2.840.113549.1.1.4":    // MD5 with RSA encryption 
299                                                         hash = MD5.Create ();
300                                                         break;
301                                                 case "1.2.840.113549.1.1.5":    // SHA-1 with RSA Encryption 
302                                                 case "1.3.14.3.2.29":           // SHA1 with RSA signature 
303                                                 case "1.2.840.10040.4.3":       // SHA1-1 with DSA
304                                                         hash = SHA1.Create ();
305                                                         break;
306                                                 default:
307                                                         return null;
308                                         }
309                                         if ((decoder == null) || (decoder.Count < 1))
310                                                 return null;
311                                         byte[] toBeSigned = decoder [0].GetBytes ();
312                                         certhash = hash.ComputeHash (toBeSigned, 0, toBeSigned.Length);
313                                 }
314                                 return (byte[]) certhash.Clone ();
315                         }
316                 }
317
318                 public virtual string IssuerName {
319                         get { return m_issuername; }
320                 }
321
322                 public virtual string KeyAlgorithm {
323                         get { return m_keyalgo; }
324                 }
325
326                 public virtual byte[] KeyAlgorithmParameters {
327                         get {
328                                 if (m_keyalgoparams == null)
329                                         return null;
330                                 return (byte[]) m_keyalgoparams.Clone (); 
331                         }
332                 }
333
334                 public virtual byte[] PublicKey {
335                         get { 
336                                 if (m_publickey == null)
337                                         return null;
338                                 return (byte[]) m_publickey.Clone ();
339                         }
340                 }
341
342                 public virtual RSA RSA {
343                         get {
344                                 if (_rsa == null) {
345                                         RSAParameters rsaParams = new RSAParameters ();
346                                         // for RSA m_publickey contains 2 ASN.1 integers
347                                         // the modulus and the public exponent
348                                         ASN1 pubkey = new ASN1 (m_publickey);
349                                         ASN1 modulus = pubkey [0];
350                                         if ((modulus == null) || (modulus.Tag != 0x02))
351                                                 return null;
352                                         ASN1 exponent = pubkey [1];
353                                         if (exponent.Tag != 0x02)
354                                                 return null;
355
356                                         rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
357                                         rsaParams.Exponent = exponent.Value;
358
359                                         // BUG: MS BCL 1.0 can't import a key which 
360                                         // isn't the same size as the one present in
361                                         // the container.
362                                         int keySize = (rsaParams.Modulus.Length << 3);
363                                         _rsa = (RSA) new RSACryptoServiceProvider (keySize);
364                                         _rsa.ImportParameters (rsaParams);
365                                 }
366                                 return _rsa; 
367                         }
368 #if NET_2_0
369                         set {
370                                 if (value != null)
371                                         _dsa = null;
372                                 _rsa = value;
373                         }
374 #endif
375                 }
376                 
377                 public virtual byte[] RawData {
378                         get {
379                                 if (m_encodedcert == null)
380                                         return null;
381                                 return (byte[]) m_encodedcert.Clone ();
382                         }
383                 }
384
385                 public virtual byte[] SerialNumber {
386                         get { 
387                                 if (serialnumber == null)
388                                         return null;
389                                 return (byte[]) serialnumber.Clone (); 
390                         }
391                 }
392
393                 public virtual byte[] Signature {
394                         get { 
395                                 if (signature == null)
396                                         return null;
397
398                                 switch (m_signaturealgo) {
399                                         case "1.2.840.113549.1.1.2":    // MD2 with RSA encryption 
400                                         case "1.2.840.113549.1.1.4":    // MD5 with RSA encryption 
401                                         case "1.2.840.113549.1.1.5":    // SHA-1 with RSA Encryption 
402                                         case "1.3.14.3.2.29":           // SHA1 with RSA signature
403                                                 return (byte[]) signature.Clone ();
404
405                                         case "1.2.840.10040.4.3":       // SHA-1 with DSA
406                                                 ASN1 sign = new ASN1 (signature);
407                                                 if ((sign == null) || (sign.Count != 2))
408                                                         return null;
409                                                 // parts may be less than 20 bytes (i.e. first bytes were 0x00)
410                                                 byte[] part1 = sign [0].Value;
411                                                 byte[] part2 = sign [1].Value;
412                                                 byte[] sig = new byte [40];
413                                                 Buffer.BlockCopy (part1, 0, sig, (20 - part1.Length), part1.Length);
414                                                 Buffer.BlockCopy (part2, 0, sig, (40 - part2.Length), part2.Length);
415                                                 return sig;
416
417                                         default:
418                                                 throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
419                                 }
420                         }
421                 }
422
423                 public virtual string SignatureAlgorithm {
424                         get { return m_signaturealgo; }
425                 }
426
427                 public virtual byte[] SignatureAlgorithmParameters {
428                         get { 
429                                 if (m_signaturealgoparams == null)
430                                         return m_signaturealgoparams;
431                                 return (byte[]) m_signaturealgoparams.Clone ();
432                         }
433                 }
434
435                 public virtual string SubjectName {
436                         get { return m_subject; }
437                 }
438
439                 public virtual DateTime ValidFrom {
440                         get { return m_from; }
441                 }
442
443                 public virtual DateTime ValidUntil {
444                         get { return m_until; }
445                 }
446
447                 public int Version {
448                         get { return version; }
449                 }
450
451                 public bool IsCurrent {
452                         get { return WasCurrent (DateTime.Now); }
453                 }
454
455                 public bool WasCurrent (DateTime instant) 
456                 {
457                         return ((instant > ValidFrom) && (instant <= ValidUntil));
458                 }
459
460                 internal bool VerifySignature (DSA dsa) 
461                 {
462                         // signatureOID is check by both this.Hash and this.Signature
463                         DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
464                         // only SHA-1 is supported
465                         v.SetHashAlgorithm ("SHA1");
466                         return v.VerifySignature (this.Hash, this.Signature);
467                 }
468
469                 internal bool VerifySignature (RSA rsa) 
470                 {
471                         RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
472                         switch (m_signaturealgo) {
473                                 // MD2 with RSA encryption 
474                                 case "1.2.840.113549.1.1.2":
475                                         // maybe someone installed MD2 ?
476                                         v.SetHashAlgorithm ("MD2");
477                                         break;
478                                 // MD5 with RSA encryption 
479                                 case "1.2.840.113549.1.1.4":
480                                         v.SetHashAlgorithm ("MD5");
481                                         break;
482                                 // SHA-1 with RSA Encryption 
483                                 case "1.2.840.113549.1.1.5":
484                                 case "1.3.14.3.2.29":
485                                         v.SetHashAlgorithm ("SHA1");
486                                         break;
487                                 default:
488                                         throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
489                         }
490                         return v.VerifySignature (this.Hash, this.Signature);
491                 }
492
493                 public bool VerifySignature (AsymmetricAlgorithm aa) 
494                 {
495                         if (aa == null)
496                                 throw new ArgumentNullException ("aa");
497
498                         if (aa is RSA)
499                                 return VerifySignature (aa as RSA);
500                         else if (aa is DSA)
501                                 return VerifySignature (aa as DSA);
502                         else 
503                                 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
504                 }
505
506                 public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature) 
507                 {
508                         RSACryptoServiceProvider r = (RSACryptoServiceProvider) RSA;
509                         return r.VerifyHash (hash, hashAlgorithm, signature);
510                 }
511
512                 public bool IsSelfSigned {
513                         get { 
514                                 if (m_issuername == m_subject)
515                                         return VerifySignature (RSA); 
516                                 else
517                                         return false;
518                         }
519                 }
520
521 #if INSIDE_CORLIB || NET_2_0
522                 public ASN1 GetIssuerName ()
523                 {
524                         return issuer;
525                 }
526
527                 public ASN1 GetSubjectName ()
528                 {
529                         return subject;
530                 }
531
532                 protected X509Certificate (SerializationInfo info, StreamingContext context)
533                 {
534                         Parse ((byte[]) info.GetValue ("raw", typeof (byte[])));
535                 }
536
537                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
538                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
539                 {
540                         info.AddValue ("raw", m_encodedcert);
541                         // note: we NEVER serialize the private key
542                 }
543 #endif
544
545                 static byte[] PEM (string type, byte[] data) 
546                 {
547                         string pem = Encoding.ASCII.GetString (data);
548                         string header = String.Format ("-----BEGIN {0}-----", type);
549                         string footer = String.Format ("-----END {0}-----", type);
550                         int start = pem.IndexOf (header) + header.Length;
551                         int end = pem.IndexOf (footer, start);
552                         string base64 = pem.Substring (start, (end - start));
553                         return Convert.FromBase64String (base64);
554                 }
555         }
556 }