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