5 // Martin Baulig <martin.baulig@xamarin.com>
7 // Copyright (c) 2016 Xamarin Inc. (http://www.xamarin.com)
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:
16 // The above copyright notice and this permission notice shall be included in
17 // all copies or substantial portions of the Software.
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
26 #if SECURITY_DEP && MONO_FEATURE_BTLS
27 #if MONO_SECURITY_ALIAS
28 extern alias MonoSecurity;
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;
39 #if MONO_SECURITY_ALIAS
40 using MonoSecurity::Mono.Security.Interface;
42 using Mono.Security.Interface;
45 using MNS = Mono.Net.Security;
49 class MonoBtlsContext : MNS.MobileTlsContext, IMonoBtlsBioMono
51 X509Certificate remoteCertificate;
52 X509Certificate clientCertificate;
53 X509CertificateImplBtls nativeServerCertificate;
54 X509CertificateImplBtls nativeClientCertificate;
60 MonoTlsConnectionInfo connectionInfo;
61 bool certificateValidated;
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)
74 nativeServerCertificate = GetPrivateCertificate (serverCertificate);
77 static X509CertificateImplBtls GetPrivateCertificate (X509Certificate certificate)
79 var impl = certificate.Impl as X509CertificateImplBtls;
81 return (X509CertificateImplBtls)impl.Clone ();
83 var password = Guid.NewGuid ().ToString ();
84 var buffer = certificate.Export (X509ContentType.Pfx, password);
86 impl = new X509CertificateImplBtls ();
87 impl.Import (buffer, password, X509KeyStorageFlags.DefaultKeySet);
91 new public MonoBtlsProvider Provider {
92 get { return (MonoBtlsProvider)base.Provider; }
95 int VerifyCallback (MonoBtlsX509StoreCtx storeCtx)
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;
106 int SelectCallback ()
108 Debug ("SELECT CALLBACK!");
110 GetPeerCertificate ();
111 if (remoteCertificate == null)
112 throw new TlsException (AlertDescription.InternalError, "Cannot request client certificate before receiving one from the server.");
114 var clientCert = SelectClientCertificate (remoteCertificate, null);
115 Debug ("SELECT CALLBACK #1: {0}", clientCert);
116 if (clientCert == null)
119 nativeClientCertificate = GetPrivateCertificate (clientCert);
120 Debug ("SELECT CALLBACK #2: {0}", nativeClientCertificate);
121 clientCertificate = new X509Certificate (nativeClientCertificate);
122 SetPrivateCertificate (nativeClientCertificate);
126 public override void StartHandshake ()
128 InitializeConnection ();
130 ssl = new MonoBtlsSsl (ctx);
132 bio = new MonoBtlsBioMono (this);
136 SetPrivateCertificate (nativeServerCertificate);
138 ssl.SetServerName (ServerName);
142 void SetPrivateCertificate (X509CertificateImplBtls privateCert)
144 Debug ("SetPrivateCertificate: {0}", privateCert);
145 ssl.SetCertificate (privateCert.X509);
146 ssl.SetPrivateKey (privateCert.NativePrivateKey);
147 var intermediate = privateCert.IntermediateCertificates;
148 if (intermediate == null)
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);
157 static Exception GetException (MonoBtlsSslError status)
161 var error = MonoBtlsError.GetError (out file, out line);
163 return new MonoBtlsException (status);
165 var text = MonoBtlsError.GetErrorString (error);
169 message = string.Format ("{0} {1}\n at {2}:{3}", status, text, file, line);
171 message = string.Format ("{0} {1}", status, text);
172 return new MonoBtlsException (message);
175 public override bool ProcessHandshake ()
179 Debug ("ProcessHandshake");
180 MonoBtlsError.ClearError ();
181 var status = DoProcessHandshake ();
182 Debug ("ProcessHandshake #1: {0}", status);
185 case MonoBtlsSslError.None:
191 case MonoBtlsSslError.WantRead:
192 case MonoBtlsSslError.WantWrite:
195 throw GetException (status);
204 MonoBtlsSslError DoProcessHandshake ()
207 return ssl.Handshake ();
209 return ssl.Accept ();
211 return ssl.Connect ();
214 public override void FinishHandshake ()
216 InitializeSession ();
218 isAuthenticated = true;
221 void InitializeConnection ()
223 ctx = new MonoBtlsSslCtx ();
226 errbio = MonoBtlsBio.CreateMonoStream (Console.OpenStandardError ());
227 ctx.SetDebugBio (errbio);
230 MonoBtlsProvider.SetupCertificateStore (ctx.CertificateStore, Settings, IsServer);
232 if (!IsServer || AskForClientCertificate)
233 ctx.SetVerifyCallback (VerifyCallback, false);
235 ctx.SetSelectCallback (SelectCallback);
237 ctx.SetVerifyParam (MonoBtlsProvider.GetVerifyParam (ServerName, IsServer));
239 TlsProtocolCode minProtocol, maxProtocol;
240 GetProtocolVersions (out minProtocol, out maxProtocol);
242 ctx.SetMinVersion ((int)minProtocol);
243 ctx.SetMaxVersion ((int)maxProtocol);
245 if (Settings != null && Settings.EnabledCiphers != null) {
246 var ciphers = new short [Settings.EnabledCiphers.Length];
247 for (int i = 0; i < ciphers.Length; i++)
248 ciphers [i] = (short)Settings.EnabledCiphers [i];
249 ctx.SetCiphers (ciphers, true);
253 void GetPeerCertificate ()
255 if (remoteCertificate != null)
257 using (var remoteCert = ssl.GetPeerCertificate ()) {
258 if (remoteCert != null)
259 remoteCertificate = MonoBtlsProvider.CreateCertificate (remoteCert);
263 void InitializeSession ()
265 GetPeerCertificate ();
267 if (IsServer && AskForClientCertificate && !certificateValidated) {
268 if (!ValidateCertificate (null, null))
269 throw new TlsException (AlertDescription.CertificateUnknown);
272 var cipher = (CipherSuiteCode)ssl.GetCipher ();
273 var protocol = (TlsProtocolCode)ssl.GetVersion ();
274 var serverName = ssl.GetServerName ();
275 Debug ("GET CONNECTION INFO: {0:x}:{0} {1:x}:{1} {2}", cipher, protocol, (TlsProtocolCode)protocol);
277 connectionInfo = new MonoTlsConnectionInfo {
278 CipherSuiteCode = cipher,
279 ProtocolVersion = GetProtocol (protocol),
280 PeerDomainName = serverName
284 static TlsProtocols GetProtocol (TlsProtocolCode protocol)
287 case TlsProtocolCode.Tls10:
288 return TlsProtocols.Tls10;
289 case TlsProtocolCode.Tls11:
290 return TlsProtocols.Tls11;
291 case TlsProtocolCode.Tls12:
292 return TlsProtocols.Tls12;
294 throw new NotSupportedException ();
298 public override void Flush ()
300 throw new NotImplementedException ();
303 public override int Read (byte[] buffer, int offset, int size, out bool wantMore)
305 Debug ("Read: {0} {1} {2}", buffer.Length, offset, size);
307 var data = Marshal.AllocHGlobal (size);
308 if (data == IntPtr.Zero)
309 throw new OutOfMemoryException ();
312 MonoBtlsError.ClearError ();
313 var status = ssl.Read (data, ref size);
314 Debug ("Read done: {0} {1}", status, size);
316 if (status == MonoBtlsSslError.WantRead) {
319 } else if (status != MonoBtlsSslError.None) {
320 throw GetException (status);
324 Marshal.Copy (data, buffer, offset, size);
329 Marshal.FreeHGlobal (data);
333 public override int Write (byte[] buffer, int offset, int size, out bool wantMore)
335 Debug ("Write: {0} {1} {2}", buffer.Length, offset, size);
337 var data = Marshal.AllocHGlobal (size);
338 if (data == IntPtr.Zero)
339 throw new OutOfMemoryException ();
342 MonoBtlsError.ClearError ();
343 Marshal.Copy (buffer, offset, data, size);
344 var status = ssl.Write (data, ref size);
345 Debug ("Write done: {0} {1}", status, size);
347 if (status == MonoBtlsSslError.WantWrite) {
350 } else if (status != MonoBtlsSslError.None) {
351 throw GetException (status);
357 Marshal.FreeHGlobal (data);
361 public override void Close ()
377 if (errbio != null) {
383 void Dispose<T> (ref T disposable)
384 where T : class, IDisposable
387 if (disposable != null)
388 disposable.Dispose ();
396 protected override void Dispose (bool disposing)
400 Dispose (ref remoteCertificate);
401 Dispose (ref nativeServerCertificate);
402 Dispose (ref nativeClientCertificate);
403 Dispose (ref clientCertificate);
407 Dispose (ref errbio);
410 base.Dispose (disposing);
414 int IMonoBtlsBioMono.Read (byte[] buffer, int offset, int size, out bool wantMore)
416 Debug ("InternalRead: {0} {1}", offset, size);
417 var ret = Parent.InternalRead (buffer, offset, size, out wantMore);
418 Debug ("InternalReadDone: {0} {1}", ret, wantMore);
422 bool IMonoBtlsBioMono.Write (byte[] buffer, int offset, int size)
424 Debug ("InternalWrite: {0} {1}", offset, size);
425 var ret = Parent.InternalWrite (buffer, offset, size);
426 Debug ("InternalWrite done: {0}", ret);
430 void IMonoBtlsBioMono.Flush ()
435 void IMonoBtlsBioMono.Close ()
440 public override bool HasContext {
441 get { return ssl != null && ssl.IsValid; }
443 public override bool IsAuthenticated {
444 get { return isAuthenticated; }
446 public override MonoTlsConnectionInfo ConnectionInfo {
447 get { return connectionInfo; }
449 internal override bool IsRemoteCertificateAvailable {
450 get { return remoteCertificate != null; }
452 internal override X509Certificate LocalClientCertificate {
453 get { return clientCertificate; }
455 public override X509Certificate RemoteCertificate {
456 get { return remoteCertificate; }
458 public override TlsProtocols NegotiatedProtocol {
459 get { return connectionInfo.ProtocolVersion; }