2009-06-12 Bill Holmes <billholmes54@gmail.com>
[mono.git] / mcs / class / System / System.Security.Cryptography.X509Certificates / X509Certificate2.cs
1 //
2 // System.Security.Cryptography.X509Certificate2 class
3 //
4 // Author:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //
7 // (C) 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 #if NET_2_0
31
32 using System.IO;
33 using System.Text;
34 #if SECURITY_DEP
35 using Mono.Security;
36 using Mono.Security.Cryptography;
37 using MX = Mono.Security.X509;
38 #endif
39
40 namespace System.Security.Cryptography.X509Certificates {
41
42         public class X509Certificate2 : X509Certificate {
43 #if SECURITY_DEP
44                 private bool _archived;
45                 private X509ExtensionCollection _extensions;
46                 private string _name = String.Empty;
47                 private string _serial;
48                 private PublicKey _publicKey;
49                 private X500DistinguishedName issuer_name;
50                 private X500DistinguishedName subject_name;
51                 private Oid signature_algorithm;
52
53                 private MX.X509Certificate _cert;
54
55                 private static string empty_error = Locale.GetText ("Certificate instance is empty.");
56
57                 // constructors
58
59                 public X509Certificate2 ()
60                 {
61                         _cert = null;
62                 }
63
64                 public X509Certificate2 (byte[] rawData)
65                 {
66                         Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
67                 }
68
69                 public X509Certificate2 (byte[] rawData, string password)
70                 {
71                         Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
72                 }
73
74                 public X509Certificate2 (byte[] rawData, SecureString password)
75                 {
76                         Import (rawData, password, X509KeyStorageFlags.DefaultKeySet);
77                 }
78
79                 public X509Certificate2 (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
80                 {
81                         Import (rawData, password, keyStorageFlags);
82                 }
83
84                 public X509Certificate2 (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
85                 {
86                         Import (rawData, password, keyStorageFlags);
87                 }
88
89                 public X509Certificate2 (string fileName)
90                 {
91                         Import (fileName, String.Empty, X509KeyStorageFlags.DefaultKeySet);
92                 }
93
94                 public X509Certificate2 (string fileName, string password)
95                 {
96                         Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
97                 }
98
99                 public X509Certificate2 (string fileName, SecureString password)
100                 {
101                         Import (fileName, password, X509KeyStorageFlags.DefaultKeySet);
102                 }
103
104                 public X509Certificate2 (string fileName, string password, X509KeyStorageFlags keyStorageFlags)
105                 {
106                         Import (fileName, password, keyStorageFlags);
107                 }
108
109                 public X509Certificate2 (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags)
110                 {
111                         Import (fileName, password, keyStorageFlags);
112                 }
113
114                 public X509Certificate2 (IntPtr handle) : base (handle) 
115                 {
116                         _cert = new MX.X509Certificate (base.GetRawCertData ());
117                 }
118
119                 public X509Certificate2 (X509Certificate certificate) 
120                         : base (certificate)
121                 {
122                         _cert = new MX.X509Certificate (base.GetRawCertData ());
123                 }
124
125                 // properties
126
127                 public bool Archived {
128                         get {
129                                 if (_cert == null)
130                                         throw new CryptographicException (empty_error);
131                                 return _archived;
132                         }
133                         set {
134                                 if (_cert == null)
135                                         throw new CryptographicException (empty_error);
136                                 _archived = value;
137                         }
138                 }
139
140                 public X509ExtensionCollection Extensions {
141                         get {
142                                 if (_cert == null)
143                                         throw new CryptographicException (empty_error);
144                                 if (_extensions == null)
145                                         _extensions = new X509ExtensionCollection (_cert);
146                                 return _extensions;
147                         }
148                 }
149
150                 public string FriendlyName {
151                         get {
152                                 if (_cert == null)
153                                         throw new CryptographicException (empty_error);
154                                 return _name;
155                         }
156                         set {
157                                 if (_cert == null)
158                                         throw new CryptographicException (empty_error);
159                                 _name = value;
160                         }
161                 }
162
163                 // FIXME - Could be more efficient
164                 public bool HasPrivateKey {
165                         get { return PrivateKey != null; }
166                 }
167
168                 public X500DistinguishedName IssuerName {
169                         get {
170                                 if (_cert == null)
171                                         throw new CryptographicException (empty_error);
172                                 if (issuer_name == null)
173                                         issuer_name = new X500DistinguishedName (_cert.GetIssuerName ().GetBytes ());
174                                 return issuer_name;
175                         }
176                 } 
177
178                 public DateTime NotAfter {
179                         get {
180                                 if (_cert == null)
181                                         throw new CryptographicException (empty_error);
182                                 return _cert.ValidUntil.ToLocalTime ();
183                         }
184                 }
185
186                 public DateTime NotBefore {
187                         get {
188                                 if (_cert == null)
189                                         throw new CryptographicException (empty_error);
190                                 return _cert.ValidFrom.ToLocalTime ();
191                         }
192                 }
193
194                 public AsymmetricAlgorithm PrivateKey {
195                         get {
196                                 if (_cert == null)
197                                         throw new CryptographicException (empty_error);
198                                 try {
199                                         if (_cert.RSA != null) {
200                                                 RSACryptoServiceProvider rcsp = _cert.RSA as RSACryptoServiceProvider;
201                                                 if (rcsp != null)
202                                                         return rcsp.PublicOnly ? null : rcsp;
203                                                 RSAManaged rsam = _cert.RSA as RSAManaged;
204                                                 if (rsam != null)
205                                                         return rsam.PublicOnly ? null : rsam;
206
207                                                 _cert.RSA.ExportParameters (true);
208                                                 return _cert.RSA;
209                                         } else if (_cert.DSA != null) {
210                                                 DSACryptoServiceProvider dcsp = _cert.DSA as DSACryptoServiceProvider;
211                                                 if (dcsp != null)
212                                                         return dcsp.PublicOnly ? null : dcsp;
213         
214                                                 _cert.DSA.ExportParameters (true);
215                                                 return _cert.DSA;
216                                         }
217                                 }
218                                 catch {
219                                 }
220                                 return null;
221                         }
222                         set {
223                                 if (_cert == null)
224                                         throw new CryptographicException (empty_error);
225
226                                 // allow NULL so we can "forget" the key associated to the certificate
227                                 // e.g. in case we want to export it in another format (see bug #396620)
228                                 if (value == null) {
229                                         _cert.RSA = null;
230                                         _cert.DSA = null;
231                                 } else  if (value is RSA)
232                                         _cert.RSA = (RSA) value;
233                                 else if (value is DSA)
234                                         _cert.DSA = (DSA) value;
235                                 else
236                                         throw new NotSupportedException ();
237                         }
238                 } 
239
240                 public PublicKey PublicKey {
241                         get { 
242                                 if (_cert == null)
243                                         throw new CryptographicException (empty_error);
244
245                                 if (_publicKey == null) {
246                                         try {
247                                                 _publicKey = new PublicKey (_cert);
248                                         }
249                                         catch (Exception e) {
250                                                 string msg = Locale.GetText ("Unable to decode public key.");
251                                                 throw new CryptographicException (msg, e);
252                                         }
253                                 }
254                                 return _publicKey;
255                         }
256                 } 
257
258                 public byte[] RawData {
259                         get {
260                                 if (_cert == null)
261                                         throw new CryptographicException (empty_error);
262
263                                 return base.GetRawCertData ();
264                         }
265                 } 
266
267                 public string SerialNumber {
268                         get { 
269                                 if (_cert == null)
270                                         throw new CryptographicException (empty_error);
271
272                                 if (_serial == null) {
273                                         StringBuilder sb = new StringBuilder ();
274                                         byte[] serial = _cert.SerialNumber;
275                                         for (int i=serial.Length - 1; i >= 0; i--)
276                                                 sb.Append (serial [i].ToString ("X2"));
277                                         _serial = sb.ToString ();
278                                 }
279                                 return _serial; 
280                         }
281                 } 
282
283                 public Oid SignatureAlgorithm {
284                         get {
285                                 if (_cert == null)
286                                         throw new CryptographicException (empty_error);
287
288                                 if (signature_algorithm == null)
289                                         signature_algorithm = new Oid (_cert.SignatureAlgorithm);
290                                 return signature_algorithm;
291                         }
292                 } 
293
294                 public X500DistinguishedName SubjectName {
295                         get {
296                                 if (_cert == null)
297                                         throw new CryptographicException (empty_error);
298
299                                 if (subject_name == null)
300                                         subject_name = new X500DistinguishedName (_cert.GetSubjectName ().GetBytes ());
301                                 return subject_name;
302                         }
303                 } 
304
305                 public string Thumbprint {
306                         get { return base.GetCertHashString (); }
307                 } 
308
309                 public int Version {
310                         get {
311                                 if (_cert == null)
312                                         throw new CryptographicException (empty_error);
313                                 return _cert.Version;
314                         }
315                 }
316
317                 // methods
318
319                 [MonoTODO ("always return String.Empty for UpnName, DnsFromAlternativeName and UrlName")]
320                 public string GetNameInfo (X509NameType nameType, bool forIssuer) 
321                 {
322                         switch (nameType) {
323                         case X509NameType.SimpleName:
324                                 if (_cert == null)
325                                         throw new CryptographicException (empty_error);
326                                 // return CN= or, if missing, the first part of the DN
327                                 ASN1 sn = forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ();
328                                 ASN1 dn = Find (commonName, sn);
329                                 if (dn != null)
330                                         return GetValueAsString (dn);
331                                 if (sn.Count == 0)
332                                         return String.Empty;
333                                 ASN1 last_entry = sn [sn.Count - 1];
334                                 if (last_entry.Count == 0)
335                                         return String.Empty;
336                                 return GetValueAsString (last_entry [0]);
337                         case X509NameType.EmailName:
338                                 // return the E= part of the DN (if present)
339                                 ASN1 e = Find (email, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
340                                 if (e != null)
341                                         return GetValueAsString (e);
342                                 return String.Empty;
343                         case X509NameType.UpnName:
344                                 // FIXME - must find/create test case
345                                 return String.Empty;
346                         case X509NameType.DnsName:
347                                 // return the CN= part of the DN (if present)
348                                 ASN1 cn = Find (commonName, forIssuer ? _cert.GetIssuerName () : _cert.GetSubjectName ());
349                                 if (cn != null)
350                                         return GetValueAsString (cn);
351                                 return String.Empty;
352                         case X509NameType.DnsFromAlternativeName:
353                                 // FIXME - must find/create test case
354                                 return String.Empty;
355                         case X509NameType.UrlName:
356                                 // FIXME - must find/create test case
357                                 return String.Empty;
358                         default:
359                                 throw new ArgumentException ("nameType");
360                         }
361                 }
362
363                 static byte[] commonName = { 0x55, 0x04, 0x03 };
364                 static byte[] email = { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x09, 0x01 };
365
366                 private ASN1 Find (byte[] oid, ASN1 dn)
367                 {
368                         if (dn.Count == 0)
369                                 return null;
370
371                         // process SET
372                         for (int i = 0; i < dn.Count; i++) {
373                                 ASN1 set = dn [i];
374                                 for (int j = 0; j < set.Count; j++) {
375                                         ASN1 pair = set [j];
376                                         if (pair.Count != 2)
377                                                 continue;
378
379                                         ASN1 poid = pair [0];
380                                         if (poid == null)
381                                                 continue;
382
383                                         if (poid.CompareValue (oid))
384                                                 return pair;
385                                 }
386                         }
387                         return null;
388                 }
389
390                 private string GetValueAsString (ASN1 pair)
391                 {
392                         if (pair.Count != 2)
393                                 return String.Empty;
394
395                         ASN1 value = pair [1];
396                         if ((value.Value == null) || (value.Length == 0))
397                                 return String.Empty;
398
399                         if (value.Tag == 0x1E) {
400                                 // BMPSTRING
401                                 StringBuilder sb = new StringBuilder ();
402                                 for (int j = 1; j < value.Value.Length; j += 2)
403                                         sb.Append ((char)value.Value [j]);
404                                 return sb.ToString ();
405                         } else {
406                                 return Encoding.UTF8.GetString (value.Value);
407                         }
408                 }
409
410                 private void ImportPkcs12 (byte[] rawData, string password)
411                 {
412                         MX.PKCS12 pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
413                         if (pfx.Certificates.Count > 0) {
414                                 _cert = pfx.Certificates [0];
415                         } else {
416                                 _cert = null;
417                         }
418                         if (pfx.Keys.Count > 0) {
419                                 _cert.RSA = (pfx.Keys [0] as RSA);
420                                 _cert.DSA = (pfx.Keys [0] as DSA);
421                         }
422                 }
423
424                 public override void Import (byte[] rawData) 
425                 {
426                         Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
427                 }
428
429                 [MonoTODO ("missing KeyStorageFlags support")]
430                 public override void Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
431                 {
432                         base.Import (rawData, password, keyStorageFlags);
433                         if (password == null) {
434                                 try {
435                                         _cert = new Mono.Security.X509.X509Certificate (rawData);
436                                 }
437                                 catch (Exception e) {
438                                         try {
439                                                 ImportPkcs12 (rawData, null);
440                                         }
441                                         catch {
442                                                 string msg = Locale.GetText ("Unable to decode certificate.");
443                                                 // inner exception is the original (not second) exception
444                                                 throw new CryptographicException (msg, e);
445                                         }
446                                 }
447                         } else {
448                                 // try PKCS#12
449                                 try {
450                                         ImportPkcs12 (rawData, password);
451                                 }
452                                 catch {
453                                         // it's possible to supply a (unrequired/unusued) password
454                                         // fix bug #79028
455                                         _cert = new Mono.Security.X509.X509Certificate (rawData);
456                                 }
457                         }
458                 }
459
460                 [MonoTODO ("SecureString is incomplete")]
461                 public override void Import (byte[] rawData, SecureString password, X509KeyStorageFlags keyStorageFlags)
462                 {
463                         Import (rawData, (string) null, keyStorageFlags);
464                 }
465
466                 public override void Import (string fileName) 
467                 {
468                         byte[] rawData = Load (fileName);
469                         Import (rawData, (string)null, X509KeyStorageFlags.DefaultKeySet);
470                 }
471
472                 [MonoTODO ("missing KeyStorageFlags support")]
473                 public override void Import (string fileName, string password, X509KeyStorageFlags keyStorageFlags) 
474                 {
475                         byte[] rawData = Load (fileName);
476                         Import (rawData, password, keyStorageFlags);
477                 }
478
479                 [MonoTODO ("SecureString is incomplete")]
480                 public override void Import (string fileName, SecureString password, X509KeyStorageFlags keyStorageFlags) 
481                 {
482                         byte[] rawData = Load (fileName);
483                         Import (rawData, (string)null, keyStorageFlags);
484                 }
485
486                 private static byte[] Load (string fileName)
487                 {
488                         byte[] data = null;
489                         using (FileStream fs = File.OpenRead (fileName)) {
490                                 data = new byte [fs.Length];
491                                 fs.Read (data, 0, data.Length);
492                                 fs.Close ();
493                         }
494                         return data;
495                 }
496
497                 public override void Reset () 
498                 {
499                         _cert = null;
500                         _archived = false;
501                         _extensions = null;
502                         _name = String.Empty;
503                         _serial = null;
504                         _publicKey = null;
505                         issuer_name = null;
506                         subject_name = null;
507                         signature_algorithm = null;
508                         base.Reset ();
509                 }
510
511                 public override string ToString ()
512                 {
513                         if (_cert == null)
514                                 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
515
516                         return base.ToString (true);
517                 }
518
519                 public override string ToString (bool verbose)
520                 {
521                         if (_cert == null)
522                                 return "System.Security.Cryptography.X509Certificates.X509Certificate2";
523
524                         // the non-verbose X509Certificate2 == verbose X509Certificate
525                         if (!verbose)
526                                 return base.ToString (true);
527
528                         string nl = Environment.NewLine;
529                         StringBuilder sb = new StringBuilder ();
530                         sb.AppendFormat ("[Version]{0}  V{1}{0}{0}", nl, Version);
531                         sb.AppendFormat ("[Subject]{0}  {1}{0}{0}", nl, Subject);
532                         sb.AppendFormat ("[Issuer]{0}  {1}{0}{0}", nl, Issuer);
533                         sb.AppendFormat ("[Serial Number]{0}  {1}{0}{0}", nl, SerialNumber);
534                         sb.AppendFormat ("[Not Before]{0}  {1}{0}{0}", nl, NotBefore);
535                         sb.AppendFormat ("[Not After]{0}  {1}{0}{0}", nl, NotAfter);
536                         sb.AppendFormat ("[Thumbprint]{0}  {1}{0}{0}", nl, Thumbprint);
537                         sb.AppendFormat ("[Signature Algorithm]{0}  {1}({2}){0}{0}", nl, SignatureAlgorithm.FriendlyName, 
538                                 SignatureAlgorithm.Value);
539
540                         AsymmetricAlgorithm key = PublicKey.Key;
541                         sb.AppendFormat ("[Public Key]{0}  Algorithm: ", nl);
542                         if (key is RSA)
543                                 sb.Append ("RSA");
544                         else if (key is DSA)
545                                 sb.Append ("DSA");
546                         else
547                                 sb.Append (key.ToString ());
548                         sb.AppendFormat ("{0}  Length: {1}{0}  Key Blob: ", nl, key.KeySize);
549                         AppendBuffer (sb, PublicKey.EncodedKeyValue.RawData);
550                         sb.AppendFormat ("{0}  Parameters: ", nl);
551                         AppendBuffer (sb, PublicKey.EncodedParameters.RawData);
552                         sb.Append (nl);
553
554                         return sb.ToString ();
555                 }
556
557                 private static void AppendBuffer (StringBuilder sb, byte[] buffer)
558                 {
559                         if (buffer == null)
560                                 return;
561                         for (int i=0; i < buffer.Length; i++) {
562                                 sb.Append (buffer [i].ToString ("x2"));
563                                 if (i < buffer.Length - 1)
564                                         sb.Append (" ");
565                         }
566                 }
567
568                 [MonoTODO ("by default this depends on the incomplete X509Chain")]
569                 public bool Verify ()
570                 {
571                         if (_cert == null)
572                                 throw new CryptographicException (empty_error);
573
574                         X509Chain chain = (X509Chain) CryptoConfig.CreateFromName ("X509Chain");
575                         if (!chain.Build (this))
576                                 return false;
577                         // TODO - check chain and other stuff ???
578                         return true;
579                 }
580
581                 // static methods
582
583                 private static byte[] signedData = new byte[] { 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x07, 0x02 };
584
585                 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12, Pkcs7 and Unknown")]
586                 public static X509ContentType GetCertContentType (byte[] rawData)
587                 {
588                         if ((rawData == null) || (rawData.Length == 0))
589                                 throw new ArgumentException ("rawData");
590
591                         X509ContentType type = X509ContentType.Unknown;
592                         try {
593                                 ASN1 data = new ASN1 (rawData);
594                                 if (data.Tag != 0x30) {
595                                         string msg = Locale.GetText ("Unable to decode certificate.");
596                                         throw new CryptographicException (msg);
597                                 }
598
599                                 if (data.Count == 0)
600                                         return type;
601
602                                 if (data.Count == 3) {
603                                         switch (data [0].Tag) {
604                                         case 0x30:
605                                                 // SEQUENCE / SEQUENCE / BITSTRING
606                                                 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x03))
607                                                         type = X509ContentType.Cert;
608                                                 break;
609                                         case 0x02:
610                                                 // INTEGER / SEQUENCE / SEQUENCE
611                                                 if ((data [1].Tag == 0x30) && (data [2].Tag == 0x30))
612                                                         type = X509ContentType.Pkcs12;
613                                                 // note: Pfx == Pkcs12
614                                                 break;
615                                         }
616                                 }
617
618                                 // check for PKCS#7 (count unknown but greater than 0)
619                                 // SEQUENCE / OID (signedData)
620                                 if ((data [0].Tag == 0x06) && data [0].CompareValue (signedData))
621                                         type = X509ContentType.Pkcs7;
622                         }
623                         catch (Exception e) {
624                                 string msg = Locale.GetText ("Unable to decode certificate.");
625                                 throw new CryptographicException (msg, e);
626                         }
627
628                         return type;
629                 }
630
631                 [MonoTODO ("Detection limited to Cert, Pfx, Pkcs12 and Unknown")]
632                 public static X509ContentType GetCertContentType (string fileName)
633                 {
634                         if (fileName == null)
635                                 throw new ArgumentNullException ("fileName");
636                         if (fileName.Length == 0)
637                                 throw new ArgumentException ("fileName");
638
639                         byte[] data = Load (fileName);
640                         return GetCertContentType (data);
641                 }
642
643                 // internal stuff because X509Certificate2 isn't complete enough
644                 // (maybe X509Certificate3 will be better?)
645
646                 internal MX.X509Certificate MonoCertificate {
647                         get { return _cert; }
648                 }
649
650 #else
651                 // HACK - this ensure the type X509Certificate2 and PrivateKey property exists in the build before
652                 // Mono.Security.dll is built. This is required to get working client certificate in SSL/TLS
653                 public AsymmetricAlgorithm PrivateKey {
654                         get { return null; }
655                 }
656 #endif
657         }
658 }
659 #endif