Merge pull request #3769 from evincarofautumn/fix-verify-before-allocs
[mono.git] / mcs / class / System / Mono.Btls / MonoBtlsSsl.cs
1 //
2 // MonoBtlsSsl.cs
3 //
4 // Author:
5 //       Martin Baulig <martin.baulig@xamarin.com>
6 //
7 // Copyright (c) 2015 Xamarin Inc. (http://www.xamarin.com)
8 //
9 // Permission is hereby granted, free of charge, to any person obtaining a copy
10 // of this software and associated documentation files (the "Software"), to deal
11 // in the Software without restriction, including without limitation the rights
12 // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
13 // copies of the Software, and to permit persons to whom the Software is
14 // furnished to do so, subject to the following conditions:
15 //
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
18 //
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
22 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
23 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
24 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
25 // THE SOFTWARE.
26 #if SECURITY_DEP && MONO_FEATURE_BTLS
27 using System;
28 using System.IO;
29 using System.Text;
30 using System.Runtime.InteropServices;
31 using System.Runtime.CompilerServices;
32
33 #if MONOTOUCH
34 using MonoTouch;
35 #endif
36
37 namespace Mono.Btls
38 {
39         delegate int MonoBtlsVerifyCallback (MonoBtlsX509StoreCtx ctx);
40         delegate int MonoBtlsSelectCallback ();
41
42         class MonoBtlsSsl : MonoBtlsObject
43         {
44                 internal class BoringSslHandle : MonoBtlsHandle
45                 {
46                         public BoringSslHandle (IntPtr handle)
47                                 : base (handle, true)
48                         {
49                         }
50
51                         protected override bool ReleaseHandle ()
52                         {
53                                 mono_btls_ssl_destroy (handle);
54                                 return true;
55                         }
56                 }
57
58                 [DllImport (BTLS_DYLIB)]
59                 extern static void mono_btls_ssl_destroy (IntPtr handle);
60
61                 [DllImport (BTLS_DYLIB)]
62                 extern static IntPtr mono_btls_ssl_new (IntPtr handle);
63
64                 [DllImport (BTLS_DYLIB)]
65                 extern static int mono_btls_ssl_use_certificate (IntPtr handle, IntPtr x509);
66
67                 [DllImport (BTLS_DYLIB)]
68                 extern static int mono_btls_ssl_use_private_key (IntPtr handle, IntPtr key);
69
70                 [DllImport (BTLS_DYLIB)]
71                 extern static int mono_btls_ssl_add_chain_certificate (IntPtr handle, IntPtr x509);
72
73                 [DllImport (BTLS_DYLIB)]
74                 extern static int mono_btls_ssl_accept (IntPtr handle);
75
76                 [DllImport (BTLS_DYLIB)]
77                 extern static int mono_btls_ssl_connect (IntPtr handle);
78
79                 [DllImport (BTLS_DYLIB)]
80                 extern static int mono_btls_ssl_handshake (IntPtr handle);
81
82                 [DllImport (BTLS_DYLIB)]
83                 extern static void mono_btls_ssl_close (IntPtr handle);
84
85                 [DllImport (BTLS_DYLIB)]
86                 extern static void mono_btls_ssl_set_bio (IntPtr handle, IntPtr bio);
87
88                 [DllImport (BTLS_DYLIB)]
89                 extern static int mono_btls_ssl_read (IntPtr handle, IntPtr data, int len);
90
91                 [DllImport (BTLS_DYLIB)]
92                 extern static int mono_btls_ssl_write (IntPtr handle, IntPtr data, int len);
93
94                 [DllImport (BTLS_DYLIB)]
95                 extern static int mono_btls_ssl_get_error (IntPtr handle, int ret_code);
96
97                 [DllImport (BTLS_DYLIB)]
98                 extern static int mono_btls_ssl_get_version (IntPtr handle);
99
100                 [DllImport (BTLS_DYLIB)]
101                 extern static void mono_btls_ssl_set_min_version (IntPtr handle, int version);
102
103                 [DllImport (BTLS_DYLIB)]
104                 extern static void mono_btls_ssl_set_max_version (IntPtr handle, int version);
105
106                 [DllImport (BTLS_DYLIB)]
107                 extern static int mono_btls_ssl_get_cipher (IntPtr handle);
108
109                 [DllImport (BTLS_DYLIB)]
110                 extern static int mono_btls_ssl_get_ciphers (IntPtr handle, out IntPtr data);
111
112                 [DllImport (BTLS_DYLIB)]
113                 extern static IntPtr mono_btls_ssl_get_peer_certificate (IntPtr handle);
114
115                 [DllImport (BTLS_DYLIB)]
116                 extern static int mono_btls_ssl_set_cipher_list (IntPtr handle, IntPtr str);
117
118                 [DllImport (BTLS_DYLIB)]
119                 extern static void mono_btls_ssl_print_errors_cb (IntPtr func, IntPtr ctx);
120
121                 [DllImport (BTLS_DYLIB)]
122                 extern static int mono_btls_ssl_set_verify_param (IntPtr handle, IntPtr param);
123
124                 [DllImport (BTLS_DYLIB)]
125                 extern static int mono_btls_ssl_set_server_name (IntPtr handle, IntPtr name);
126
127                 static BoringSslHandle Create_internal (MonoBtlsSslCtx ctx)
128                 {
129                         var handle = mono_btls_ssl_new (ctx.Handle.DangerousGetHandle ());
130                         if (handle == IntPtr.Zero)
131                                 throw new MonoBtlsException ();
132                         return new BoringSslHandle (handle);
133                 }
134
135                 PrintErrorsCallbackFunc printErrorsFunc;
136                 IntPtr printErrorsFuncPtr;
137
138                 public MonoBtlsSsl (MonoBtlsSslCtx ctx)
139                         : base (Create_internal (ctx))
140                 {
141                         printErrorsFunc = PrintErrorsCallback;
142                         printErrorsFuncPtr = Marshal.GetFunctionPointerForDelegate (printErrorsFunc);
143                 }
144
145                 new internal BoringSslHandle Handle {
146                         get { return (BoringSslHandle)base.Handle; }
147                 }
148
149                 public void SetBio (MonoBtlsBio bio)
150                 {
151                         CheckThrow ();
152                         mono_btls_ssl_set_bio (
153                                 Handle.DangerousGetHandle (),
154                                 bio.Handle.DangerousGetHandle ());
155                 }
156
157                 Exception ThrowError ([CallerMemberName] string callerName = null)
158                 {
159                         string errors;
160                         try {
161                                 if (callerName == null)
162                                         callerName = GetType ().Name;
163                                 errors = GetErrors ();
164                         } catch {
165                                 errors = null;
166                         }
167
168                         if (errors != null) {
169                                 Console.Error.WriteLine ("ERROR: {0} failed: {1}", callerName, errors);
170                                 throw new MonoBtlsException ("{0} failed: {1}.", callerName, errors);
171                         } else {
172                                 Console.Error.WriteLine ("ERROR: {0} failed.", callerName);
173                                 throw new MonoBtlsException ("{0} failed.", callerName);
174                         }
175                 }
176
177                 MonoBtlsSslError GetError (int ret_code)
178                 {
179                         CheckThrow ();
180                         var error = mono_btls_ssl_get_error (
181                                 Handle.DangerousGetHandle (), ret_code);
182                         return (MonoBtlsSslError)error;
183                 }
184
185                 public void SetCertificate (MonoBtlsX509 x509)
186                 {
187                         CheckThrow ();
188
189                         var ret = mono_btls_ssl_use_certificate (
190                                 Handle.DangerousGetHandle (),
191                                 x509.Handle.DangerousGetHandle ());
192                         if (ret <= 0)
193                                 throw ThrowError ();
194                 }
195
196                 public void SetPrivateKey (MonoBtlsKey key)
197                 {
198                         CheckThrow ();
199
200                         var ret = mono_btls_ssl_use_private_key (
201                                 Handle.DangerousGetHandle (),
202                                 key.Handle.DangerousGetHandle ());
203                         if (ret <= 0)
204                                 throw ThrowError ();
205                 }
206
207                 public void AddIntermediateCertificate (MonoBtlsX509 x509)
208                 {
209                         CheckThrow ();
210
211                         var ret = mono_btls_ssl_add_chain_certificate (
212                                 Handle.DangerousGetHandle (),
213                                 x509.Handle.DangerousGetHandle ());
214                         if (ret <= 0)
215                                 throw ThrowError ();
216                 }
217
218                 public MonoBtlsSslError Accept ()
219                 {
220                         CheckThrow ();
221
222                         var ret = mono_btls_ssl_accept (Handle.DangerousGetHandle ());
223
224                         var error = GetError (ret);
225                         return error;
226                 }
227
228                 public MonoBtlsSslError Connect ()
229                 {
230                         CheckThrow ();
231
232                         var ret = mono_btls_ssl_connect (Handle.DangerousGetHandle ());
233
234                         var error = GetError (ret);
235                         return error;
236                 }
237
238                 public MonoBtlsSslError Handshake ()
239                 {
240                         CheckThrow ();
241
242                         var ret = mono_btls_ssl_handshake (Handle.DangerousGetHandle ());
243
244                         var error = GetError (ret);
245                         return error;
246                 }
247
248                 delegate int PrintErrorsCallbackFunc (IntPtr str, IntPtr len, IntPtr ctx);
249
250 #if MONOTOUCH
251                 [MonoPInvokeCallback (typeof (PrintErrorsCallbackFunc))]
252 #endif
253                 static int PrintErrorsCallback (IntPtr str, IntPtr len, IntPtr ctx)
254                 {
255                         var sb = (StringBuilder)GCHandle.FromIntPtr (ctx).Target;
256                         try {
257                                 var text = Marshal.PtrToStringAnsi (str, (int)len);
258                                 sb.Append (text);
259                                 return 1;
260                         } catch {
261                                 return 0;
262                         }
263                 }
264
265                 public string GetErrors ()
266                 {
267                         var text = new StringBuilder ();
268                         var handle = GCHandle.Alloc (text);
269
270                         try {
271                                 mono_btls_ssl_print_errors_cb (printErrorsFuncPtr, GCHandle.ToIntPtr (handle));
272                                 return text.ToString ();
273                         } finally {
274                                 if (handle.IsAllocated)
275                                         handle.Free ();
276                         }
277                 }
278
279                 public void PrintErrors ()
280                 {
281                         var errors = GetErrors ();
282                         if (string.IsNullOrEmpty (errors))
283                                 return;
284                         Console.Error.WriteLine (errors);
285                 }
286
287                 public MonoBtlsSslError Read (IntPtr data, ref int dataSize)
288                 {
289                         CheckThrow ();
290                         var ret = mono_btls_ssl_read (
291                                 Handle.DangerousGetHandle (), data, dataSize);
292
293                         if (ret >= 0) {
294                                 dataSize = ret;
295                                 return MonoBtlsSslError.None;
296                         }
297
298                         var error = mono_btls_ssl_get_error (
299                                 Handle.DangerousGetHandle (), ret);
300                         dataSize = 0;
301                         return (MonoBtlsSslError)error;
302                 }
303
304                 public MonoBtlsSslError Write (IntPtr data, ref int dataSize)
305                 {
306                         CheckThrow ();
307                         var ret = mono_btls_ssl_write (
308                                 Handle.DangerousGetHandle (), data, dataSize);
309
310                         if (ret >= 0) {
311                                 dataSize = ret;
312                                 return MonoBtlsSslError.None;
313                         }
314
315                         var error = mono_btls_ssl_get_error (
316                                 Handle.DangerousGetHandle (), ret);
317                         dataSize = 0;
318                         return (MonoBtlsSslError)error;
319                 }
320
321                 public int GetVersion ()
322                 {
323                         CheckThrow ();
324                         return mono_btls_ssl_get_version (Handle.DangerousGetHandle ());
325                 }
326
327                 public void SetMinVersion (int version)
328                 {
329                         CheckThrow ();
330                         mono_btls_ssl_set_min_version (Handle.DangerousGetHandle (), version);
331                 }
332
333                 public void SetMaxVersion (int version)
334                 {
335                         CheckThrow ();
336                         mono_btls_ssl_set_max_version (Handle.DangerousGetHandle (), version);
337                 }
338
339                 public int GetCipher ()
340                 {
341                         CheckThrow ();
342                         var cipher = mono_btls_ssl_get_cipher (Handle.DangerousGetHandle ());
343                         CheckError (cipher > 0);
344                         return cipher;
345                 }
346
347                 public short[] GetCiphers ()
348                 {
349                         CheckThrow ();
350                         IntPtr data;
351                         var count = mono_btls_ssl_get_ciphers (
352                                 Handle.DangerousGetHandle (), out data);
353                         CheckError (count > 0);
354                         try {
355                                 short[] ciphers = new short[count];
356                                 Marshal.Copy (data, ciphers, 0, count);
357                                 return ciphers;
358                         } finally {
359                                 FreeDataPtr (data);
360                         }
361                 }
362
363                 public void SetCipherList (string str)
364                 {
365                         CheckThrow ();
366                         IntPtr strPtr = IntPtr.Zero;
367                         try {
368                                 strPtr = Marshal.StringToHGlobalAnsi (str);
369                                 var ret = mono_btls_ssl_set_cipher_list (
370                                         Handle.DangerousGetHandle (), strPtr);
371                                 CheckError (ret);
372                         } finally {
373                                 if (strPtr != IntPtr.Zero)
374                                         Marshal.FreeHGlobal (strPtr);
375                         }
376                 }
377
378                 public MonoBtlsX509 GetPeerCertificate ()
379                 {
380                         CheckThrow ();
381                         var x509 = mono_btls_ssl_get_peer_certificate (
382                                 Handle.DangerousGetHandle ());
383                         if (x509 == IntPtr.Zero)
384                                 return null;
385                         return new MonoBtlsX509 (new MonoBtlsX509.BoringX509Handle (x509));
386                 }
387
388                 public void SetVerifyParam (MonoBtlsX509VerifyParam param)
389                 {
390                         CheckThrow ();
391                         var ret = mono_btls_ssl_set_verify_param (
392                                 Handle.DangerousGetHandle (),
393                                 param.Handle.DangerousGetHandle ());
394                         CheckError (ret);
395                 }
396
397                 public void SetServerName (string name)
398                 {
399                         CheckThrow ();
400                         IntPtr namePtr = IntPtr.Zero;
401                         try {
402                                 namePtr = Marshal.StringToHGlobalAnsi (name);
403                                 var ret = mono_btls_ssl_set_server_name (
404                                         Handle.DangerousGetHandle (), namePtr);
405                                 CheckError (ret);
406                         } finally {
407                                 if (namePtr != IntPtr.Zero)
408                                         Marshal.FreeHGlobal (namePtr);
409                         }
410                 }
411
412                 protected override void Close ()
413                 {
414                         mono_btls_ssl_close (Handle.DangerousGetHandle ());
415                 }
416         }
417 }
418 #endif