05575d9d58c0f5632081f661ce5b7bb70f96bee6
[mono.git] / mcs / class / corlib / System.Security.Cryptography.X509Certificates / X509Helper.cs
1 //
2 // X509Helpers.cs: X.509 helper and utility functions.
3 //
4 // Authors:
5 //      Sebastien Pouliot  <sebastien@ximian.com>
6 //      Martin Baulig  <martin.baulig@xamarin.com>
7 //
8 // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
9 // Copyright (C) 2004-2006 Novell, Inc (http://www.novell.com)
10 // Copyright (C) 2015 Xamarin, Inc. (http://www.xamarin.com)
11 //
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
30 //
31 using System;
32 using System.Text;
33 using System.Threading;
34 using System.Runtime.InteropServices;
35 #if !MOBILE
36 using System.Security.Permissions;
37 #endif
38 using MX = Mono.Security.X509;
39
40 namespace System.Security.Cryptography.X509Certificates
41 {
42         static partial class X509Helper
43         {
44                 static INativeCertificateHelper nativeHelper;
45
46                 internal static void InstallNativeHelper (INativeCertificateHelper helper)
47                 {
48                         if (nativeHelper == null)
49                                 Interlocked.CompareExchange (ref nativeHelper, helper, null);
50                 }
51
52 #if MONO_FEATURE_APPLETLS
53                 static bool ShouldUseAppleTls
54                 {
55                         get
56                         {
57                                 if (!System.Environment.IsMacOS)
58                                         return false;
59                                 // MONO_TLS_PROVIDER values default or apple (not legacy or btls) and must be on MacOS
60                                 var variable = Environment.GetEnvironmentVariable ("MONO_TLS_PROVIDER");
61                                 return string.IsNullOrEmpty (variable) || variable == "default" || variable == "apple"; // On Platform.IsMacOS default is AppleTlsProvider
62                         }
63                 }
64 #endif
65
66                 public static X509CertificateImpl InitFromHandle (IntPtr handle)
67                 {
68 #if MONO_FEATURE_APPLETLS && ONLY_APPLETLS // ONLY_APPLETLS should not support any other option
69                         return InitFromHandleApple (handle);
70 #elif MONOTOUCH_WATCH
71                         throw new PlatformNotSupportedException ();
72 #else
73
74 #if MONO_FEATURE_APPLETLS // If we support AppleTls, which is the default, and not overriding to legacy
75                         if (ShouldUseAppleTls)
76                                 return InitFromHandleApple (handle);
77 #endif
78 #if !MOBILE
79                         return InitFromHandleCore (handle);
80 #elif !MONOTOUCH && !XAMMAC
81                         throw new NotSupportedException ();
82 #endif
83 #endif
84                 }
85
86                 static X509CertificateImpl Import (byte[] rawData)
87                 {
88 #if MONO_FEATURE_APPLETLS && ONLY_APPLETLS // ONLY_APPLETLS should not support any other option
89                         return ImportApple (rawData);
90 #elif MONOTOUCH_WATCH
91                         throw new PlatformNotSupportedException ();
92 #else
93 #if MONO_FEATURE_APPLETLS
94                         if (ShouldUseAppleTls)
95                                 return ImportApple (rawData);
96 #endif
97                         return ImportCore (rawData);
98 #endif
99                 }
100
101 #if !MOBILE
102                 // typedef struct _CERT_CONTEXT {
103                 //      DWORD                   dwCertEncodingType;
104                 //      BYTE                    *pbCertEncoded;
105                 //      DWORD                   cbCertEncoded;
106                 //      PCERT_INFO              pCertInfo;
107                 //      HCERTSTORE              hCertStore;
108                 // } CERT_CONTEXT, *PCERT_CONTEXT;
109                 // typedef const CERT_CONTEXT *PCCERT_CONTEXT;
110                 [StructLayout (LayoutKind.Sequential)]
111                 internal struct CertificateContext {
112                         public UInt32 dwCertEncodingType;
113                         public IntPtr pbCertEncoded;
114                         public UInt32 cbCertEncoded;
115                         public IntPtr pCertInfo;
116                         public IntPtr hCertStore;
117                 }
118                 // NOTE: We only define the CryptoAPI structure (from WINCRYPT.H)
119                 // so we don't create any dependencies on Windows DLL in corlib
120
121                 [SecurityPermission (SecurityAction.Demand, UnmanagedCode = true)]
122                 public static X509CertificateImpl InitFromHandleCore (IntPtr handle)
123                 {
124                         // both Marshal.PtrToStructure and Marshal.Copy use LinkDemand (so they will always success from here)
125                         CertificateContext cc = (CertificateContext) Marshal.PtrToStructure (handle, typeof (CertificateContext));
126                         byte[] data = new byte [cc.cbCertEncoded];
127                         Marshal.Copy (cc.pbCertEncoded, data, 0, (int)cc.cbCertEncoded);
128                         var x509 = new MX.X509Certificate (data);
129                         return new X509CertificateImplMono (x509);
130                 }
131 #endif
132
133                 public static X509CertificateImpl InitFromCertificate (X509Certificate cert)
134                 {
135                         if (nativeHelper != null)
136                                 return nativeHelper.Import (cert);
137
138                         return InitFromCertificate (cert.Impl);
139                 }
140
141                 public static X509CertificateImpl InitFromCertificate (X509CertificateImpl impl)
142                 {
143                         ThrowIfContextInvalid (impl);
144                         var copy = impl.Clone ();
145                         if (copy != null)
146                                 return copy;
147
148                         var data = impl.GetRawCertData ();
149                         if (data == null)
150                                 return null;
151
152                         var x509 = new MX.X509Certificate (data);
153                         return new X509CertificateImplMono (x509);
154                 }
155
156                 public static bool IsValid (X509CertificateImpl impl)
157                 {
158                         return impl != null && impl.IsValid;
159                 }
160
161                 internal static void ThrowIfContextInvalid (X509CertificateImpl impl)
162                 {
163                         if (!IsValid (impl))
164                                 throw GetInvalidContextException ();
165                 }
166
167                 internal static Exception GetInvalidContextException ()
168                 {
169                         return new CryptographicException (Locale.GetText ("Certificate instance is empty."));
170                 }
171
172                 internal static MX.X509Certificate ImportPkcs12 (byte[] rawData, string password)
173                 {
174                         var pfx = (password == null) ? new MX.PKCS12 (rawData) : new MX.PKCS12 (rawData, password);
175                         if (pfx.Certificates.Count == 0) {
176                                 // no certificate was found
177                                 return null;
178                         } else if (pfx.Keys.Count == 0) {
179                                 // no key were found - pick the first certificate
180                                 return pfx.Certificates [0];
181                         } else {
182                                 // find the certificate that match the first key
183                                 var keypair = (pfx.Keys [0] as AsymmetricAlgorithm);
184                                 string pubkey = keypair.ToXmlString (false);
185                                 foreach (var c in pfx.Certificates) {
186                                         if ((c.RSA != null) && (pubkey == c.RSA.ToXmlString (false)))
187                                                 return c;
188                                         if ((c.DSA != null) && (pubkey == c.DSA.ToXmlString (false)))
189                                                 return c;
190                                 }
191                                 return pfx.Certificates [0]; // no match, pick first certificate without keys
192                         }
193                 }
194
195                 static byte[] PEM (string type, byte[] data)
196                 {
197                         string pem = Encoding.ASCII.GetString (data);
198                         string header = String.Format ("-----BEGIN {0}-----", type);
199                         string footer = String.Format ("-----END {0}-----", type);
200                         int start = pem.IndexOf (header) + header.Length;
201                         int end = pem.IndexOf (footer, start);
202                         string base64 = pem.Substring (start, (end - start));
203                         return Convert.FromBase64String (base64);
204                 }
205
206                 static byte[] ConvertData (byte[] data)
207                 {
208                         if (data == null || data.Length == 0)
209                                 return data;
210
211                         // does it looks like PEM ?
212                         if (data [0] != 0x30) {
213                                 try {
214                                         return PEM ("CERTIFICATE", data);
215                                 } catch {
216                                         // let the implementation take care of it.
217                                 }
218                         }
219                         return data;
220                 }
221
222                 static X509CertificateImpl ImportCore (byte[] rawData)
223                 {
224                         MX.X509Certificate x509;
225                         try {
226                                 x509 = new MX.X509Certificate (rawData);
227                         } catch (Exception e) {
228                                 try {
229                                         x509 = ImportPkcs12 (rawData, null);
230                                 } catch {
231                                         string msg = Locale.GetText ("Unable to decode certificate.");
232                                         // inner exception is the original (not second) exception
233                                         throw new CryptographicException (msg, e);
234                                 }
235                         }
236
237                         return new X509CertificateImplMono (x509);
238                 }
239
240                 public static X509CertificateImpl Import (byte[] rawData, string password, X509KeyStorageFlags keyStorageFlags)
241                 {
242                         if (password == null) {
243                                 rawData = ConvertData (rawData);
244                                 return Import (rawData);
245                         }
246
247                         MX.X509Certificate x509;
248                         // try PKCS#12
249                         try {
250                                 x509 = ImportPkcs12 (rawData, password);
251                         } catch {
252                                 // it's possible to supply a (unrequired/unusued) password
253                                 // fix bug #79028
254                                 x509 = new MX.X509Certificate (rawData);
255                         }
256
257                         return new X509CertificateImplMono (x509);
258                 }
259
260                 public static byte[] Export (X509CertificateImpl impl, X509ContentType contentType, byte[] password)
261                 {
262                         ThrowIfContextInvalid (impl);
263                         return impl.Export (contentType, password);
264                 }
265
266                 public static bool Equals (X509CertificateImpl first, X509CertificateImpl second)
267                 {
268                         if (!IsValid (first) || !IsValid (second))
269                                 return false;
270
271                         bool result;
272                         if (first.Equals (second, out result))
273                                 return result;
274
275                         var firstRaw = first.GetRawCertData ();
276                         var secondRaw = second.GetRawCertData ();
277
278                         if (firstRaw == null)
279                                 return secondRaw == null;
280                         else if (secondRaw == null)
281                                 return false;
282
283                         if (firstRaw.Length != secondRaw.Length)
284                                 return false;
285
286                         for (int i = 0; i < firstRaw.Length; i++) {
287                                 if (firstRaw [i] != secondRaw [i])
288                                         return false;
289                         }
290
291                         return true;
292                 }
293
294                 // almost every byte[] returning function has a string equivalent
295                 // sadly the BitConverter insert dash between bytes :-(
296                 public static string ToHexString (byte[] data)
297                 {
298                         if (data != null) {
299                                 StringBuilder sb = new StringBuilder ();
300                                 for (int i = 0; i < data.Length; i++)
301                                         sb.Append (data[i].ToString ("X2"));
302                                 return sb.ToString ();
303                         }
304                         else
305                                 return null;
306                 }
307         }
308 }