d968f83851475a711589e27ea27c34ea4d14cda0
[mono.git] / mcs / class / System / Mono.AppleTls / ImportExport.cs
1 #if SECURITY_DEP && MONO_FEATURE_APPLETLS
2 // 
3 // ImportExport.cs
4 //
5 // Authors:
6 //      Sebastien Pouliot  <sebastien@xamarin.com>
7 //     
8 // Copyright 2011-2014 Xamarin Inc.
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.InteropServices;
32 using System.Security.Cryptography;
33 using System.Security.Cryptography.X509Certificates;
34 using ObjCRuntime;
35 using Mono.Net;
36
37 #if MONO_FEATURE_BTLS
38 using Mono.Btls;
39 #else
40 using Mono.Security.Cryptography;
41 #endif
42
43 namespace Mono.AppleTls {
44
45         internal partial class SecImportExport {
46                 
47                 [DllImport (AppleTlsContext.SecurityLibrary)]
48                 extern static SecStatusCode SecPKCS12Import (IntPtr pkcs12_data, IntPtr options, out IntPtr items);
49                 
50                 static public SecStatusCode ImportPkcs12 (byte[] buffer, CFDictionary options, out CFDictionary[] array)
51                 {
52                         using (CFData data = CFData.FromData (buffer)) {
53                                 return ImportPkcs12 (data, options, out array);
54                         }
55                 }
56
57                 static public SecStatusCode ImportPkcs12 (CFData data, CFDictionary options, out CFDictionary [] array)
58                 {
59                         if (options == null)
60                                 throw new ArgumentNullException ("options");
61                         
62                         IntPtr handle;
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);
67                         return code;
68                 }
69
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);
80
81                 static public CFArray ItemImport (byte[] buffer, string password)
82                 {
83                         using (var data = CFData.FromData (buffer))
84                         using (var pwstring = CFString.Create (password)) {
85                                 SecItemImportExportKeyParameters keyParams = new SecItemImportExportKeyParameters ();
86                                 keyParams.passphrase = pwstring.Handle;
87
88                                 return ItemImport (data, SecExternalFormat.PKCS12, SecExternalItemType.Aggregate, SecItemImportExportFlags.None, keyParams);
89                         }
90                 }
91
92                 static CFArray ItemImport (CFData data, SecExternalFormat format, SecExternalItemType itemType,
93                                            SecItemImportExportFlags flags = SecItemImportExportFlags.None,
94                                            SecItemImportExportKeyParameters? keyParams = null)
95                 {
96                         return ItemImport (data, ref format, ref itemType, flags, keyParams);
97                 }
98
99                 static CFArray ItemImport (CFData data, ref SecExternalFormat format, ref SecExternalItemType itemType,
100                                            SecItemImportExportFlags flags = SecItemImportExportFlags.None,
101                                            SecItemImportExportKeyParameters? keyParams = null)
102                 {
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);
109                         }
110
111                         IntPtr result;
112                         var status = SecItemImport (data.Handle, IntPtr.Zero, ref format, ref itemType, flags, keyParamsPtr, IntPtr.Zero, out result);
113
114                         if (keyParamsPtr != IntPtr.Zero)
115                                 Marshal.FreeHGlobal (keyParamsPtr);
116
117                         if (status != SecStatusCode.Success)
118                                 throw new NotSupportedException (status.ToString ());
119
120                         return new CFArray (result, true);
121                 }
122
123                 [DllImport (AppleTlsContext.SecurityLibrary)]
124                 extern static /* SecIdentityRef */ IntPtr SecIdentityCreate (
125                         /* CFAllocatorRef */ IntPtr allocator,
126                         /* SecCertificateRef */ IntPtr certificate,
127                         /* SecKeyRef */ IntPtr privateKey);
128
129                 static public SecIdentity ItemImport (X509Certificate2 certificate)
130                 {
131                         if (!certificate.HasPrivateKey)
132                                 throw new NotSupportedException ();
133
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 ();
139
140                                 return new SecIdentity (identity, true);
141                         }
142                 }
143
144                 static byte[] ExportKey (RSA key)
145                 {
146 #if MONO_FEATURE_BTLS
147                         using (var btlsKey = MonoBtlsKey.CreateFromRSAPrivateKey (key))
148                                 return btlsKey.GetBytes (true);
149 #else
150                         return PKCS8.PrivateKeyInfo.Encode (key);
151 #endif
152                 }
153
154                 static SecKey ImportPrivateKey (X509Certificate2 certificate)
155                 {
156                         if (!certificate.HasPrivateKey)
157                                 throw new NotSupportedException ();
158
159                         CFArray items;
160                         using (var data = CFData.FromData (ExportKey ((RSA)certificate.PrivateKey)))
161                                 items = ItemImport (data, SecExternalFormat.OpenSSL, SecExternalItemType.PrivateKey);
162
163                         try {
164                                 if (items.Count != 1)
165                                         throw new InvalidOperationException ("Private key import failed.");
166
167                                 var imported = items[0];
168                                 if (CFType.GetTypeID (imported) != SecKey.GetTypeID ())
169                                         throw new InvalidOperationException ("Private key import doesn't return SecKey.");
170
171                                 return new SecKey (imported, items.Handle);
172                         } finally {
173                                 items.Dispose ();
174                         }
175                 }
176
177                 const int SEC_KEY_IMPORT_EXPORT_PARAMS_VERSION = 0;
178
179                 // Native enum; don't change.
180                 enum SecExternalFormat : int {
181                         Unknown = 0,
182                         OpenSSL = 1,
183                         X509Cert = 9,
184                         PEMSequence = 10,
185                         PKCS7 = 11,
186                         PKCS12 = 12
187                 }
188
189                 // Native enum; don't change.
190                 enum SecExternalItemType : int {
191                         Unknown = 0,
192                         PrivateKey = 1,
193                         PublicKey = 2,
194                         SessionKey = 3,
195                         Certificate = 4,
196                         Aggregate = 5
197                 }
198
199                 // Native enum; don't change
200                 enum SecItemImportExportFlags : int {
201                         None,
202                         PemArmour = 0x00000001,   /* exported blob is PEM formatted */
203                 }
204
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. */
211
212                         IntPtr alertTitle;
213                         IntPtr alertPrompt;
214
215                         public IntPtr accessRef;       /* SecAccessRef */
216
217                         IntPtr keyUsage;
218                         IntPtr keyAttributes;
219                 }
220         }
221 }
222 #endif