[BTLS]: Improve error handling. (#4317)
[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                         string file;
160                         int line;
161                         var error = MonoBtlsError.GetError (out file, out line);
162                         if (error == null)
163                                 return new MonoBtlsException (status);
164
165                         var text = MonoBtlsError.GetErrorString (error);
166
167                         string message;
168                         if (file != null)
169                                 message = string.Format ("{0} {1}\n  at {2}:{3}", status, text, file, line);
170                         else
171                                 message = string.Format ("{0} {1}", status, text);
172                         return new MonoBtlsException (message);
173                 }
174
175                 public override bool ProcessHandshake ()
176                 {
177                         var done = false;
178                         while (!done) {
179                                 Debug ("ProcessHandshake");
180                                 MonoBtlsError.ClearError ();
181                                 var status = DoProcessHandshake ();
182                                 Debug ("ProcessHandshake #1: {0}", status);
183
184                                 switch (status) {
185                                 case MonoBtlsSslError.None:
186                                         if (connected)
187                                                 done = true;
188                                         else
189                                                 connected = true;
190                                         break;
191                                 case MonoBtlsSslError.WantRead:
192                                 case MonoBtlsSslError.WantWrite:
193                                         return false;
194                                 default:
195                                         throw GetException (status);
196                                 }
197                         }
198
199                         ssl.PrintErrors ();
200
201                         return true;
202                 }
203
204                 MonoBtlsSslError DoProcessHandshake ()
205                 {
206                         if (connected)
207                                 return ssl.Handshake ();
208                         else if (IsServer)
209                                 return ssl.Accept ();
210                         else
211                                 return ssl.Connect ();
212                 }
213
214                 public override void FinishHandshake ()
215                 {
216                         InitializeSession ();
217
218                         isAuthenticated = true;
219                 }
220
221                 void SetupCertificateStore ()
222                 {
223                         MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore);
224
225                         if (Settings != null && Settings.TrustAnchors != null) {
226                                 var trust = IsServer ? MonoBtlsX509TrustKind.TRUST_CLIENT : MonoBtlsX509TrustKind.TRUST_SERVER;
227                                 ctx.CertificateStore.AddCollection (Settings.TrustAnchors, trust);
228                         }
229                 }
230
231                 void InitializeConnection ()
232                 {
233                         ctx = new MonoBtlsSslCtx ();
234
235 #if MARTIN_DEBUG
236                         errbio = MonoBtlsBio.CreateMonoStream (Console.OpenStandardError ());
237                         ctx.SetDebugBio (errbio);
238 #endif
239
240                         SetupCertificateStore ();
241
242                         if (!IsServer || AskForClientCertificate)
243                                 ctx.SetVerifyCallback (VerifyCallback, false);
244                         if (!IsServer)
245                                 ctx.SetSelectCallback (SelectCallback);
246
247                         ctx.SetVerifyParam (MonoBtlsProvider.GetVerifyParam (ServerName, IsServer));
248
249                         TlsProtocolCode minProtocol, maxProtocol;
250                         GetProtocolVersions (out minProtocol, out maxProtocol);
251
252                         ctx.SetMinVersion ((int)minProtocol);
253                         ctx.SetMaxVersion ((int)maxProtocol);
254
255                         if (Settings != null && Settings.EnabledCiphers != null) {
256                                 var ciphers = new short [Settings.EnabledCiphers.Length];
257                                 for (int i = 0; i < ciphers.Length; i++)
258                                         ciphers [i] = (short)Settings.EnabledCiphers [i];
259                                 ctx.SetCiphers (ciphers, true);
260                         }
261                 }
262
263                 void GetPeerCertificate ()
264                 {
265                         if (remoteCertificate != null)
266                                 return;
267                         using (var remoteCert = ssl.GetPeerCertificate ()) {
268                                 if (remoteCert != null)
269                                         remoteCertificate = MonoBtlsProvider.CreateCertificate (remoteCert);
270                         }
271                 }
272
273                 void InitializeSession ()
274                 {
275                         GetPeerCertificate ();
276
277                         if (IsServer && AskForClientCertificate && !certificateValidated) {
278                                 if (!ValidateCertificate (null, null))
279                                         throw new TlsException (AlertDescription.CertificateUnknown);
280                         }
281
282                         var cipher = (CipherSuiteCode)ssl.GetCipher ();
283                         var protocol = (TlsProtocolCode)ssl.GetVersion ();
284                         var serverName = ssl.GetServerName ();
285                         Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
286
287                         connectionInfo = new MonoTlsConnectionInfo {
288                                 CipherSuiteCode = cipher,
289                                 ProtocolVersion = GetProtocol (protocol),
290                                 PeerDomainName = serverName
291                         };
292                 }
293
294                 static TlsProtocols GetProtocol (TlsProtocolCode protocol)
295                 {
296                         switch (protocol) {
297                         case TlsProtocolCode.Tls10:
298                                 return TlsProtocols.Tls10;
299                         case TlsProtocolCode.Tls11:
300                                 return TlsProtocols.Tls11;
301                         case TlsProtocolCode.Tls12:
302                                 return TlsProtocols.Tls12;
303                         default:
304                                 throw new NotSupportedException ();
305                         }
306                 }
307
308                 public override void Flush ()
309                 {
310                         throw new NotImplementedException ();
311                 }
312
313                 public override int Read (byte[] buffer, int offset, int size, out bool wantMore)
314                 {
315                         Debug ("Read: {0} {1} {2}", buffer.Length, offset, size);
316
317                         var data = Marshal.AllocHGlobal (size);
318                         if (data == IntPtr.Zero)
319                                 throw new OutOfMemoryException ();
320
321                         try {
322                                 MonoBtlsError.ClearError ();
323                                 var status = ssl.Read (data, ref size);
324                                 Debug ("Read done: {0} {1}", status, size);
325
326                                 if (status == MonoBtlsSslError.WantRead) {
327                                         wantMore = true;
328                                         return 0;
329                                 } else if (status != MonoBtlsSslError.None) {
330                                         throw GetException (status);
331                                 }
332
333                                 if (size > 0)
334                                         Marshal.Copy (data, buffer, offset, size);
335
336                                 wantMore = false;
337                                 return size;
338                         } finally {
339                                 Marshal.FreeHGlobal (data);
340                         }
341                 }
342
343                 public override int Write (byte[] buffer, int offset, int size, out bool wantMore)
344                 {
345                         Debug ("Write: {0} {1} {2}", buffer.Length, offset, size);
346
347                         var data = Marshal.AllocHGlobal (size);
348                         if (data == IntPtr.Zero)
349                                 throw new OutOfMemoryException ();
350
351                         try {
352                                 MonoBtlsError.ClearError ();
353                                 Marshal.Copy (buffer, offset, data, size);
354                                 var status = ssl.Write (data, ref size);
355                                 Debug ("Write done: {0} {1}", status, size);
356
357                                 if (status == MonoBtlsSslError.WantWrite) {
358                                         wantMore = true;
359                                         return 0;
360                                 } else if (status != MonoBtlsSslError.None) {
361                                         throw GetException (status);
362                                 }
363
364                                 wantMore = false;
365                                 return size;
366                         } finally {
367                                 Marshal.FreeHGlobal (data);
368                         }
369                 }
370
371                 public override void Close ()
372                 {
373                         Debug ("Close!");
374
375                         if (ssl != null) {
376                                 ssl.Dispose ();
377                                 ssl = null;
378                         }
379                         if (ctx != null) {
380                                 ctx.Dispose ();
381                                 ctx = null;
382                         }
383                         if (bio != null) {
384                                 bio.Dispose ();
385                                 bio = null;
386                         }
387                         if (errbio != null) {
388                                 errbio.Dispose ();
389                                 errbio = null;
390                         }
391                 }
392
393                 void Dispose<T> (ref T disposable)
394                         where T : class, IDisposable
395                 {
396                         try {
397                                 if (disposable != null)
398                                         disposable.Dispose ();
399                         } catch {
400                                 ;
401                         } finally {
402                                 disposable = null;
403                         }
404                 }
405
406                 protected override void Dispose (bool disposing)
407                 {
408                         try {
409                                 if (disposing) {
410                                         Dispose (ref remoteCertificate);
411                                         Dispose (ref nativeServerCertificate);
412                                         Dispose (ref nativeClientCertificate);
413                                         Dispose (ref clientCertificate);
414                                         Dispose (ref ctx);
415                                         Dispose (ref ssl);
416                                         Dispose (ref bio);
417                                         Dispose (ref errbio);
418                                 }
419                         } finally {
420                                 base.Dispose (disposing);
421                         }
422                 }
423
424                 int IMonoBtlsBioMono.Read (byte[] buffer, int offset, int size, out bool wantMore)
425                 {
426                         Debug ("InternalRead: {0} {1}", offset, size);
427                         var ret = Parent.InternalRead (buffer, offset, size, out wantMore);
428                         Debug ("InternalReadDone: {0} {1}", ret, wantMore);
429                         return ret;
430                 }
431
432                 bool IMonoBtlsBioMono.Write (byte[] buffer, int offset, int size)
433                 {
434                         Debug ("InternalWrite: {0} {1}", offset, size);
435                         var ret = Parent.InternalWrite (buffer, offset, size);
436                         Debug ("InternalWrite done: {0}", ret);
437                         return ret;
438                 }
439
440                 void IMonoBtlsBioMono.Flush ()
441                 {
442                         ;
443                 }
444
445                 void IMonoBtlsBioMono.Close ()
446                 {
447                         ;
448                 }
449
450                 public override bool HasContext {
451                         get { return ssl != null && ssl.IsValid; }
452                 }
453                 public override bool IsAuthenticated {
454                         get { return isAuthenticated; }
455                 }
456                 public override MonoTlsConnectionInfo ConnectionInfo {
457                         get { return connectionInfo; }
458                 }
459                 internal override bool IsRemoteCertificateAvailable {
460                         get { return remoteCertificate != null; }
461                 }
462                 internal override X509Certificate LocalClientCertificate {
463                         get { return clientCertificate; }
464                 }
465                 public override X509Certificate RemoteCertificate {
466                         get { return remoteCertificate; }
467                 }
468                 public override TlsProtocols NegotiatedProtocol {
469                         get { return connectionInfo.ProtocolVersion; }
470                 }
471         }
472 }
473 #endif