d351bd06c1c8941169d0b6371d878d8f2b7571be
[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 #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 #if NET_2_0
101                 private const bool reversed = true;
102 #else
103                 private const bool reversed = false;
104 #endif
105
106                 // that's were the real job is!
107                 private void Parse (byte[] data) 
108                 {
109                         string e = "Input data cannot be coded as a valid certificate.";
110                         try {
111                                 decoder = new ASN1 (data);
112                                 // Certificate 
113                                 if (decoder.Tag != 0x30)
114                                         throw new CryptographicException (e);
115                                 // Certificate / TBSCertificate
116                                 if (decoder [0].Tag != 0x30)
117                                         throw new CryptographicException (e);
118
119                                 ASN1 tbsCertificate = decoder [0];
120
121                                 int tbs = 0;
122                                 // Certificate / TBSCertificate / Version
123                                 ASN1 v = decoder [0][tbs];
124                                 version = 1;                    // DEFAULT v1
125                                 if ((v.Tag == 0xA0) && (v.Count > 0)) {
126                                         // version (optional) is present only in v2+ certs
127                                         version += v [0].Value [0];     // zero based
128                                         tbs++;
129                                 }
130
131                                 // Certificate / TBSCertificate / CertificateSerialNumber
132                                 ASN1 sn = decoder [0][tbs++];
133                                 if (sn.Tag != 0x02) 
134                                         throw new CryptographicException (e);
135                                 serialnumber = sn.Value;
136                                 Array.Reverse (serialnumber, 0, serialnumber.Length);
137                 
138                                 // Certificate / TBSCertificate / AlgorithmIdentifier
139                                 tbs++;
140                                 // ASN1 signatureAlgo = tbsCertificate.Element (tbs++, 0x30); 
141                 
142                                 issuer = tbsCertificate.Element (tbs++, 0x30); 
143                                 m_issuername = X501.ToString (issuer);
144                 
145                                 ASN1 validity = tbsCertificate.Element (tbs++, 0x30);
146                                 ASN1 notBefore = validity [0];
147                                 m_from = ASN1Convert.ToDateTime (notBefore);
148                                 ASN1 notAfter = validity [1];
149                                 m_until = ASN1Convert.ToDateTime (notAfter);
150                 
151                                 subject = tbsCertificate.Element (tbs++, 0x30);
152                                 m_subject = X501.ToString (subject);
153                 
154                                 ASN1 subjectPublicKeyInfo = tbsCertificate.Element (tbs++, 0x30);
155                 
156                                 ASN1 algorithm = subjectPublicKeyInfo.Element (0, 0x30);
157                                 ASN1 algo = algorithm.Element (0, 0x06);
158                                 m_keyalgo = ASN1Convert.ToOid (algo);
159                                 // parameters ANY DEFINED BY algorithm OPTIONAL
160                                 // so we dont ask for a specific (Element) type and return DER
161                                 ASN1 parameters = algorithm [1];
162                                 m_keyalgoparams = ((algorithm.Count > 1) ? parameters.GetBytes () : null);
163                 
164                                 ASN1 subjectPublicKey = subjectPublicKeyInfo.Element (1, 0x03); 
165                                 // we must drop th first byte (which is the number of unused bits
166                                 // in the BITSTRING)
167                                 int n = subjectPublicKey.Length - 1;
168                                 m_publickey = new byte [n];
169                                 Buffer.BlockCopy (subjectPublicKey.Value, 1, m_publickey, 0, n);
170
171                                 // signature processing
172                                 byte[] bitstring = decoder [2].Value;
173                                 // first byte contains unused bits in first byte
174                                 signature = new byte [bitstring.Length - 1];
175                                 Buffer.BlockCopy (bitstring, 1, signature, 0, signature.Length);
176
177                                 algorithm = decoder [1];
178                                 algo = algorithm.Element (0, 0x06);
179                                 m_signaturealgo = ASN1Convert.ToOid (algo);
180                                 parameters = algorithm [1];
181                                 if (parameters != null)
182                                         m_signaturealgoparams = parameters.GetBytes ();
183                                 else
184                                         m_signaturealgoparams = null;
185
186                                 // Certificate / TBSCertificate / issuerUniqueID
187                                 ASN1 issuerUID = tbsCertificate.Element (tbs, 0xA1);
188                                 if (issuerUID != null) {
189                                         tbs++;
190 //                                      issuerUniqueID = issuerUID.Value;
191                                 }
192
193                                 // Certificate / TBSCertificate / subjectUniqueID
194                                 ASN1 subjectUID = tbsCertificate.Element (tbs, 0xA2);
195                                 if (subjectUID != null) {
196                                         tbs++;
197 //                                      subjectUniqueID = subjectUID.Value;
198                                 }
199
200                                 // Certificate / TBSCertificate / Extensions
201                                 ASN1 extns = tbsCertificate.Element (tbs, 0xA3);
202                                 if ((extns != null) && (extns.Count == 1))
203                                         extensions = new X509ExtensionCollection (extns [0]);
204                                 else
205                                         extensions = new X509ExtensionCollection (null);
206
207                                 // keep a copy of the original data
208                                 m_encodedcert = (byte[]) data.Clone ();
209                         }
210                         catch (Exception ex) {
211                                 throw new CryptographicException (e, ex);
212                         }
213                 }
214
215                 // constructors
216
217                 public X509Certificate (byte[] data) 
218                 {
219                         if (data != null)
220                                 Parse (data);
221                 }
222
223                 private byte[] GetUnsignedBigInteger (byte[] integer) 
224                 {
225                         if (integer [0] == 0x00) {
226                                 // this first byte is added so we're sure it's an unsigned integer
227                                 // however we can't feed it into RSAParameters or DSAParameters
228                                 int length = integer.Length - 1;
229                                 byte[] uinteger = new byte [length];
230                                 Buffer.BlockCopy (integer, 1, uinteger, 0, length);
231                                 return uinteger;
232                         }
233                         else
234                                 return integer;
235                 }
236
237                 // public methods
238
239                 public DSA DSA {
240                         get {
241                                 if (_dsa == null) {
242                                         DSAParameters dsaParams = new DSAParameters ();
243                                         // for DSA m_publickey contains 1 ASN.1 integer - Y
244                                         ASN1 pubkey = new ASN1 (m_publickey);
245                                         if ((pubkey == null) || (pubkey.Tag != 0x02))
246                                                 return null;
247                                         dsaParams.Y = GetUnsignedBigInteger (pubkey.Value);
248
249                                         ASN1 param = new ASN1 (m_keyalgoparams);
250                                         if ((param == null) || (param.Tag != 0x30) || (param.Count < 3))
251                                                 return null;
252                                         if ((param [0].Tag != 0x02) || (param [1].Tag != 0x02) || (param [2].Tag != 0x02))
253                                                 return null;
254                                         dsaParams.P = GetUnsignedBigInteger (param [0].Value);
255                                         dsaParams.Q = GetUnsignedBigInteger (param [1].Value);
256                                         dsaParams.G = GetUnsignedBigInteger (param [2].Value);
257
258                                         // BUG: MS BCL 1.0 can't import a key which 
259                                         // isn't the same size as the one present in
260                                         // the container.
261                                         _dsa = (DSA) new DSACryptoServiceProvider (dsaParams.Y.Length << 3);
262                                         _dsa.ImportParameters (dsaParams);
263                                 }
264                                 return _dsa; 
265                         }
266 #if NET_2_0
267                         set {
268                                 _dsa = value;
269                                 if (value != null)
270                                         _rsa = null;
271                         }
272 #endif
273                 }
274
275                 public X509ExtensionCollection Extensions {
276                         get { return extensions; }
277                 }
278
279                 public byte[] Hash {
280                         get {
281                                 if (certhash == null) {
282                                         HashAlgorithm hash = null;
283                                         switch (m_signaturealgo) {
284                                                 case "1.2.840.113549.1.1.2":    // MD2 with RSA encryption 
285                                                         // maybe someone installed MD2 ?
286 #if INSIDE_CORLIB
287                                                         hash = HashAlgorithm.Create ("MD2");
288 #else
289                                                         hash = Mono.Security.Cryptography.MD2.Create ();
290 #endif
291                                                         break;
292                                                 case "1.2.840.113549.1.1.4":    // MD5 with RSA encryption 
293                                                         hash = MD5.Create ();
294                                                         break;
295                                                 case "1.2.840.113549.1.1.5":    // SHA-1 with RSA Encryption 
296                                                 case "1.3.14.3.2.29":           // SHA1 with RSA signature 
297                                                 case "1.2.840.10040.4.3":       // SHA1-1 with DSA
298                                                         hash = SHA1.Create ();
299                                                         break;
300                                                 default:
301                                                         return null;
302                                         }
303                                         if ((decoder == null) || (decoder.Count < 1))
304                                                 return null;
305                                         byte[] toBeSigned = decoder [0].GetBytes ();
306                                         certhash = hash.ComputeHash (toBeSigned, 0, toBeSigned.Length);
307                                 }
308                                 return (byte[]) certhash.Clone ();
309                         }
310                 }
311
312                 public virtual string IssuerName {
313                         get { return m_issuername; }
314                 }
315
316                 public virtual string KeyAlgorithm {
317                         get { return m_keyalgo; }
318                 }
319
320                 public virtual byte[] KeyAlgorithmParameters {
321                         get {
322                                 if (m_keyalgoparams == null)
323                                         return null;
324                                 return (byte[]) m_keyalgoparams.Clone (); 
325                         }
326                 }
327
328                 public virtual byte[] PublicKey {
329                         get { 
330                                 if (m_publickey == null)
331                                         return null;
332                                 return (byte[]) m_publickey.Clone ();
333                         }
334                 }
335
336                 public virtual RSA RSA {
337                         get {
338                                 if (_rsa == null) {
339                                         RSAParameters rsaParams = new RSAParameters ();
340                                         // for RSA m_publickey contains 2 ASN.1 integers
341                                         // the modulus and the public exponent
342                                         ASN1 pubkey = new ASN1 (m_publickey);
343                                         ASN1 modulus = pubkey [0];
344                                         if ((modulus == null) || (modulus.Tag != 0x02))
345                                                 return null;
346                                         ASN1 exponent = pubkey [1];
347                                         if (exponent.Tag != 0x02)
348                                                 return null;
349
350                                         rsaParams.Modulus = GetUnsignedBigInteger (modulus.Value);
351                                         rsaParams.Exponent = exponent.Value;
352
353                                         // BUG: MS BCL 1.0 can't import a key which 
354                                         // isn't the same size as the one present in
355                                         // the container.
356                                         int keySize = (rsaParams.Modulus.Length << 3);
357                                         _rsa = (RSA) new RSACryptoServiceProvider (keySize);
358                                         _rsa.ImportParameters (rsaParams);
359                                 }
360                                 return _rsa; 
361                         }
362 #if NET_2_0
363                         set {
364                                 if (value != null)
365                                         _dsa = null;
366                                 _rsa = value;
367                         }
368 #endif
369                 }
370                 
371                 public virtual byte[] RawData {
372                         get {
373                                 if (m_encodedcert == null)
374                                         return null;
375                                 return (byte[]) m_encodedcert.Clone ();
376                         }
377                 }
378
379                 public virtual byte[] SerialNumber {
380                         get { 
381                                 if (serialnumber == null)
382                                         return null;
383                                 return (byte[]) serialnumber.Clone (); 
384                         }
385                 }
386
387                 public virtual byte[] Signature {
388                         get { 
389                                 if (signature == null)
390                                         return null;
391
392                                 switch (m_signaturealgo) {
393                                         case "1.2.840.113549.1.1.2":    // MD2 with RSA encryption 
394                                         case "1.2.840.113549.1.1.4":    // MD5 with RSA encryption 
395                                         case "1.2.840.113549.1.1.5":    // SHA-1 with RSA Encryption 
396                                         case "1.3.14.3.2.29":           // SHA1 with RSA signature
397                                                 return (byte[]) signature.Clone ();
398
399                                         case "1.2.840.10040.4.3":       // SHA-1 with DSA
400                                                 ASN1 sign = new ASN1 (signature);
401                                                 if ((sign == null) || (sign.Count != 2))
402                                                         return null;
403                                                 // parts may be less than 20 bytes (i.e. first bytes were 0x00)
404                                                 byte[] part1 = sign [0].Value;
405                                                 byte[] part2 = sign [1].Value;
406                                                 byte[] sig = new byte [40];
407                                                 Buffer.BlockCopy (part1, 0, sig, (20 - part1.Length), part1.Length);
408                                                 Buffer.BlockCopy (part2, 0, sig, (40 - part2.Length), part2.Length);
409                                                 return sig;
410
411                                         default:
412                                                 throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
413                                 }
414                         }
415                 }
416
417                 public virtual string SignatureAlgorithm {
418                         get { return m_signaturealgo; }
419                 }
420
421                 public virtual byte[] SignatureAlgorithmParameters {
422                         get { 
423                                 if (m_signaturealgoparams == null)
424                                         return m_signaturealgoparams;
425                                 return (byte[]) m_signaturealgoparams.Clone ();
426                         }
427                 }
428
429                 public virtual string SubjectName {
430                         get { return m_subject; }
431                 }
432
433                 public virtual DateTime ValidFrom {
434                         get { return m_from; }
435                 }
436
437                 public virtual DateTime ValidUntil {
438                         get { return m_until; }
439                 }
440
441                 public int Version {
442                         get { return version; }
443                 }
444
445                 public bool IsCurrent {
446                         get { return WasCurrent (DateTime.Now); }
447                 }
448
449                 public bool WasCurrent (DateTime instant) 
450                 {
451                         return ((instant > ValidFrom) && (instant <= ValidUntil));
452                 }
453
454                 internal bool VerifySignature (DSA dsa) 
455                 {
456                         // signatureOID is check by both this.Hash and this.Signature
457                         DSASignatureDeformatter v = new DSASignatureDeformatter (dsa);
458                         // only SHA-1 is supported
459                         v.SetHashAlgorithm ("SHA1");
460                         return v.VerifySignature (this.Hash, this.Signature);
461                 }
462
463                 internal bool VerifySignature (RSA rsa) 
464                 {
465                         RSAPKCS1SignatureDeformatter v = new RSAPKCS1SignatureDeformatter (rsa);
466                         switch (m_signaturealgo) {
467                                 // MD2 with RSA encryption 
468                                 case "1.2.840.113549.1.1.2":
469                                         // maybe someone installed MD2 ?
470                                         v.SetHashAlgorithm ("MD2");
471                                         break;
472                                 // MD5 with RSA encryption 
473                                 case "1.2.840.113549.1.1.4":
474                                         v.SetHashAlgorithm ("MD5");
475                                         break;
476                                 // SHA-1 with RSA Encryption 
477                                 case "1.2.840.113549.1.1.5":
478                                 case "1.3.14.3.2.29":
479                                         v.SetHashAlgorithm ("SHA1");
480                                         break;
481                                 default:
482                                         throw new CryptographicException ("Unsupported hash algorithm: " + m_signaturealgo);
483                         }
484                         return v.VerifySignature (this.Hash, this.Signature);
485                 }
486
487                 public bool VerifySignature (AsymmetricAlgorithm aa) 
488                 {
489                         if (aa == null)
490                                 throw new ArgumentNullException ("aa");
491
492                         if (aa is RSA)
493                                 return VerifySignature (aa as RSA);
494                         else if (aa is DSA)
495                                 return VerifySignature (aa as DSA);
496                         else 
497                                 throw new NotSupportedException ("Unknown Asymmetric Algorithm " + aa.ToString ());
498                 }
499
500                 public bool CheckSignature (byte[] hash, string hashAlgorithm, byte[] signature) 
501                 {
502                         RSACryptoServiceProvider r = (RSACryptoServiceProvider) RSA;
503                         return r.VerifyHash (hash, hashAlgorithm, signature);
504                 }
505
506                 public bool IsSelfSigned {
507                         get { 
508                                 if (m_issuername == m_subject)
509                                         return VerifySignature (RSA); 
510                                 else
511                                         return false;
512                         }
513                 }
514
515 #if INSIDE_CORLIB || NET_2_0
516                 public ASN1 GetIssuerName ()
517                 {
518                         return issuer;
519                 }
520
521                 public ASN1 GetSubjectName ()
522                 {
523                         return subject;
524                 }
525
526                 protected X509Certificate (SerializationInfo info, StreamingContext context)
527                 {
528                         Parse ((byte[]) info.GetValue ("raw", typeof (byte[])));
529                 }
530
531                 [SecurityPermission (SecurityAction.Demand, SerializationFormatter = true)]
532                 public virtual void GetObjectData (SerializationInfo info, StreamingContext context)
533                 {
534                         info.AddValue ("raw", m_encodedcert);
535                         // note: we NEVER serialize the private key
536                 }
537 #endif
538         }
539 }