Merge pull request #642 from Ventero/CleanCopyLocal
[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@xamarin.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 // Copyright 2013 Xamarin Inc. (http://www.xamarin.com)
10 //
11 // Permission is hereby granted, free of charge, to any person obtaining
12 // a copy of this software and associated documentation files (the
13 // "Software"), to deal in the Software without restriction, including
14 // without limitation the rights to use, copy, modify, merge, publish,
15 // distribute, sublicense, and/or sell copies of the Software, and to
16 // permit persons to whom the Software is furnished to do so, subject to
17 // the following conditions:
18 // 
19 // The above copyright notice and this permission notice shall be
20 // included in all copies or substantial portions of the Software.
21 // 
22 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
23 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
24 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
25 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
26 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
27 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
28 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
29 //
30
31 using System;
32 using System.Runtime.Serialization;
33 using System.Security.Cryptography;
34 using SSCX = System.Security.Cryptography.X509Certificates;
35 using System.Security.Permissions;
36 using System.Text;
37 using Mono.Security.Cryptography;
38
39 namespace Mono.Security.X509 {
40
41         // References:
42         // a.   Internet X.509 Public Key Infrastructure Certificate and CRL Profile
43         //      http://www.ietf.org/rfc/rfc3280.txt
44         // b.   ITU ASN.1 standards (free download)
45         //      http://www.itu.int/ITU-T/studygroups/com17/languages/
46
47 #if INSIDE_CORLIB
48         internal class X509Certificate : ISerializable {
49 #else
50         public class X509Certificate : ISerializable {
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, 0x81);
184                                 if (issuerUID != null) {
185                                         tbs++;
186                                         issuerUniqueID = issuerUID.Value;
187                                 }
188
189                                 // Certificate / TBSCertificate / subjectUniqueID
190                                 ASN1 subjectUID = tbsCertificate.Element (tbs, 0x82);
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] != 0x30)) {
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 (m_keyalgoparams == null)
248                                         throw new CryptographicException ("Missing key algorithm parameters.");
249
250                                 if (_dsa == null) {
251                                         DSAParameters dsaParams = new DSAParameters ();
252                                         // for DSA m_publickey contains 1 ASN.1 integer - Y
253                                         ASN1 pubkey = new ASN1 (m_publickey);
254                                         if ((pubkey == null) || (pubkey.Tag != 0x02))
255                                                 return null;
256                                         dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
257
258                                         ASN1 param = new ASN1 (m_keyalgoparams);
259                                         if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
260                                                 return null;
261                                         if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
262                                                 return null;
263                                         dsaParams.P = GetUnsignedBigInteger (param [0].Value);
264                                         dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
265                                         dsaParams.G = GetUnsignedBigInteger (param [2].Value);
266
267                                         // BUG: MS BCL 1.0 can't import a key which 
268                                         // isn't the same size as the one present in
269                                         // the container.
270                                         _dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
271                                         _dsa.ImportParameters (dsaParams);
272                                 }
273                                 return _dsa; 
274                         }
275
276                         set {
277                                 _dsa = value;
278                                 if (value != null)
279                                         _rsa = null;
280                         }
281                 }
282
283                 public X509ExtensionCollection Extensions {
284                         get { return extensions; }
285                 }
286
287                 public byte[] Hash {
288                         get {
289                                 if (certhash == null) {
290                                         if ((decoder == null) || (decoder.Count < 1))
291                                                 return null;
292                                         string algo = PKCS1.HashNameFromOid (m_signaturealgo, false);
293                                         if (algo == null)
294                                                 return null;
295                                         byte[] toBeSigned = decoder [0].GetBytes ();
296                                         using (var hash = PKCS1.CreateFromName (algo))
297                                                 certhash = hash.ComputeHash (toBeSigned, 0, toBeSigned.Length);
298                                 }
299                                 return (byte[]) certhash.Clone ();
300                         }
301                 }
302
303                 public virtual string IssuerName {
304                         get { return m_issuername; }
305                 }
306
307                 public virtual string KeyAlgorithm {
308                         get { return m_keyalgo; }
309                 }
310
311                 public virtual byte[] KeyAlgorithmParameters {
312                         get {
313                                 if (m_keyalgoparams == null)
314                                         return null;
315                                 return (byte[]) m_keyalgoparams.Clone (); 
316                         }
317                         set { m_keyalgoparams = value; }
318                 }
319
320                 public virtual byte[] PublicKey {
321                         get { 
322                                 if (m_publickey == null)
323                                         return null;
324                                 return (byte[]) m_publickey.Clone ();
325                         }
326                 }
327
328                 public virtual RSA RSA {
329                         get {
330                                 if (_rsa == null) {
331                                         RSAParameters rsaParams = new RSAParameters ();
332                                         // for RSA m_publickey contains 2 ASN.1 integers
333                                         // the modulus and the public exponent
334                                         ASN1 pubkey = new ASN1 (m_publickey);
335                                         ASN1 modulus = pubkey [0];
336                                         if ((modulus == null) || (modulus.Tag != 0x02))
337                                                 return null;
338                                         ASN1 exponent = pubkey [1];
339                                         if (exponent.Tag != 0x02)
340                                                 return null;
341
342                                         rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
343                                         rsaParams.Exponent = exponent.Value;
344
345                                         // BUG: MS BCL 1.0 can't import a key which 
346                                         // isn't the same size as the one present in
347                                         // the container.
348                                         int keySize = (rsaParams.Modulus.Length << 3);
349                                         _rsa = (RSA) new RSACryptoServiceProvider (keySize);
350                                         _rsa.ImportParameters (rsaParams);
351                                 }
352                                 return _rsa; 
353                         }
354
355                         set {
356                                 if (value != null)
357                                         _dsa = null;
358                                 _rsa = value;
359                         }
360                 }
361                 
362                 public virtual byte[] RawData {
363                         get {
364                                 if (m_encodedcert == null)
365                                         return null;
366                                 return (byte[]) m_encodedcert.Clone ();
367                         }
368                 }
369
370                 public virtual byte[] SerialNumber {
371                         get { 
372                                 if (serialnumber == null)
373                                         return null;
374                                 return (byte[]) serialnumber.Clone (); 
375                         }
376                 }
377
378                 public virtual byte[] Signature {
379                         get { 
380                                 if (signature == null)
381                                         return null;
382
383                                 switch (m_signaturealgo) {
384                                         case "1.2.840.113549.1.1.2":    // MD2 with RSA encryption 
385                                         case "1.2.840.113549.1.1.3":    // MD4 with RSA encryption 
386                                         case "1.2.840.113549.1.1.4":    // MD5 with RSA encryption 
387                                         case "1.2.840.113549.1.1.5":    // SHA-1 with RSA Encryption 
388                                         case "1.3.14.3.2.29":           // SHA1 with RSA signature
389                                         case "1.2.840.113549.1.1.11":   // SHA-256 with RSA Encryption
390                                         case "1.2.840.113549.1.1.12":   // SHA-384 with RSA Encryption
391                                         case "1.2.840.113549.1.1.13":   // SHA-512 with RSA Encryption
392                                         case "1.3.36.3.3.1.2":                  // RIPEMD160 with RSA Encryption
393                                                 return (byte[]) signature.Clone ();
394
395                                         case "1.2.840.10040.4.3":       // SHA-1 with DSA
396                                                 ASN1 sign = new ASN1 (signature);
397                                                 if ((sign == null) || (sign.Count != 2))
398                                                         return null;
399                                                 byte[] part1 = sign [0].Value;
400                                                 byte[] part2 = sign [1].Value;
401                                                 byte[] sig = new byte [40];
402                                                 // parts may be less than 20 bytes (i.e. first bytes were 0x00)
403                                                 // parts may be more than 20 bytes (i.e. first byte > 0x80, negative)
404                                                 int s1 = System.Math.Max (0, part1.Length - 20);
405                                                 int e1 = System.Math.Max (0, 20 - part1.Length);
406                                                 Buffer.BlockCopy (part1, s1, sig, e1, part1.Length - s1);
407                                                 int s2 = System.Math.Max (0, part2.Length - 20);
408                                                 int e2 = System.Math.Max (20, 40 - part2.Length);
409                                                 Buffer.BlockCopy (part2, s2, sig, e2, part2.Length - s2);
410                                                 return sig;
411
412                                         default:
413                                                 throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
414                                 }
415                         }
416                 }
417
418                 public virtual string SignatureAlgorithm {
419                         get { return m_signaturealgo; }
420                 }
421
422                 public virtual byte[] SignatureAlgorithmParameters {
423                         get { 
424                                 if (m_signaturealgoparams == null)
425                                         return m_signaturealgoparams;
426                                 return (byte[]) m_signaturealgoparams.Clone ();
427                         }
428                 }
429
430                 public virtual string SubjectName {
431                         get { return m_subject; }
432                 }
433
434                 public virtual DateTime ValidFrom {
435                         get { return m_from; }
436                 }
437
438                 public virtual DateTime ValidUntil {
439                         get { return m_until; }
440                 }
441
442                 public int Version {
443                         get { return version; }
444                 }
445
446                 public bool IsCurrent {
447                         get { return WasCurrent (DateTime.UtcNow); }
448                 }
449
450                 public bool WasCurrent (DateTime instant) 
451                 {
452                         return ((instant > ValidFrom) && (instant <= ValidUntil));
453                 }
454
455                 // uncommon v2 "extension"
456                 public byte[] IssuerUniqueIdentifier {
457                         get {
458                                 if (issuerUniqueID == null)
459                                         return null;
460                                 return (byte[]) issuerUniqueID.Clone ();
461                         }
462                 }
463
464                 // uncommon v2 "extension"
465                 public byte[] SubjectUniqueIdentifier {
466                         get {
467                                 if (subjectUniqueID == null)
468                                         return null;
469                                 return (byte[]) subjectUniqueID.Clone ();
470                         }
471                 }
472
473                 internal bool VerifySignature (DSA dsa) 
474                 {
475                         // signatureOID is check by both this.Hash and this.Signature
476                         DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
477                         // only SHA-1 is supported
478                         v.SetHashAlgorithm ("SHA1");
479                         return v.VerifySignature (this.Hash, this.Signature);
480                 }
481
482                 internal bool VerifySignature (RSA rsa) 
483                 {
484                         // SHA1-1 with DSA
485                         if (m_signaturealgo == "1.2.840.10040.4.3")
486                                 return false;
487                         RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
488                         v.SetHashAlgorithm (PKCS1.HashNameFromOid (m_signaturealgo));
489                         return v.VerifySignature (this.Hash, this.Signature);
490                 }
491
492                 public bool VerifySignature (AsymmetricAlgorithm aa) 
493                 {
494                         if (aa == null)
495                                 throw new ArgumentNullException ("aa");
496
497                         if (aa is RSA)
498                                 return VerifySignature (aa as RSA);
499                         else if (aa is DSA)
500                                 return VerifySignature (aa as DSA);
501                         else 
502                                 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
503                 }
504
505                 public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature) 
506                 {
507                         RSACryptoServiceProvider r = (RSACryptoServiceProvider) RSA;
508                         return r.VerifyHash (hash, hashAlgorithm, signature);
509                 }
510
511                 public bool IsSelfSigned {
512                         get { 
513                                 if (m_issuername != m_subject)
514                                         return false;
515
516                                 try {
517                                         if (RSA != null)
518                                                 return VerifySignature (RSA);
519                                         else if (DSA != null)
520                                                 return VerifySignature (DSA);
521                                         else
522                                                 return false; // e.g. a certificate with only DSA parameters
523                                 }
524                                 catch (CryptographicException) {
525                                         return false;
526                                 }
527                         }
528                 }
529
530                 public ASN1 GetIssuerName ()
531                 {
532                         return issuer;
533                 }
534
535                 public ASN1 GetSubjectName ()
536                 {
537                         return subject;
538                 }
539
540                 protected X509Certificate (SerializationInfo info, StreamingContext context)
541                 {
542                         Parse ((byte[]) info.GetValue ("raw", typeof (byte[])));
543                 }
544
545                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
546                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
547                 {
548                         info.AddValue ("raw", m_encodedcert);
549                         // note: we NEVER serialize the private key
550                 }
551
552                 static byte[] PEM (string type, byte[] data) 
553                 {
554                         string pem = Encoding.ASCII.GetString (data);
555                         string header = String.Format ("-----BEGIN {0}-----", type);
556                         string footer = String.Format ("-----END {0}-----", type);
557                         int start = pem.IndexOf (header) + header.Length;
558                         int end = pem.IndexOf (footer, start);
559                         string base64 = pem.Substring (start, (end - start));
560                         return Convert.FromBase64String (base64);
561                 }
562         }
563 }