Add support for validating RSA-based X.509 certifcates using SHA256
[mono.git] / mcs / class / Mono.Security / 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 #else
48         public class X509Certificate : ISerializable {
49 #endif
50
51                 private ASN1 decoder;
52
53                 private byte[] m_encodedcert;
54                 private DateTime m_from;
55                 private DateTime m_until;
56                 private ASN1 issuer;
57                 private string m_issuername;
58                 private string m_keyalgo;
59                 private byte[] m_keyalgoparams;
60                 private ASN1 subject;
61                 private string m_subject;
62                 private byte[] m_publickey;
63                 private byte[] signature;
64                 private string m_signaturealgo;
65                 private byte[] m_signaturealgoparams;
66                 private byte[] certhash;
67                 private RSA _rsa;
68                 private DSA _dsa;
69                 
70                 // from http://www.ietf.org/rfc/rfc2459.txt
71                 //
72                 //Certificate  ::=  SEQUENCE  {
73                 //     tbsCertificate       TBSCertificate,
74                 //     signatureAlgorithm   AlgorithmIdentifier,
75                 //     signature            BIT STRING  }
76                 //
77                 //TBSCertificate  ::=  SEQUENCE  {
78                 //     version         [0]  Version DEFAULT v1,
79                 //     serialNumber         CertificateSerialNumber,
80                 //     signature            AlgorithmIdentifier,
81                 //     issuer               Name,
82                 //     validity             Validity,
83                 //     subject              Name,
84                 //     subjectPublicKeyInfo SubjectPublicKeyInfo,
85                 //     issuerUniqueID  [1]  IMPLICIT UniqueIdentifier OPTIONAL,
86                 //                          -- If present, version shall be v2 or v3
87                 //     subjectUniqueID [2]  IMPLICIT UniqueIdentifier OPTIONAL,
88                 //                          -- If present, version shall be v2 or v3
89                 //     extensions      [3]  Extensions OPTIONAL
90                 //                          -- If present, version shall be v3 --  }
91                 private int version;
92                 private byte[] serialnumber;
93
94                 private byte[] issuerUniqueID;
95                 private byte[] subjectUniqueID;
96                 private X509ExtensionCollection extensions;
97
98                 private static string encoding_error = Locale.GetText ("Input data cannot be coded as a valid certificate.");
99
100
101                 // that's were the real job is!
102                 private void Parse (byte[] data) 
103                 {
104                         try {
105                                 decoder = new ASN1 (data);
106                                 // Certificate 
107                                 if (decoder.Tag != 0x30)
108                                         throw new CryptographicException (encoding_error);
109                                 // Certificate / TBSCertificate
110                                 if (decoder [0].Tag != 0x30)
111                                         throw new CryptographicException (encoding_error);
112
113                                 ASN1 tbsCertificate = decoder [0];
114
115                                 int tbs = 0;
116                                 // Certificate / TBSCertificate / Version
117                                 ASN1 v = decoder [0][tbs];
118                                 version = 1;                    // DEFAULT v1
119                                 if ((v.Tag == 0xA0) && (v.Count > 0)) {
120                                         // version (optional) is present only in v2+ certs
121                                         version += v [0].Value [0];     // zero based
122                                         tbs++;
123                                 }
124
125                                 // Certificate / TBSCertificate / CertificateSerialNumber
126                                 ASN1 sn = decoder [0][tbs++];
127                                 if (sn.Tag != 0x02) 
128                                         throw new CryptographicException (encoding_error);
129                                 serialnumber = sn.Value;
130                                 Array.Reverse (serialnumber, 0, serialnumber.Length);
131                 
132                                 // Certificate / TBSCertificate / AlgorithmIdentifier
133                                 tbs++;
134                                 // ASN1 signatureAlgo = tbsCertificate.Element (tbs++, 0x30); 
135                 
136                                 issuer = tbsCertificate.Element (tbs++, 0x30); 
137                                 m_issuername = X501.ToString (issuer);
138                 
139                                 ASN1 validity = tbsCertificate.Element (tbs++, 0x30);
140                                 ASN1 notBefore = validity [0];
141                                 m_from = ASN1Convert.ToDateTime (notBefore);
142                                 ASN1 notAfter = validity [1];
143                                 m_until = ASN1Convert.ToDateTime (notAfter);
144                 
145                                 subject = tbsCertificate.Element (tbs++, 0x30);
146                                 m_subject = X501.ToString (subject);
147                 
148                                 ASN1 subjectPublicKeyInfo = tbsCertificate.Element (tbs++, 0x30);
149                 
150                                 ASN1 algorithm = subjectPublicKeyInfo.Element (0, 0x30);
151                                 ASN1 algo = algorithm.Element (0, 0x06);
152                                 m_keyalgo = ASN1Convert.ToOid (algo);
153                                 // parameters ANY DEFINED BY algorithm OPTIONAL
154                                 // so we dont ask for a specific (Element) type and return DER
155                                 ASN1 parameters = algorithm [1];
156                                 m_keyalgoparams = ((algorithm.Count > 1) ? parameters.GetBytes () : null);
157                 
158                                 ASN1 subjectPublicKey = subjectPublicKeyInfo.Element (1, 0x03); 
159                                 // we must drop th first byte (which is the number of unused bits
160                                 // in the BITSTRING)
161                                 int n = subjectPublicKey.Length - 1;
162                                 m_publickey = new byte [n];
163                                 Buffer.BlockCopy (subjectPublicKey.Value, 1, m_publickey, 0, n);
164
165                                 // signature processing
166                                 byte[] bitstring = decoder [2].Value;
167                                 // first byte contains unused bits in first byte
168                                 signature = new byte [bitstring.Length - 1];
169                                 Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
170
171                                 algorithm = decoder [1];
172                                 algo = algorithm.Element (0, 0x06);
173                                 m_signaturealgo = ASN1Convert.ToOid (algo);
174                                 parameters = algorithm [1];
175                                 if (parameters != null)
176                                         m_signaturealgoparams = parameters.GetBytes ();
177                                 else
178                                         m_signaturealgoparams = null;
179
180                                 // Certificate / TBSCertificate / issuerUniqueID
181                                 ASN1 issuerUID = tbsCertificate.Element (tbs, 0x81);
182                                 if (issuerUID != null) {
183                                         tbs++;
184                                         issuerUniqueID = issuerUID.Value;
185                                 }
186
187                                 // Certificate / TBSCertificate / subjectUniqueID
188                                 ASN1 subjectUID = tbsCertificate.Element (tbs, 0x82);
189                                 if (subjectUID != null) {
190                                         tbs++;
191                                         subjectUniqueID = subjectUID.Value;
192                                 }
193
194                                 // Certificate / TBSCertificate / Extensions
195                                 ASN1 extns = tbsCertificate.Element (tbs, 0xA3);
196                                 if ((extns != null) && (extns.Count == 1))
197                                         extensions = new X509ExtensionCollection (extns [0]);
198                                 else
199                                         extensions = new X509ExtensionCollection (null);
200
201                                 // keep a copy of the original data
202                                 m_encodedcert = (byte[]) data.Clone ();
203                         }
204                         catch (Exception ex) {
205                                 throw new CryptographicException (encoding_error, ex);
206                         }
207                 }
208
209                 // constructors
210
211                 public X509Certificate (byte[] data) 
212                 {
213                         if (data != null) {
214                                 // does it looks like PEM ?
215                                 if ((data.Length > 0) && (data [0] != 0x30)) {
216                                         try {
217                                                 data = PEM ("CERTIFICATE", data);
218                                         }
219                                         catch (Exception ex) {
220                                                 throw new CryptographicException (encoding_error, ex);
221                                         }
222                                 }
223                                 Parse (data);
224                         }
225                 }
226
227                 private byte[] GetUnsignedBigInteger (byte[] integer) 
228                 {
229                         if (integer [0] == 0x00) {
230                                 // this first byte is added so we're sure it's an unsigned integer
231                                 // however we can't feed it into RSAParameters or DSAParameters
232                                 int length = integer.Length - 1;
233                                 byte[] uinteger = new byte [length];
234                                 Buffer.BlockCopy (integer, 1, uinteger, 0, length);
235                                 return uinteger;
236                         }
237                         else
238                                 return integer;
239                 }
240
241                 // public methods
242
243                 public DSA DSA {
244                         get {
245                                 if (m_keyalgoparams == null)
246                                         throw new CryptographicException ("Missing key algorithm parameters.");
247
248                                 if (_dsa == null) {
249                                         DSAParameters dsaParams = new DSAParameters ();
250                                         // for DSA m_publickey contains 1 ASN.1 integer - Y
251                                         ASN1 pubkey = new ASN1 (m_publickey);
252                                         if ((pubkey == null) || (pubkey.Tag != 0x02))
253                                                 return null;
254                                         dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
255
256                                         ASN1 param = new ASN1 (m_keyalgoparams);
257                                         if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
258                                                 return null;
259                                         if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
260                                                 return null;
261                                         dsaParams.P = GetUnsignedBigInteger (param [0].Value);
262                                         dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
263                                         dsaParams.G = GetUnsignedBigInteger (param [2].Value);
264
265                                         // BUG: MS BCL 1.0 can't import a key which 
266                                         // isn't the same size as the one present in
267                                         // the container.
268                                         _dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
269                                         _dsa.ImportParameters (dsaParams);
270                                 }
271                                 return _dsa; 
272                         }
273
274                         set {
275                                 _dsa = value;
276                                 if (value != null)
277                                         _rsa = null;
278                         }
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                                                 case "1.2.840.113549.1.1.11":   // SHA-256 with RSA Encryption
307                                                         hash = SHA256.Create ();
308                                                         break;
309                                                 default:
310                                                         return null;
311                                         }
312                                         if ((decoder == null) || (decoder.Count < 1))
313                                                 return null;
314                                         byte[] toBeSigned = decoder [0].GetBytes ();
315                                         certhash = hash.ComputeHash (toBeSigned, 0, toBeSigned.Length);
316                                 }
317                                 return (byte[]) certhash.Clone ();
318                         }
319                 }
320
321                 public virtual string IssuerName {
322                         get { return m_issuername; }
323                 }
324
325                 public virtual string KeyAlgorithm {
326                         get { return m_keyalgo; }
327                 }
328
329                 public virtual byte[] KeyAlgorithmParameters {
330                         get {
331                                 if (m_keyalgoparams == null)
332                                         return null;
333                                 return (byte[]) m_keyalgoparams.Clone (); 
334                         }
335                         set { m_keyalgoparams = value; }
336                 }
337
338                 public virtual byte[] PublicKey {
339                         get { 
340                                 if (m_publickey == null)
341                                         return null;
342                                 return (byte[]) m_publickey.Clone ();
343                         }
344                 }
345
346                 public virtual RSA RSA {
347                         get {
348                                 if (_rsa == null) {
349                                         RSAParameters rsaParams = new RSAParameters ();
350                                         // for RSA m_publickey contains 2 ASN.1 integers
351                                         // the modulus and the public exponent
352                                         ASN1 pubkey = new ASN1 (m_publickey);
353                                         ASN1 modulus = pubkey [0];
354                                         if ((modulus == null) || (modulus.Tag != 0x02))
355                                                 return null;
356                                         ASN1 exponent = pubkey [1];
357                                         if (exponent.Tag != 0x02)
358                                                 return null;
359
360                                         rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
361                                         rsaParams.Exponent = exponent.Value;
362
363                                         // BUG: MS BCL 1.0 can't import a key which 
364                                         // isn't the same size as the one present in
365                                         // the container.
366                                         int keySize = (rsaParams.Modulus.Length << 3);
367                                         _rsa = (RSA) new RSACryptoServiceProvider (keySize);
368                                         _rsa.ImportParameters (rsaParams);
369                                 }
370                                 return _rsa; 
371                         }
372
373                         set {
374                                 if (value != null)
375                                         _dsa = null;
376                                 _rsa = value;
377                         }
378                 }
379                 
380                 public virtual byte[] RawData {
381                         get {
382                                 if (m_encodedcert == null)
383                                         return null;
384                                 return (byte[]) m_encodedcert.Clone ();
385                         }
386                 }
387
388                 public virtual byte[] SerialNumber {
389                         get { 
390                                 if (serialnumber == null)
391                                         return null;
392                                 return (byte[]) serialnumber.Clone (); 
393                         }
394                 }
395
396                 public virtual byte[] Signature {
397                         get { 
398                                 if (signature == null)
399                                         return null;
400
401                                 switch (m_signaturealgo) {
402                                         case "1.2.840.113549.1.1.2":    // MD2 with RSA encryption 
403                                         case "1.2.840.113549.1.1.4":    // MD5 with RSA encryption 
404                                         case "1.2.840.113549.1.1.5":    // SHA-1 with RSA Encryption 
405                                         case "1.3.14.3.2.29":           // SHA1 with RSA signature
406                                         case "1.2.840.113549.1.1.11":   // SHA-256 with RSA Encryption
407                                                 return (byte[]) signature.Clone ();
408
409                                         case "1.2.840.10040.4.3":       // SHA-1 with DSA
410                                                 ASN1 sign = new ASN1 (signature);
411                                                 if ((sign == null) || (sign.Count != 2))
412                                                         return null;
413                                                 byte[] part1 = sign [0].Value;
414                                                 byte[] part2 = sign [1].Value;
415                                                 byte[] sig = new byte [40];
416                                                 // parts may be less than 20 bytes (i.e. first bytes were 0x00)
417                                                 // parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
418                                                 int s1 = System.Math.Max (0, part1.Length - 20);
419                                                 int e1 = System.Math.Max (0, 20 - part1.Length);
420                                                 Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
421                                                 int s2 = System.Math.Max (0, part2.Length - 20);
422                                                 int e2 = System.Math.Max (20, 40 - part2.Length);
423                                                 Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
424                                                 return sig;
425
426                                         default:
427                                                 throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
428                                 }
429                         }
430                 }
431
432                 public virtual string SignatureAlgorithm {
433                         get { return m_signaturealgo; }
434                 }
435
436                 public virtual byte[] SignatureAlgorithmParameters {
437                         get { 
438                                 if (m_signaturealgoparams == null)
439                                         return m_signaturealgoparams;
440                                 return (byte[]) m_signaturealgoparams.Clone ();
441                         }
442                 }
443
444                 public virtual string SubjectName {
445                         get { return m_subject; }
446                 }
447
448                 public virtual DateTime ValidFrom {
449                         get { return m_from; }
450                 }
451
452                 public virtual DateTime ValidUntil {
453                         get { return m_until; }
454                 }
455
456                 public int Version {
457                         get { return version; }
458                 }
459
460                 public bool IsCurrent {
461                         get { return WasCurrent (DateTime.UtcNow); }
462                 }
463
464                 public bool WasCurrent (DateTime instant) 
465                 {
466                         return ((instant > ValidFrom) && (instant <= ValidUntil));
467                 }
468
469                 // uncommon v2 "extension"
470                 public byte[] IssuerUniqueIdentifier {
471                         get {
472                                 if (issuerUniqueID == null)
473                                         return null;
474                                 return (byte[]) issuerUniqueID.Clone ();
475                         }
476                 }
477
478                 // uncommon v2 "extension"
479                 public byte[] SubjectUniqueIdentifier {
480                         get {
481                                 if (subjectUniqueID == null)
482                                         return null;
483                                 return (byte[]) subjectUniqueID.Clone ();
484                         }
485                 }
486
487                 internal bool VerifySignature (DSA dsa) 
488                 {
489                         // signatureOID is check by both this.Hash and this.Signature
490                         DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
491                         // only SHA-1 is supported
492                         v.SetHashAlgorithm ("SHA1");
493                         return v.VerifySignature (this.Hash, this.Signature);
494                 }
495
496                 internal bool VerifySignature (RSA rsa) 
497                 {
498                         RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
499                         switch (m_signaturealgo) {
500                                 // MD2 with RSA encryption 
501                                 case "1.2.840.113549.1.1.2":
502                                         // maybe someone installed MD2 ?
503                                         v.SetHashAlgorithm ("MD2");
504                                         break;
505                                 // MD5 with RSA encryption 
506                                 case "1.2.840.113549.1.1.4":
507                                         v.SetHashAlgorithm ("MD5");
508                                         break;
509                                 // SHA-1 with RSA Encryption 
510                                 case "1.2.840.113549.1.1.5":
511                                 case "1.3.14.3.2.29":
512                                         v.SetHashAlgorithm ("SHA1");
513                                         break;
514                                 // SHA-256 with RSA Encryption 
515                                 case "1.2.840.113549.1.1.11":
516                                         v.SetHashAlgorithm ("SHA256");
517                                         break;
518                                 default:
519                                         throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
520                         }
521                         return v.VerifySignature (this.Hash, this.Signature);
522                 }
523
524                 public bool VerifySignature (AsymmetricAlgorithm aa) 
525                 {
526                         if (aa == null)
527                                 throw new ArgumentNullException ("aa");
528
529                         if (aa is RSA)
530                                 return VerifySignature (aa as RSA);
531                         else if (aa is DSA)
532                                 return VerifySignature (aa as DSA);
533                         else 
534                                 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
535                 }
536
537                 public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature) 
538                 {
539                         RSACryptoServiceProvider r = (RSACryptoServiceProvider) RSA;
540                         return r.VerifyHash (hash, hashAlgorithm, signature);
541                 }
542
543                 public bool IsSelfSigned {
544                         get { 
545                                 if (m_issuername != m_subject)
546                                         return false;
547
548                                 try {
549                                         if (RSA != null)
550                                                 return VerifySignature (RSA);
551                                         else if (DSA != null)
552                                                 return VerifySignature (DSA);
553                                         else
554                                                 return false; // e.g. a certificate with only DSA parameters
555                                 }
556                                 catch (CryptographicException) {
557                                         return false;
558                                 }
559                         }
560                 }
561
562                 public ASN1 GetIssuerName ()
563                 {
564                         return issuer;
565                 }
566
567                 public ASN1 GetSubjectName ()
568                 {
569                         return subject;
570                 }
571
572                 protected X509Certificate (SerializationInfo info, StreamingContext context)
573                 {
574                         Parse ((byte[]) info.GetValue ("raw", typeof (byte[])));
575                 }
576
577                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
578                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
579                 {
580                         info.AddValue ("raw", m_encodedcert);
581                         // note: we NEVER serialize the private key
582                 }
583
584                 static byte[] PEM (string type, byte[] data) 
585                 {
586                         string pem = Encoding.ASCII.GetString (data);
587                         string header = String.Format ("-----BEGIN {0}-----", type);
588                         string footer = String.Format ("-----END {0}-----", type);
589                         int start = pem.IndexOf (header) + header.Length;
590                         int end = pem.IndexOf (footer, start);
591                         string base64 = pem.Substring (start, (end - start));
592                         return Convert.FromBase64String (base64);
593                 }
594         }
595 }