2 // System.Net.Security.SslStream.cs
5 // Tim Coleman (tim@timcoleman.com)
6 // Atsushi Enomoto (atsushi@ximian.com)
7 // Marek Safar (marek.safar@gmail.com)
9 // Copyright (C) Tim Coleman, 2004
10 // (c) 2004,2007 Novell, Inc. (http://www.novell.com)
11 // Copyright 2011 Xamarin Inc.
15 // Permission is hereby granted, free of charge, to any person obtaining
16 // a copy of this software and associated documentation files (the
17 // "Software"), to deal in the Software without restriction, including
18 // without limitation the rights to use, copy, modify, merge, publish,
19 // distribute, sublicense, and/or sell copies of the Software, and to
20 // permit persons to whom the Software is furnished to do so, subject to
21 // the following conditions:
23 // The above copyright notice and this permission notice shall be
24 // included in all copies or substantial portions of the Software.
26 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
27 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
29 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
30 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
31 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
32 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38 extern alias PrebuiltSystem;
40 #if MONO_SECURITY_ALIAS
41 extern alias MonoSecurity;
44 #if MONO_SECURITY_ALIAS
45 using MonoCipherAlgorithmType = MonoSecurity::Mono.Security.Protocol.Tls.CipherAlgorithmType;
46 using MonoHashAlgorithmType = MonoSecurity::Mono.Security.Protocol.Tls.HashAlgorithmType;
47 using MonoExchangeAlgorithmType = MonoSecurity::Mono.Security.Protocol.Tls.ExchangeAlgorithmType;
48 using MonoSecurityProtocolType = MonoSecurity::Mono.Security.Protocol.Tls.SecurityProtocolType;
49 using MonoSecurity::Mono.Security.Protocol.Tls;
50 using MonoSecurity::Mono.Security.Interface;
52 using MonoCipherAlgorithmType = Mono.Security.Protocol.Tls.CipherAlgorithmType;
53 using MonoHashAlgorithmType = Mono.Security.Protocol.Tls.HashAlgorithmType;
54 using MonoExchangeAlgorithmType = Mono.Security.Protocol.Tls.ExchangeAlgorithmType;
55 using MonoSecurityProtocolType = Mono.Security.Protocol.Tls.SecurityProtocolType;
56 using Mono.Security.Protocol.Tls;
57 using Mono.Security.Interface;
60 using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
63 using CipherAlgorithmType = System.Security.Authentication.CipherAlgorithmType;
64 using HashAlgorithmType = System.Security.Authentication.HashAlgorithmType;
65 using ExchangeAlgorithmType = System.Security.Authentication.ExchangeAlgorithmType;
70 using System.Net.Security;
71 using System.Security.Authentication;
72 using System.Security.Cryptography.X509Certificates;
73 using System.Security.Principal;
74 using System.Security.Cryptography;
76 using System.Threading.Tasks;
78 namespace Mono.Net.Security
80 [MonoTODO ("Non-X509Certificate2 certificate is not supported")]
81 internal class LegacySslStream : AuthenticatedStream, IMonoSslStream
85 SslStreamBase ssl_stream;
86 MonoTlsProvider provider;
87 MonoTlsSettings settings;
88 ICertificateValidator certificateValidator;
94 public LegacySslStream (Stream innerStream, bool leaveInnerStreamOpen, MonoTlsProvider provider, MonoTlsSettings settings)
95 : base (innerStream, leaveInnerStreamOpen)
97 this.provider = provider;
98 this.settings = settings;
99 this.certificateValidator = ChainValidationHelper.GetDefaultValidator (provider, settings);
101 #endregion // Constructors
105 public override bool CanRead {
106 get { return InnerStream.CanRead; }
109 public override bool CanSeek {
110 get { return InnerStream.CanSeek; }
113 public override bool CanTimeout {
114 get { return InnerStream.CanTimeout; }
117 public override bool CanWrite {
118 get { return InnerStream.CanWrite; }
121 public override long Length {
122 get { return InnerStream.Length; }
125 public override long Position {
126 get { return InnerStream.Position; }
128 throw new NotSupportedException ("This stream does not support seek operations");
132 // AuthenticatedStream overrides
134 public override bool IsAuthenticated {
135 get { return ssl_stream != null; }
138 public override bool IsEncrypted {
139 get { return IsAuthenticated; }
142 public override bool IsMutuallyAuthenticated {
143 get { return IsAuthenticated && (IsServer ? RemoteCertificate != null : LocalCertificate != null); }
146 public override bool IsServer {
147 get { return ssl_stream is SslServerStream; }
150 public override bool IsSigned {
151 get { return IsAuthenticated; }
154 public override int ReadTimeout {
155 get { return InnerStream.ReadTimeout; }
156 set { InnerStream.ReadTimeout = value; }
159 public override int WriteTimeout {
160 get { return InnerStream.WriteTimeout; }
161 set { InnerStream.WriteTimeout = value; }
166 public virtual bool CheckCertRevocationStatus {
168 if (!IsAuthenticated)
171 return ssl_stream.CheckCertRevocationStatus;
175 public virtual CipherAlgorithmType CipherAlgorithm {
177 CheckConnectionAuthenticated ();
179 switch (ssl_stream.CipherAlgorithm) {
180 case MonoCipherAlgorithmType.Des:
181 return CipherAlgorithmType.Des;
182 case MonoCipherAlgorithmType.None:
183 return CipherAlgorithmType.None;
184 case MonoCipherAlgorithmType.Rc2:
185 return CipherAlgorithmType.Rc2;
186 case MonoCipherAlgorithmType.Rc4:
187 return CipherAlgorithmType.Rc4;
188 case MonoCipherAlgorithmType.SkipJack:
190 case MonoCipherAlgorithmType.TripleDes:
191 return CipherAlgorithmType.TripleDes;
192 case MonoCipherAlgorithmType.Rijndael:
193 switch (ssl_stream.CipherStrength) {
195 return CipherAlgorithmType.Aes128;
197 return CipherAlgorithmType.Aes192;
199 return CipherAlgorithmType.Aes256;
204 throw new InvalidOperationException ("Not supported cipher algorithm is in use. It is likely a bug in SslStream.");
208 public virtual int CipherStrength {
210 CheckConnectionAuthenticated ();
212 return ssl_stream.CipherStrength;
216 public virtual HashAlgorithmType HashAlgorithm {
218 CheckConnectionAuthenticated ();
220 switch (ssl_stream.HashAlgorithm) {
221 case MonoHashAlgorithmType.Md5:
222 return HashAlgorithmType.Md5;
223 case MonoHashAlgorithmType.None:
224 return HashAlgorithmType.None;
225 case MonoHashAlgorithmType.Sha1:
226 return HashAlgorithmType.Sha1;
229 throw new InvalidOperationException ("Not supported hash algorithm is in use. It is likely a bug in SslStream.");
233 public virtual int HashStrength {
235 CheckConnectionAuthenticated ();
237 return ssl_stream.HashStrength;
241 public virtual ExchangeAlgorithmType KeyExchangeAlgorithm {
243 CheckConnectionAuthenticated ();
245 switch (ssl_stream.KeyExchangeAlgorithm) {
246 case MonoExchangeAlgorithmType.DiffieHellman:
247 return ExchangeAlgorithmType.DiffieHellman;
248 case MonoExchangeAlgorithmType.Fortezza:
250 case MonoExchangeAlgorithmType.None:
251 return ExchangeAlgorithmType.None;
252 case MonoExchangeAlgorithmType.RsaKeyX:
253 return ExchangeAlgorithmType.RsaKeyX;
254 case MonoExchangeAlgorithmType.RsaSign:
255 return ExchangeAlgorithmType.RsaSign;
258 throw new InvalidOperationException ("Not supported exchange algorithm is in use. It is likely a bug in SslStream.");
262 public virtual int KeyExchangeStrength {
264 CheckConnectionAuthenticated ();
266 return ssl_stream.KeyExchangeStrength;
270 X509Certificate IMonoSslStream.InternalLocalCertificate {
272 return IsServer ? ssl_stream.ServerCertificate : ((SslClientStream) ssl_stream).SelectedClientCertificate;
276 public virtual X509Certificate LocalCertificate {
278 CheckConnectionAuthenticated ();
280 return IsServer ? ssl_stream.ServerCertificate : ((SslClientStream) ssl_stream).SelectedClientCertificate;
284 public virtual X509Certificate RemoteCertificate {
286 CheckConnectionAuthenticated ();
287 return !IsServer ? ssl_stream.ServerCertificate : ((SslServerStream) ssl_stream).ClientCertificate;
291 public virtual SslProtocols SslProtocol {
293 CheckConnectionAuthenticated ();
295 switch (ssl_stream.SecurityProtocol) {
296 case MonoSecurityProtocolType.Default:
297 return SslProtocols.Default;
298 case MonoSecurityProtocolType.Ssl2:
299 return SslProtocols.Ssl2;
300 case MonoSecurityProtocolType.Ssl3:
301 return SslProtocols.Ssl3;
302 case MonoSecurityProtocolType.Tls:
303 return SslProtocols.Tls;
306 throw new InvalidOperationException ("Not supported SSL/TLS protocol is in use. It is likely a bug in SslStream.");
310 #endregion // Properties
315 AsymmetricAlgorithm GetPrivateKey (X509Certificate cert, string targetHost)
317 // FIXME: what can I do for non-X509Certificate2 ?
318 X509Certificate2 cert2 = cert as X509Certificate2;
319 return cert2 != null ? cert2.PrivateKey : null;
322 X509Certificate OnCertificateSelection (X509CertificateCollection clientCerts, X509Certificate serverCert, string targetHost, X509CertificateCollection serverRequestedCerts)
324 string [] acceptableIssuers = new string [serverRequestedCerts != null ? serverRequestedCerts.Count : 0];
325 for (int i = 0; i < acceptableIssuers.Length; i++)
326 acceptableIssuers [i] = serverRequestedCerts [i].GetIssuerName ();
327 X509Certificate clientCertificate;
328 certificateValidator.SelectClientCertificate (targetHost, clientCerts, serverCert, acceptableIssuers, out clientCertificate);
329 return clientCertificate;
332 public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
334 return BeginAuthenticateAsClient (targetHost, new X509CertificateCollection (), SslProtocols.Tls, false, asyncCallback, asyncState);
337 public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
340 throw new InvalidOperationException ("This SslStream is already authenticated");
342 SslClientStream s = new SslClientStream (InnerStream, targetHost, !LeaveInnerStreamOpen, GetMonoSslProtocol (enabledSslProtocols), clientCertificates);
343 s.CheckCertRevocationStatus = checkCertificateRevocation;
345 // Due to the Mono.Security internal, it cannot reuse
346 // the delegated argument, as Mono.Security creates
347 // another instance of X509Certificate which lacks
348 // private key but is filled the private key via this
350 s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string host) {
351 string hash = cert.GetCertHashString ();
352 // ... so, we cannot use the delegate argument.
353 foreach (X509Certificate cc in clientCertificates) {
354 if (cc.GetCertHashString () != hash)
356 X509Certificate2 cert2 = cc as X509Certificate2;
357 cert2 = cert2 ?? new X509Certificate2 (cc);
358 return cert2.PrivateKey;
363 // Even if validation_callback is null this allows us to verify requests where the user
364 // does not provide a verification callback but attempts to authenticate with the website
365 // as a client (see https://bugzilla.xamarin.com/show_bug.cgi?id=18962 for an example)
366 s.ServerCertValidation2 += (mcerts) => {
367 X509CertificateCollection certs = null;
368 if (mcerts != null) {
369 certs = new X509CertificateCollection ();
370 for (int i = 0; i < mcerts.Count; i++)
371 certs.Add (new X509Certificate2 (mcerts [i].RawData));
373 return ((ChainValidationHelper)certificateValidator).ValidateCertificate (targetHost, false, certs);
375 s.ClientCertSelectionDelegate = OnCertificateSelection;
379 return BeginWrite (new byte [0], 0, 0, asyncCallback, asyncState);
382 public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
384 CheckConnectionAuthenticated ();
386 return ssl_stream.BeginRead (buffer, offset, count, asyncCallback, asyncState);
389 public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
391 return BeginAuthenticateAsServer (serverCertificate, false, SslProtocols.Tls, false, asyncCallback, asyncState);
394 public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
397 throw new InvalidOperationException ("This SslStream is already authenticated");
399 SslServerStream s = new SslServerStream (InnerStream, serverCertificate, false, clientCertificateRequired, !LeaveInnerStreamOpen, GetMonoSslProtocol (enabledSslProtocols));
400 s.CheckCertRevocationStatus = checkCertificateRevocation;
401 // Due to the Mono.Security internal, it cannot reuse
402 // the delegated argument, as Mono.Security creates
403 // another instance of X509Certificate which lacks
404 // private key but is filled the private key via this
406 s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string targetHost) {
407 // ... so, we cannot use the delegate argument.
408 X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2 (serverCertificate);
409 return cert2 != null ? cert2.PrivateKey : null;
412 s.ClientCertValidationDelegate = delegate (X509Certificate cert, int[] certErrors) {
413 var errors = certErrors.Length > 0 ? MonoSslPolicyErrors.RemoteCertificateChainErrors : MonoSslPolicyErrors.None;
414 return ((ChainValidationHelper)certificateValidator).ValidateClientCertificate (cert, errors);
419 return BeginWrite (new byte[0], 0, 0, asyncCallback, asyncState);
422 MonoSecurityProtocolType GetMonoSslProtocol (SslProtocols ms)
425 case SslProtocols.Ssl2:
426 return MonoSecurityProtocolType.Ssl2;
427 case SslProtocols.Ssl3:
428 return MonoSecurityProtocolType.Ssl3;
429 case SslProtocols.Tls:
430 return MonoSecurityProtocolType.Tls;
432 return MonoSecurityProtocolType.Default;
436 public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
438 CheckConnectionAuthenticated ();
440 return ssl_stream.BeginWrite (buffer, offset, count, asyncCallback, asyncState);
443 public virtual void AuthenticateAsClient (string targetHost)
445 AuthenticateAsClient (targetHost, new X509CertificateCollection (), SslProtocols.Tls, false);
448 public virtual void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
450 EndAuthenticateAsClient (BeginAuthenticateAsClient (
451 targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, null, null));
454 public virtual void AuthenticateAsServer (X509Certificate serverCertificate)
456 AuthenticateAsServer (serverCertificate, false, SslProtocols.Tls, false);
459 public virtual void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
461 EndAuthenticateAsServer (BeginAuthenticateAsServer (
462 serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, null, null));
465 protected override void Dispose (bool disposing)
468 if (ssl_stream != null)
469 ssl_stream.Dispose ();
472 base.Dispose (disposing);
475 public virtual void EndAuthenticateAsClient (IAsyncResult asyncResult)
477 CheckConnectionAuthenticated ();
480 ssl_stream.EndRead (asyncResult);
482 ssl_stream.EndWrite (asyncResult);
485 public virtual void EndAuthenticateAsServer (IAsyncResult asyncResult)
487 CheckConnectionAuthenticated ();
490 ssl_stream.EndRead (asyncResult);
492 ssl_stream.EndWrite (asyncResult);
495 public override int EndRead (IAsyncResult asyncResult)
497 CheckConnectionAuthenticated ();
499 return ssl_stream.EndRead (asyncResult);
502 public override void EndWrite (IAsyncResult asyncResult)
504 CheckConnectionAuthenticated ();
506 ssl_stream.EndWrite (asyncResult);
509 public override void Flush ()
511 CheckConnectionAuthenticated ();
513 InnerStream.Flush ();
516 public override int Read (byte[] buffer, int offset, int count)
518 return EndRead (BeginRead (buffer, offset, count, null, null));
521 public override long Seek (long offset, SeekOrigin origin)
523 throw new NotSupportedException ("This stream does not support seek operations");
526 public override void SetLength (long value)
528 InnerStream.SetLength (value);
531 public override void Write (byte[] buffer, int offset, int count)
533 EndWrite (BeginWrite (buffer, offset, count, null, null));
536 public void Write (byte[] buffer)
538 Write (buffer, 0, buffer.Length);
541 void CheckConnectionAuthenticated ()
543 if (!IsAuthenticated)
544 throw new InvalidOperationException ("This operation is invalid until it is successfully authenticated");
547 public virtual Task AuthenticateAsClientAsync (string targetHost)
549 return Task.Factory.FromAsync (BeginAuthenticateAsClient, EndAuthenticateAsClient, targetHost, null);
552 public virtual Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
554 var t = Tuple.Create (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, this);
556 return Task.Factory.FromAsync ((callback, state) => {
557 var d = (Tuple<string, X509CertificateCollection, SslProtocols, bool, LegacySslStream>) state;
558 return d.Item5.BeginAuthenticateAsClient (d.Item1, d.Item2, d.Item3, d.Item4, callback, null);
559 }, EndAuthenticateAsClient, t);
562 public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
564 return Task.Factory.FromAsync (BeginAuthenticateAsServer, EndAuthenticateAsServer, serverCertificate, null);
567 public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
569 var t = Tuple.Create (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, this);
571 return Task.Factory.FromAsync ((callback, state) => {
572 var d = (Tuple<X509Certificate, bool, SslProtocols, bool, LegacySslStream>) state;
573 return d.Item5.BeginAuthenticateAsServer (d.Item1, d.Item2, d.Item3, d.Item4, callback, null);
574 }, EndAuthenticateAsServer, t);
577 #endregion // Methods
579 #region IMonoSslStream
581 AuthenticatedStream IMonoSslStream.AuthenticatedStream {
585 TransportContext IMonoSslStream.TransportContext {
586 get { throw new NotSupportedException (); }