1 #if SECURITY_DEP && MONO_FEATURE_APPLETLS
6 // Sebastien Pouliot <sebastien@xamarin.com>
8 // Copyright 2011-2014 Xamarin Inc.
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:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
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.
31 using System.Runtime.InteropServices;
32 using System.Security.Cryptography;
33 using System.Security.Cryptography.X509Certificates;
40 using Mono.Security.Cryptography;
43 namespace Mono.AppleTls {
45 internal partial class SecImportExport {
47 [DllImport (AppleTlsContext.SecurityLibrary)]
48 extern static SecStatusCode SecPKCS12Import (IntPtr pkcs12_data, IntPtr options, out IntPtr items);
50 static public SecStatusCode ImportPkcs12 (byte[] buffer, CFDictionary options, out CFDictionary[] array)
52 using (CFData data = CFData.FromData (buffer)) {
53 return ImportPkcs12 (data, options, out array);
57 static public SecStatusCode ImportPkcs12 (CFData data, CFDictionary options, out CFDictionary [] array)
60 throw new ArgumentNullException ("options");
63 SecStatusCode code = SecPKCS12Import (data.Handle, options.Handle, out handle);
64 array = CFArray.ArrayFromHandle <CFDictionary> (handle, h => new CFDictionary (h, false));
65 if (handle != IntPtr.Zero)
66 CFObject.CFRelease (handle);
70 [DllImport (AppleTlsContext.SecurityLibrary)]
71 extern static SecStatusCode SecItemImport (
72 /* CFDataRef */ IntPtr importedData,
73 /* CFStringRef */ IntPtr fileNameOrExtension, // optional
74 /* SecExternalFormat* */ ref SecExternalFormat inputFormat, // optional, IN/OUT
75 /* SecExternalItemType* */ ref SecExternalItemType itemType, // optional, IN/OUT
76 /* SecItemImportExportFlags */ SecItemImportExportFlags flags,
77 /* const SecItemImportExportKeyParameters* */ IntPtr keyParams, // optional
78 /* SecKeychainRef */ IntPtr importKeychain, // optional
79 /* CFArrayRef* */ out IntPtr outItems);
81 static public CFArray ItemImport (byte[] buffer, string password)
83 using (var data = CFData.FromData (buffer))
84 using (var pwstring = CFString.Create (password)) {
85 SecItemImportExportKeyParameters keyParams = new SecItemImportExportKeyParameters ();
86 keyParams.passphrase = pwstring.Handle;
88 return ItemImport (data, SecExternalFormat.PKCS12, SecExternalItemType.Aggregate, SecItemImportExportFlags.None, keyParams);
92 static CFArray ItemImport (CFData data, SecExternalFormat format, SecExternalItemType itemType,
93 SecItemImportExportFlags flags = SecItemImportExportFlags.None,
94 SecItemImportExportKeyParameters? keyParams = null)
96 return ItemImport (data, ref format, ref itemType, flags, keyParams);
99 static CFArray ItemImport (CFData data, ref SecExternalFormat format, ref SecExternalItemType itemType,
100 SecItemImportExportFlags flags = SecItemImportExportFlags.None,
101 SecItemImportExportKeyParameters? keyParams = null)
103 IntPtr keyParamsPtr = IntPtr.Zero;
104 if (keyParams != null) {
105 keyParamsPtr = Marshal.AllocHGlobal (Marshal.SizeOf (keyParams.Value));
106 if (keyParamsPtr == IntPtr.Zero)
107 throw new OutOfMemoryException ();
108 Marshal.StructureToPtr (keyParams.Value, keyParamsPtr, false);
112 var status = SecItemImport (data.Handle, IntPtr.Zero, ref format, ref itemType, flags, keyParamsPtr, IntPtr.Zero, out result);
114 if (keyParamsPtr != IntPtr.Zero)
115 Marshal.FreeHGlobal (keyParamsPtr);
117 if (status != SecStatusCode.Success)
118 throw new NotSupportedException (status.ToString ());
120 return new CFArray (result, true);
123 [DllImport (AppleTlsContext.SecurityLibrary)]
124 extern static /* SecIdentityRef */ IntPtr SecIdentityCreate (
125 /* CFAllocatorRef */ IntPtr allocator,
126 /* SecCertificateRef */ IntPtr certificate,
127 /* SecKeyRef */ IntPtr privateKey);
129 static public SecIdentity ItemImport (X509Certificate2 certificate)
131 if (!certificate.HasPrivateKey)
132 throw new NotSupportedException ();
134 using (var key = ImportPrivateKey (certificate))
135 using (var cert = new SecCertificate (certificate)) {
136 var identity = SecIdentityCreate (IntPtr.Zero, cert.Handle, key.Handle);
137 if (CFType.GetTypeID (identity) != SecIdentity.GetTypeID ())
138 throw new InvalidOperationException ();
140 return new SecIdentity (identity, true);
144 static byte[] ExportKey (RSA key)
146 #if MONO_FEATURE_BTLS
147 using (var btlsKey = MonoBtlsKey.CreateFromRSAPrivateKey (key))
148 return btlsKey.GetBytes (true);
150 return PKCS8.PrivateKeyInfo.Encode (key);
154 static SecKey ImportPrivateKey (X509Certificate2 certificate)
156 if (!certificate.HasPrivateKey)
157 throw new NotSupportedException ();
160 using (var data = CFData.FromData (ExportKey ((RSA)certificate.PrivateKey)))
161 items = ItemImport (data, SecExternalFormat.OpenSSL, SecExternalItemType.PrivateKey);
164 if (items.Count != 1)
165 throw new InvalidOperationException ("Private key import failed.");
167 var imported = items[0];
168 if (CFType.GetTypeID (imported) != SecKey.GetTypeID ())
169 throw new InvalidOperationException ("Private key import doesn't return SecKey.");
171 return new SecKey (imported, items.Handle);
177 const int SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION = 0;
179 // Native enum; don't change.
180 enum SecExternalFormat : int {
189 // Native enum; don't change.
190 enum SecExternalItemType : int {
199 // Native enum; don't change
200 enum SecItemImportExportFlags : int {
202 PemArmour = 0x00000001, /* exported blob is PEM formatted */
205 // Native struct; don't change
206 [StructLayout (LayoutKind.Sequential)]
207 struct SecItemImportExportKeyParameters {
208 public int version; /* SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION */
209 public int flags; /* SecKeyImportExportFlags bits */
210 public IntPtr passphrase; /* SecExternalFormat.PKCS12 only. Legal types are CFStringRef and CFDataRef. */
215 public IntPtr accessRef; /* SecAccessRef */
218 IntPtr keyAttributes;