339ce4e57ced28d5dc8fe88eea4da5206abda013
[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                         var serverName = ssl.GetServerName ();
274                         Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
275
276                         connectionInfo = new MonoTlsConnectionInfo {
277                                 CipherSuiteCode = cipher,
278                                 ProtocolVersion = GetProtocol (protocol),
279                                 PeerDomainName = serverName
280                         };
281                 }
282
283                 static TlsProtocols GetProtocol (TlsProtocolCode protocol)
284                 {
285                         switch (protocol) {
286                         case TlsProtocolCode.Tls10:
287                                 return TlsProtocols.Tls10;
288                         case TlsProtocolCode.Tls11:
289                                 return TlsProtocols.Tls11;
290                         case TlsProtocolCode.Tls12:
291                                 return TlsProtocols.Tls12;
292                         default:
293                                 throw new NotSupportedException ();
294                         }
295                 }
296
297                 public override void Flush ()
298                 {
299                         throw new NotImplementedException ();
300                 }
301
302                 public override int Read (byte[] buffer, int offset, int size, out bool wantMore)
303                 {
304                         Debug ("Read: {0} {1} {2}", buffer.Length, offset, size);
305
306                         var data = Marshal.AllocHGlobal (size);
307                         if (data == IntPtr.Zero)
308                                 throw new OutOfMemoryException ();
309
310                         try {
311                                 MonoBtlsError.ClearError ();
312                                 var status = ssl.Read (data, ref size);
313                                 Debug ("Read done: {0} {1}", status, size);
314
315                                 if (status == MonoBtlsSslError.WantRead) {
316                                         wantMore = true;
317                                         return 0;
318                                 } else if (status != MonoBtlsSslError.None) {
319                                         throw GetException (status);
320                                 }
321
322                                 if (size > 0)
323                                         Marshal.Copy (data, buffer, offset, size);
324
325                                 wantMore = false;
326                                 return size;
327                         } finally {
328                                 Marshal.FreeHGlobal (data);
329                         }
330                 }
331
332                 public override int Write (byte[] buffer, int offset, int size, out bool wantMore)
333                 {
334                         Debug ("Write: {0} {1} {2}", buffer.Length, offset, size);
335
336                         var data = Marshal.AllocHGlobal (size);
337                         if (data == IntPtr.Zero)
338                                 throw new OutOfMemoryException ();
339
340                         try {
341                                 MonoBtlsError.ClearError ();
342                                 Marshal.Copy (buffer, offset, data, size);
343                                 var status = ssl.Write (data, ref size);
344                                 Debug ("Write done: {0} {1}", status, size);
345
346                                 if (status == MonoBtlsSslError.WantWrite) {
347                                         wantMore = true;
348                                         return 0;
349                                 } else if (status != MonoBtlsSslError.None) {
350                                         throw GetException (status);
351                                 }
352
353                                 wantMore = false;
354                                 return size;
355                         } finally {
356                                 Marshal.FreeHGlobal (data);
357                         }
358                 }
359
360                 public override void Close ()
361                 {
362                         Debug ("Close!");
363
364                         if (ssl != null) {
365                                 ssl.Dispose ();
366                                 ssl = null;
367                         }
368                         if (ctx != null) {
369                                 ctx.Dispose ();
370                                 ctx = null;
371                         }
372                         if (bio != null) {
373                                 bio.Dispose ();
374                                 bio = null;
375                         }
376                         if (errbio != null) {
377                                 errbio.Dispose ();
378                                 errbio = null;
379                         }
380                 }
381
382                 void Dispose<T> (ref T disposable)
383                         where T : class, IDisposable
384                 {
385                         try {
386                                 if (disposable != null)
387                                         disposable.Dispose ();
388                         } catch {
389                                 ;
390                         } finally {
391                                 disposable = null;
392                         }
393                 }
394
395                 protected override void Dispose (bool disposing)
396                 {
397                         try {
398                                 if (disposing) {
399                                         Dispose (ref remoteCertificate);
400                                         Dispose (ref nativeServerCertificate);
401                                         Dispose (ref nativeClientCertificate);
402                                         Dispose (ref clientCertificate);
403                                         Dispose (ref ctx);
404                                         Dispose (ref ssl);
405                                         Dispose (ref bio);
406                                         Dispose (ref errbio);
407                                 }
408                         } finally {
409                                 base.Dispose (disposing);
410                         }
411                 }
412
413                 int IMonoBtlsBioMono.Read (byte[] buffer, int offset, int size, out bool wantMore)
414                 {
415                         Debug ("InternalRead: {0} {1}", offset, size);
416                         var ret = Parent.InternalRead (buffer, offset, size, out wantMore);
417                         Debug ("InternalReadDone: {0} {1}", ret, wantMore);
418                         return ret;
419                 }
420
421                 bool IMonoBtlsBioMono.Write (byte[] buffer, int offset, int size)
422                 {
423                         Debug ("InternalWrite: {0} {1}", offset, size);
424                         var ret = Parent.InternalWrite (buffer, offset, size);
425                         Debug ("InternalWrite done: {0}", ret);
426                         return ret;
427                 }
428
429                 void IMonoBtlsBioMono.Flush ()
430                 {
431                         ;
432                 }
433
434                 void IMonoBtlsBioMono.Close ()
435                 {
436                         ;
437                 }
438
439                 public override bool HasContext {
440                         get { return ssl != null && ssl.IsValid; }
441                 }
442                 public override bool IsAuthenticated {
443                         get { return isAuthenticated; }
444                 }
445                 public override MonoTlsConnectionInfo ConnectionInfo {
446                         get { return connectionInfo; }
447                 }
448                 internal override bool IsRemoteCertificateAvailable {
449                         get { return remoteCertificate != null; }
450                 }
451                 internal override X509Certificate LocalClientCertificate {
452                         get { return clientCertificate; }
453                 }
454                 public override X509Certificate RemoteCertificate {
455                         get { return remoteCertificate; }
456                 }
457                 public override TlsProtocols NegotiatedProtocol {
458                         get { return connectionInfo.ProtocolVersion; }
459                 }
460         }
461 }
462 #endif