Merge pull request #3955 from kumpera/fix-embedding-api
[mono.git] / mcs / class / System / Mono.Btls / MonoBtlsContext.cs
1 //
2 // MonoBtlsContext.cs
3 //
4 // Author:
5 //       Martin Baulig <martin.baulig@xamarin.com>
6 //
7 // Copyright (c) 2016 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 #if MONO_SECURITY_ALIAS
28 extern alias MonoSecurity;
29 #endif
30
31 using System;
32 using System.IO;
33 using System.Threading;
34 using System.Threading.Tasks;
35 using System.Security.Cryptography.X509Certificates;
36 using System.Security.Authentication;
37 using System.Runtime.InteropServices;
38
39 #if MONO_SECURITY_ALIAS
40 using MonoSecurity::Mono.Security.Interface;
41 #else
42 using Mono.Security.Interface;
43 #endif
44
45 using MNS = Mono.Net.Security;
46
47 namespace Mono.Btls
48 {
49         class MonoBtlsContext : MNS.MobileTlsContext, IMonoBtlsBioMono
50         {
51                 X509Certificate remoteCertificate;
52                 X509Certificate clientCertificate;
53                 X509CertificateImplBtls nativeServerCertificate;
54                 X509CertificateImplBtls nativeClientCertificate;
55                 MonoBtlsSslCtx ctx;
56                 MonoBtlsSsl ssl;
57                 MonoBtlsBio bio;
58                 MonoBtlsBio errbio;
59
60                 MonoTlsConnectionInfo connectionInfo;
61                 bool certificateValidated;
62                 bool isAuthenticated;
63                 bool connected;
64
65                 public MonoBtlsContext (
66                         MNS.MobileAuthenticatedStream parent,
67                         bool serverMode, string targetHost,
68                         SslProtocols enabledProtocols, X509Certificate serverCertificate,
69                         X509CertificateCollection clientCertificates, bool askForClientCert)
70                         : base (parent, serverMode, targetHost, enabledProtocols,
71                                 serverCertificate, clientCertificates, askForClientCert)
72                 {
73                         if (serverMode)
74                                 nativeServerCertificate = GetPrivateCertificate (serverCertificate);
75                 }
76
77                 static X509CertificateImplBtls GetPrivateCertificate (X509Certificate certificate)
78                 {
79                         var impl = certificate.Impl as X509CertificateImplBtls;
80                         if (impl != null)
81                                 return (X509CertificateImplBtls)impl.Clone ();
82
83                         var password = Guid.NewGuid ().ToString ();
84                         var buffer = certificate.Export (X509ContentType.Pfx, password);
85
86                         impl = new X509CertificateImplBtls ();
87                         impl.Import (buffer, password, X509KeyStorageFlags.DefaultKeySet);
88                         return impl;
89                 }
90
91                 new public MonoBtlsProvider Provider {
92                         get { return (MonoBtlsProvider)base.Provider; }
93                 }
94
95                 int VerifyCallback (MonoBtlsX509StoreCtx storeCtx)
96                 {
97                         using (var chainImpl = new X509ChainImplBtls (storeCtx))
98                         using (var managedChain = new X509Chain (chainImpl)) {
99                                 var leaf = managedChain.ChainElements[0].Certificate;
100                                 var result = ValidateCertificate (leaf, managedChain);
101                                 certificateValidated = true;
102                                 return result ? 1 : 0;
103                         }
104                 }
105
106                 int SelectCallback ()
107                 {
108                         Debug ("SELECT CALLBACK!");
109
110                         GetPeerCertificate ();
111                         if (remoteCertificate == null)
112                                 throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
113
114                         var clientCert = SelectClientCertificate (remoteCertificate, null);
115                         Debug ("SELECT CALLBACK #1: {0}", clientCert);
116                         if (clientCert == null)
117                                 return 1;
118
119                         nativeClientCertificate = GetPrivateCertificate (clientCert);
120                         Debug ("SELECT CALLBACK #2: {0}", nativeClientCertificate);
121                         clientCertificate = new X509Certificate (nativeClientCertificate);
122                         SetPrivateCertificate (nativeClientCertificate);
123                         return 1;
124                 }
125
126                 public override void StartHandshake ()
127                 {
128                         InitializeConnection ();
129
130                         ssl = new MonoBtlsSsl (ctx);
131
132                         bio = new MonoBtlsBioMono (this);
133                         ssl.SetBio (bio);
134
135                         if (IsServer) {
136                                 SetPrivateCertificate (nativeServerCertificate);
137                         } else {
138                                 ssl.SetServerName (ServerName);
139                         }
140                 }
141
142                 void SetPrivateCertificate (X509CertificateImplBtls privateCert)
143                 {
144                         Debug ("SetPrivateCertificate: {0}", privateCert);
145                         ssl.SetCertificate (privateCert.X509);
146                         ssl.SetPrivateKey (privateCert.NativePrivateKey);
147                         var intermediate = privateCert.IntermediateCertificates;
148                         if (intermediate == null)
149                                 return;
150                         for (int i = 0; i < intermediate.Count; i++) {
151                                 var impl = (X509CertificateImplBtls)intermediate [i];
152                                 Debug ("SetPrivateCertificate - add intermediate: {0}", impl);
153                                 ssl.AddIntermediateCertificate (impl.X509);
154                         }
155                 }
156
157                 static Exception GetException (MonoBtlsSslError status)
158                 {
159                         var error = MonoBtlsError.GetError ();
160                         var text = MonoBtlsError.GetErrorString (error);
161                         return new MonoBtlsException ("{0} {1}", status, text);
162                 }
163
164                 public override bool ProcessHandshake ()
165                 {
166                         var done = false;
167                         while (!done) {
168                                 Debug ("ProcessHandshake");
169                                 MonoBtlsError.ClearError ();
170                                 var status = DoProcessHandshake ();
171                                 Debug ("ProcessHandshake #1: {0}", status);
172
173                                 switch (status) {
174                                 case MonoBtlsSslError.None:
175                                         if (connected)
176                                                 done = true;
177                                         else
178                                                 connected = true;
179                                         break;
180                                 case MonoBtlsSslError.WantRead:
181                                 case MonoBtlsSslError.WantWrite:
182                                         return false;
183                                 default:
184                                         throw GetException (status);
185                                 }
186                         }
187
188                         ssl.PrintErrors ();
189
190                         return true;
191                 }
192
193                 MonoBtlsSslError DoProcessHandshake ()
194                 {
195                         if (connected)
196                                 return ssl.Handshake ();
197                         else if (IsServer)
198                                 return ssl.Accept ();
199                         else
200                                 return ssl.Connect ();
201                 }
202
203                 public override void FinishHandshake ()
204                 {
205                         InitializeSession ();
206
207                         isAuthenticated = true;
208                 }
209
210                 void SetupCertificateStore ()
211                 {
212                         MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
213
214                         if (Settings != null && Settings.TrustAnchors != null) {
215                                 var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
216                                 ctx.CertificateStore.AddCollection (Settings.TrustAnchors, trust);
217                         }
218                 }
219
220                 void InitializeConnection ()
221                 {
222                         ctx = new MonoBtlsSslCtx ();
223
224 #if MARTIN_DEBUG
225                         errbio = MonoBtlsBio.CreateMonoStream (Console.OpenStandardError ());
226                         ctx.SetDebugBio (errbio);
227 #endif
228
229                         SetupCertificateStore ();
230
231                         if (!IsServer || AskForClientCertificate)
232                                 ctx.SetVerifyCallback (VerifyCallback, false);
233                         if (!IsServer)
234                                 ctx.SetSelectCallback (SelectCallback);
235
236                         ctx.SetVerifyParam (MonoBtlsProvider.GetVerifyParam (ServerName, IsServer));
237
238                         TlsProtocolCode minProtocol, maxProtocol;
239                         GetProtocolVersions (out minProtocol, out maxProtocol);
240
241                         ctx.SetMinVersion ((int)minProtocol);
242                         ctx.SetMaxVersion ((int)maxProtocol);
243
244                         if (Settings != null && Settings.EnabledCiphers != null) {
245                                 var ciphers = new short [Settings.EnabledCiphers.Length];
246                                 for (int i = 0; i < ciphers.Length; i++)
247                                         ciphers [i] = (short)Settings.EnabledCiphers [i];
248                                 ctx.SetCiphers (ciphers, true);
249                         }
250                 }
251
252                 void GetPeerCertificate ()
253                 {
254                         if (remoteCertificate != null)
255                                 return;
256                         using (var remoteCert = ssl.GetPeerCertificate ()) {
257                                 if (remoteCert != null)
258                                         remoteCertificate = MonoBtlsProvider.CreateCertificate (remoteCert);
259                         }
260                 }
261
262                 void InitializeSession ()
263                 {
264                         GetPeerCertificate ();
265
266                         if (IsServer && AskForClientCertificate && !certificateValidated) {
267                                 if (!ValidateCertificate (null, null))
268                                         throw new TlsException (AlertDescription.CertificateUnknown);
269                         }
270
271                         var cipher = (CipherSuiteCode)ssl.GetCipher ();
272                         var protocol = (TlsProtocolCode)ssl.GetVersion ();
273                         Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
274
275                         connectionInfo = new MonoTlsConnectionInfo {
276                                 CipherSuiteCode = cipher,
277                                 ProtocolVersion = GetProtocol (protocol)
278                         };
279                 }
280
281                 static TlsProtocols GetProtocol (TlsProtocolCode protocol)
282                 {
283                         switch (protocol) {
284                         case TlsProtocolCode.Tls10:
285                                 return TlsProtocols.Tls10;
286                         case TlsProtocolCode.Tls11:
287                                 return TlsProtocols.Tls11;
288                         case TlsProtocolCode.Tls12:
289                                 return TlsProtocols.Tls12;
290                         default:
291                                 throw new NotSupportedException ();
292                         }
293                 }
294
295                 public override void Flush ()
296                 {
297                         throw new NotImplementedException ();
298                 }
299
300                 public override int Read (byte[] buffer, int offset, int size, out bool wantMore)
301                 {
302                         Debug ("Read: {0} {1} {2}", buffer.Length, offset, size);
303
304                         var data = Marshal.AllocHGlobal (size);
305                         if (data == IntPtr.Zero)
306                                 throw new OutOfMemoryException ();
307
308                         try {
309                                 MonoBtlsError.ClearError ();
310                                 var status = ssl.Read (data, ref size);
311                                 Debug ("Read done: {0} {1}", status, size);
312
313                                 if (status == MonoBtlsSslError.WantRead) {
314                                         wantMore = true;
315                                         return 0;
316                                 } else if (status != MonoBtlsSslError.None) {
317                                         throw GetException (status);
318                                 }
319
320                                 if (size > 0)
321                                         Marshal.Copy (data, buffer, offset, size);
322
323                                 wantMore = false;
324                                 return size;
325                         } finally {
326                                 Marshal.FreeHGlobal (data);
327                         }
328                 }
329
330                 public override int Write (byte[] buffer, int offset, int size, out bool wantMore)
331                 {
332                         Debug ("Write: {0} {1} {2}", buffer.Length, offset, size);
333
334                         var data = Marshal.AllocHGlobal (size);
335                         if (data == IntPtr.Zero)
336                                 throw new OutOfMemoryException ();
337
338                         try {
339                                 MonoBtlsError.ClearError ();
340                                 Marshal.Copy (buffer, offset, data, size);
341                                 var status = ssl.Write (data, ref size);
342                                 Debug ("Write done: {0} {1}", status, size);
343
344                                 if (status == MonoBtlsSslError.WantWrite) {
345                                         wantMore = true;
346                                         return 0;
347                                 } else if (status != MonoBtlsSslError.None) {
348                                         throw GetException (status);
349                                 }
350
351                                 wantMore = false;
352                                 return size;
353                         } finally {
354                                 Marshal.FreeHGlobal (data);
355                         }
356                 }
357
358                 public override void Close ()
359                 {
360                         Debug ("Close!");
361                         ssl.Dispose ();
362                 }
363
364                 void Dispose<T> (ref T disposable)
365                         where T : class, IDisposable
366                 {
367                         try {
368                                 if (disposable != null)
369                                         disposable.Dispose ();
370                         } catch {
371                                 ;
372                         } finally {
373                                 disposable = null;
374                         }
375                 }
376
377                 protected override void Dispose (bool disposing)
378                 {
379                         try {
380                                 if (disposing) {
381                                         Dispose (ref remoteCertificate);
382                                         Dispose (ref nativeServerCertificate);
383                                         Dispose (ref nativeClientCertificate);
384                                         Dispose (ref clientCertificate);
385                                         Dispose (ref ctx);
386                                         Dispose (ref ssl);
387                                         Dispose (ref bio);
388                                         Dispose (ref errbio);
389                                 }
390                         } finally {
391                                 base.Dispose (disposing);
392                         }
393                 }
394
395                 int IMonoBtlsBioMono.Read (byte[] buffer, int offset, int size, out bool wantMore)
396                 {
397                         Debug ("InternalRead: {0} {1}", offset, size);
398                         var ret = Parent.InternalRead (buffer, offset, size, out wantMore);
399                         Debug ("InternalReadDone: {0} {1}", ret, wantMore);
400                         return ret;
401                 }
402
403                 bool IMonoBtlsBioMono.Write (byte[] buffer, int offset, int size)
404                 {
405                         Debug ("InternalWrite: {0} {1}", offset, size);
406                         var ret = Parent.InternalWrite (buffer, offset, size);
407                         Debug ("InternalWrite done: {0}", ret);
408                         return ret;
409                 }
410
411                 void IMonoBtlsBioMono.Flush ()
412                 {
413                         ;
414                 }
415
416                 void IMonoBtlsBioMono.Close ()
417                 {
418                         ;
419                 }
420
421                 public override bool HasContext {
422                         get { return ssl != null && ssl.IsValid; }
423                 }
424                 public override bool IsAuthenticated {
425                         get { return isAuthenticated; }
426                 }
427                 public override MonoTlsConnectionInfo ConnectionInfo {
428                         get { return connectionInfo; }
429                 }
430                 internal override bool IsRemoteCertificateAvailable {
431                         get { return remoteCertificate != null; }
432                 }
433                 internal override X509Certificate LocalClientCertificate {
434                         get { return clientCertificate; }
435                 }
436                 public override X509Certificate RemoteCertificate {
437                         get { return remoteCertificate; }
438                 }
439                 public override TlsProtocols NegotiatedProtocol {
440                         get { return connectionInfo.ProtocolVersion; }
441                 }
442         }
443 }
444 #endif