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 MonoTlsSettings settings;
87 ICertificateValidator certificateValidator;
93 public LegacySslStream (Stream innerStream)
94 : this (innerStream, false)
98 public LegacySslStream (Stream innerStream, bool leaveInnerStreamOpen)
99 : this (innerStream, leaveInnerStreamOpen, null)
103 public LegacySslStream (Stream innerStream, bool leaveInnerStreamOpen, MonoTlsSettings settings)
104 : base (innerStream, leaveInnerStreamOpen)
106 this.settings = settings;
107 this.certificateValidator = ChainValidationHelper.GetDefaultValidator (settings);
109 #endregion // Constructors
113 public override bool CanRead {
114 get { return InnerStream.CanRead; }
117 public override bool CanSeek {
118 get { return InnerStream.CanSeek; }
121 public override bool CanTimeout {
122 get { return InnerStream.CanTimeout; }
125 public override bool CanWrite {
126 get { return InnerStream.CanWrite; }
129 public override long Length {
130 get { return InnerStream.Length; }
133 public override long Position {
134 get { return InnerStream.Position; }
136 throw new NotSupportedException ("This stream does not support seek operations");
140 // AuthenticatedStream overrides
142 public override bool IsAuthenticated {
143 get { return ssl_stream != null; }
146 public override bool IsEncrypted {
147 get { return IsAuthenticated; }
150 public override bool IsMutuallyAuthenticated {
151 get { return IsAuthenticated && (IsServer ? RemoteCertificate != null : LocalCertificate != null); }
154 public override bool IsServer {
155 get { return ssl_stream is SslServerStream; }
158 public override bool IsSigned {
159 get { return IsAuthenticated; }
162 public override int ReadTimeout {
163 get { return InnerStream.ReadTimeout; }
164 set { InnerStream.ReadTimeout = value; }
167 public override int WriteTimeout {
168 get { return InnerStream.WriteTimeout; }
169 set { InnerStream.WriteTimeout = value; }
174 public virtual bool CheckCertRevocationStatus {
176 if (!IsAuthenticated)
179 return ssl_stream.CheckCertRevocationStatus;
183 public virtual CipherAlgorithmType CipherAlgorithm {
185 CheckConnectionAuthenticated ();
187 switch (ssl_stream.CipherAlgorithm) {
188 case MonoCipherAlgorithmType.Des:
189 return CipherAlgorithmType.Des;
190 case MonoCipherAlgorithmType.None:
191 return CipherAlgorithmType.None;
192 case MonoCipherAlgorithmType.Rc2:
193 return CipherAlgorithmType.Rc2;
194 case MonoCipherAlgorithmType.Rc4:
195 return CipherAlgorithmType.Rc4;
196 case MonoCipherAlgorithmType.SkipJack:
198 case MonoCipherAlgorithmType.TripleDes:
199 return CipherAlgorithmType.TripleDes;
200 case MonoCipherAlgorithmType.Rijndael:
201 switch (ssl_stream.CipherStrength) {
203 return CipherAlgorithmType.Aes128;
205 return CipherAlgorithmType.Aes192;
207 return CipherAlgorithmType.Aes256;
212 throw new InvalidOperationException ("Not supported cipher algorithm is in use. It is likely a bug in SslStream.");
216 public virtual int CipherStrength {
218 CheckConnectionAuthenticated ();
220 return ssl_stream.CipherStrength;
224 public virtual HashAlgorithmType HashAlgorithm {
226 CheckConnectionAuthenticated ();
228 switch (ssl_stream.HashAlgorithm) {
229 case MonoHashAlgorithmType.Md5:
230 return HashAlgorithmType.Md5;
231 case MonoHashAlgorithmType.None:
232 return HashAlgorithmType.None;
233 case MonoHashAlgorithmType.Sha1:
234 return HashAlgorithmType.Sha1;
237 throw new InvalidOperationException ("Not supported hash algorithm is in use. It is likely a bug in SslStream.");
241 public virtual int HashStrength {
243 CheckConnectionAuthenticated ();
245 return ssl_stream.HashStrength;
249 public virtual ExchangeAlgorithmType KeyExchangeAlgorithm {
251 CheckConnectionAuthenticated ();
253 switch (ssl_stream.KeyExchangeAlgorithm) {
254 case MonoExchangeAlgorithmType.DiffieHellman:
255 return ExchangeAlgorithmType.DiffieHellman;
256 case MonoExchangeAlgorithmType.Fortezza:
258 case MonoExchangeAlgorithmType.None:
259 return ExchangeAlgorithmType.None;
260 case MonoExchangeAlgorithmType.RsaKeyX:
261 return ExchangeAlgorithmType.RsaKeyX;
262 case MonoExchangeAlgorithmType.RsaSign:
263 return ExchangeAlgorithmType.RsaSign;
266 throw new InvalidOperationException ("Not supported exchange algorithm is in use. It is likely a bug in SslStream.");
270 public virtual int KeyExchangeStrength {
272 CheckConnectionAuthenticated ();
274 return ssl_stream.KeyExchangeStrength;
278 X509Certificate IMonoSslStream.InternalLocalCertificate {
280 return IsServer ? ssl_stream.ServerCertificate : ((SslClientStream) ssl_stream).SelectedClientCertificate;
284 public virtual X509Certificate LocalCertificate {
286 CheckConnectionAuthenticated ();
288 return IsServer ? ssl_stream.ServerCertificate : ((SslClientStream) ssl_stream).SelectedClientCertificate;
292 public virtual X509Certificate RemoteCertificate {
294 CheckConnectionAuthenticated ();
295 return !IsServer ? ssl_stream.ServerCertificate : ((SslServerStream) ssl_stream).ClientCertificate;
299 public virtual SslProtocols SslProtocol {
301 CheckConnectionAuthenticated ();
303 switch (ssl_stream.SecurityProtocol) {
304 case MonoSecurityProtocolType.Default:
305 return SslProtocols.Default;
306 case MonoSecurityProtocolType.Ssl2:
307 return SslProtocols.Ssl2;
308 case MonoSecurityProtocolType.Ssl3:
309 return SslProtocols.Ssl3;
310 case MonoSecurityProtocolType.Tls:
311 return SslProtocols.Tls;
314 throw new InvalidOperationException ("Not supported SSL/TLS protocol is in use. It is likely a bug in SslStream.");
318 #endregion // Properties
323 AsymmetricAlgorithm GetPrivateKey (X509Certificate cert, string targetHost)
325 // FIXME: what can I do for non-X509Certificate2 ?
326 X509Certificate2 cert2 = cert as X509Certificate2;
327 return cert2 != null ? cert2.PrivateKey : null;
330 X509Certificate OnCertificateSelection (X509CertificateCollection clientCerts, X509Certificate serverCert, string targetHost, X509CertificateCollection serverRequestedCerts)
332 string [] acceptableIssuers = new string [serverRequestedCerts != null ? serverRequestedCerts.Count : 0];
333 for (int i = 0; i < acceptableIssuers.Length; i++)
334 acceptableIssuers [i] = serverRequestedCerts [i].GetIssuerName ();
335 return certificateValidator.SelectClientCertificate (targetHost, clientCerts, serverCert, acceptableIssuers);
338 public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
340 return BeginAuthenticateAsClient (targetHost, new X509CertificateCollection (), SslProtocols.Tls, false, asyncCallback, asyncState);
343 public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
346 throw new InvalidOperationException ("This SslStream is already authenticated");
348 SslClientStream s = new SslClientStream (InnerStream, targetHost, !LeaveInnerStreamOpen, GetMonoSslProtocol (enabledSslProtocols), clientCertificates);
349 s.CheckCertRevocationStatus = checkCertificateRevocation;
351 // Due to the Mono.Security internal, it cannot reuse
352 // the delegated argument, as Mono.Security creates
353 // another instance of X509Certificate which lacks
354 // private key but is filled the private key via this
356 s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string host) {
357 string hash = cert.GetCertHashString ();
358 // ... so, we cannot use the delegate argument.
359 foreach (X509Certificate cc in clientCertificates) {
360 if (cc.GetCertHashString () != hash)
362 X509Certificate2 cert2 = cc as X509Certificate2;
363 cert2 = cert2 ?? new X509Certificate2 (cc);
364 return cert2.PrivateKey;
369 // Even if validation_callback is null this allows us to verify requests where the user
370 // does not provide a verification callback but attempts to authenticate with the website
371 // as a client (see https://bugzilla.xamarin.com/show_bug.cgi?id=18962 for an example)
372 s.ServerCertValidation2 += (mcerts) => {
373 X509CertificateCollection certs = null;
374 if (mcerts != null) {
375 certs = new X509CertificateCollection ();
376 for (int i = 0; i < mcerts.Count; i++)
377 certs.Add (new X509Certificate2 (mcerts [i].RawData));
379 return ((ChainValidationHelper)certificateValidator).ValidateChain (targetHost, certs);
381 s.ClientCertSelectionDelegate = OnCertificateSelection;
385 return BeginWrite (new byte [0], 0, 0, asyncCallback, asyncState);
388 public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
390 CheckConnectionAuthenticated ();
392 return ssl_stream.BeginRead (buffer, offset, count, asyncCallback, asyncState);
395 public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback asyncCallback, object asyncState)
397 return BeginAuthenticateAsServer (serverCertificate, false, SslProtocols.Tls, false, asyncCallback, asyncState);
400 public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
403 throw new InvalidOperationException ("This SslStream is already authenticated");
405 SslServerStream s = new SslServerStream (InnerStream, serverCertificate, false, clientCertificateRequired, !LeaveInnerStreamOpen, GetMonoSslProtocol (enabledSslProtocols));
406 s.CheckCertRevocationStatus = checkCertificateRevocation;
407 // Due to the Mono.Security internal, it cannot reuse
408 // the delegated argument, as Mono.Security creates
409 // another instance of X509Certificate which lacks
410 // private key but is filled the private key via this
412 s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string targetHost) {
413 // ... so, we cannot use the delegate argument.
414 X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2 (serverCertificate);
415 return cert2 != null ? cert2.PrivateKey : null;
418 s.ClientCertValidationDelegate = delegate (X509Certificate cert, int[] certErrors) {
419 var errors = certErrors.Length > 0 ? MonoSslPolicyErrors.RemoteCertificateChainErrors : MonoSslPolicyErrors.None;
420 return ((ChainValidationHelper)certificateValidator).ValidateClientCertificate (cert, errors);
425 return BeginWrite (new byte[0], 0, 0, asyncCallback, asyncState);
428 MonoSecurityProtocolType GetMonoSslProtocol (SslProtocols ms)
431 case SslProtocols.Ssl2:
432 return MonoSecurityProtocolType.Ssl2;
433 case SslProtocols.Ssl3:
434 return MonoSecurityProtocolType.Ssl3;
435 case SslProtocols.Tls:
436 return MonoSecurityProtocolType.Tls;
438 return MonoSecurityProtocolType.Default;
442 public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
444 CheckConnectionAuthenticated ();
446 return ssl_stream.BeginWrite (buffer, offset, count, asyncCallback, asyncState);
449 public virtual void AuthenticateAsClient (string targetHost)
451 AuthenticateAsClient (targetHost, new X509CertificateCollection (), SslProtocols.Tls, false);
454 public virtual void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
456 EndAuthenticateAsClient (BeginAuthenticateAsClient (
457 targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, null, null));
460 public virtual void AuthenticateAsServer (X509Certificate serverCertificate)
462 AuthenticateAsServer (serverCertificate, false, SslProtocols.Tls, false);
465 public virtual void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
467 EndAuthenticateAsServer (BeginAuthenticateAsServer (
468 serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, null, null));
471 protected override void Dispose (bool disposing)
474 if (ssl_stream != null)
475 ssl_stream.Dispose ();
478 base.Dispose (disposing);
481 public virtual void EndAuthenticateAsClient (IAsyncResult asyncResult)
483 CheckConnectionAuthenticated ();
486 ssl_stream.EndRead (asyncResult);
488 ssl_stream.EndWrite (asyncResult);
491 public virtual void EndAuthenticateAsServer (IAsyncResult asyncResult)
493 CheckConnectionAuthenticated ();
496 ssl_stream.EndRead (asyncResult);
498 ssl_stream.EndWrite (asyncResult);
501 public override int EndRead (IAsyncResult asyncResult)
503 CheckConnectionAuthenticated ();
505 return ssl_stream.EndRead (asyncResult);
508 public override void EndWrite (IAsyncResult asyncResult)
510 CheckConnectionAuthenticated ();
512 ssl_stream.EndWrite (asyncResult);
515 public override void Flush ()
517 CheckConnectionAuthenticated ();
519 InnerStream.Flush ();
522 public override int Read (byte[] buffer, int offset, int count)
524 return EndRead (BeginRead (buffer, offset, count, null, null));
527 public override long Seek (long offset, SeekOrigin origin)
529 throw new NotSupportedException ("This stream does not support seek operations");
532 public override void SetLength (long value)
534 InnerStream.SetLength (value);
537 public override void Write (byte[] buffer, int offset, int count)
539 EndWrite (BeginWrite (buffer, offset, count, null, null));
542 public void Write (byte[] buffer)
544 Write (buffer, 0, buffer.Length);
547 void CheckConnectionAuthenticated ()
549 if (!IsAuthenticated)
550 throw new InvalidOperationException ("This operation is invalid until it is successfully authenticated");
553 public virtual Task AuthenticateAsClientAsync (string targetHost)
555 return Task.Factory.FromAsync (BeginAuthenticateAsClient, EndAuthenticateAsClient, targetHost, null);
558 public virtual Task AuthenticateAsClientAsync (string targetHost, X509CertificateCollection clientCertificates, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
560 var t = Tuple.Create (targetHost, clientCertificates, enabledSslProtocols, checkCertificateRevocation, this);
562 return Task.Factory.FromAsync ((callback, state) => {
563 var d = (Tuple<string, X509CertificateCollection, SslProtocols, bool, LegacySslStream>) state;
564 return d.Item5.BeginAuthenticateAsClient (d.Item1, d.Item2, d.Item3, d.Item4, callback, null);
565 }, EndAuthenticateAsClient, t);
568 public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate)
570 return Task.Factory.FromAsync (BeginAuthenticateAsServer, EndAuthenticateAsServer, serverCertificate, null);
573 public virtual Task AuthenticateAsServerAsync (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols enabledSslProtocols, bool checkCertificateRevocation)
575 var t = Tuple.Create (serverCertificate, clientCertificateRequired, enabledSslProtocols, checkCertificateRevocation, this);
577 return Task.Factory.FromAsync ((callback, state) => {
578 var d = (Tuple<X509Certificate, bool, SslProtocols, bool, LegacySslStream>) state;
579 return d.Item5.BeginAuthenticateAsServer (d.Item1, d.Item2, d.Item3, d.Item4, callback, null);
580 }, EndAuthenticateAsServer, t);
583 #endregion // Methods
585 #region IMonoSslStream
587 AuthenticatedStream IMonoSslStream.AuthenticatedStream {
591 TransportContext IMonoSslStream.TransportContext {
592 get { throw new NotSupportedException (); }