1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573
|
//
// System.Net.Security.SslStream.cs
//
// Authors:
// Tim Coleman (tim@timcoleman.com)
// Atsushi Enomoto (atsushi@ximian.com)
//
// Copyright (C) Tim Coleman, 2004
// (c) 2004,2007 Novell, Inc. (http://www.novell.com)
//
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if NET_2_0 && SECURITY_DEP
extern alias PrebuiltSystem;
using System;
using System.IO;
using System.Net;
using System.Security.Authentication;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.Security.Cryptography;
using Mono.Security.Protocol.Tls;
using CipherAlgorithmType = System.Security.Authentication.CipherAlgorithmType;
using HashAlgorithmType = System.Security.Authentication.HashAlgorithmType;
using ExchangeAlgorithmType = System.Security.Authentication.ExchangeAlgorithmType;
using MonoCipherAlgorithmType = Mono.Security.Protocol.Tls.CipherAlgorithmType;
using MonoHashAlgorithmType = Mono.Security.Protocol.Tls.HashAlgorithmType;
using MonoExchangeAlgorithmType = Mono.Security.Protocol.Tls.ExchangeAlgorithmType;
using MonoSecurityProtocolType = Mono.Security.Protocol.Tls.SecurityProtocolType;
using X509CertificateCollection = PrebuiltSystem::System.Security.Cryptography.X509Certificates.X509CertificateCollection;
namespace System.Net.Security
{
[MonoTODO ("Non-X509Certificate2 certificate is not supported")]
public class SslStream : AuthenticatedStream
{
#region Fields
SslStreamBase ssl_stream;
RemoteCertificateValidationCallback validation_callback;
LocalCertificateSelectionCallback selection_callback;
#endregion // Fields
#region Constructors
public SslStream (Stream innerStream)
: this (innerStream, false)
{
}
public SslStream (Stream innerStream, bool leaveStreamOpen)
: base (innerStream, leaveStreamOpen)
{
}
[MonoTODO ("certValidationCallback is not passed X509Chain and SslPolicyErrors correctly")]
public SslStream (Stream innerStream, bool leaveStreamOpen, RemoteCertificateValidationCallback certValidationCallback)
: this (innerStream, leaveStreamOpen, certValidationCallback, null)
{
}
[MonoTODO ("certValidationCallback is not passed X509Chain and SslPolicyErrors correctly")]
public SslStream (Stream innerStream, bool leaveStreamOpen, RemoteCertificateValidationCallback certValidationCallback, LocalCertificateSelectionCallback certSelectionCallback)
: base (innerStream, leaveStreamOpen)
{
// they are nullable.
validation_callback = certValidationCallback;
selection_callback = certSelectionCallback;
}
#endregion // Constructors
#region Properties
public override bool CanRead {
get { return InnerStream.CanRead; }
}
public override bool CanSeek {
get { return InnerStream.CanSeek; }
}
public override bool CanTimeout {
get { return InnerStream.CanTimeout; }
}
public override bool CanWrite {
get { return InnerStream.CanWrite; }
}
public override long Length {
get { return InnerStream.Length; }
}
public override long Position {
get { return InnerStream.Position; }
set {
throw new NotSupportedException ("This stream does not support seek operations");
}
}
// AuthenticatedStream overrides
public override bool IsAuthenticated {
get { return ssl_stream != null; }
}
public override bool IsEncrypted {
get { return IsAuthenticated; }
}
public override bool IsMutuallyAuthenticated {
get { return IsAuthenticated && (IsServer ? RemoteCertificate != null : LocalCertificate != null); }
}
public override bool IsServer {
get { return ssl_stream is SslServerStream; }
}
public override bool IsSigned {
get { return IsAuthenticated; }
}
public override int ReadTimeout {
get { return InnerStream.ReadTimeout; }
set { InnerStream.ReadTimeout = value; }
}
public override int WriteTimeout {
get { return InnerStream.WriteTimeout; }
set { InnerStream.WriteTimeout = value; }
}
// SslStream
public virtual bool CheckCertRevocationStatus {
get {
if (!IsAuthenticated)
return false;
return ssl_stream.CheckCertRevocationStatus;
}
}
public virtual CipherAlgorithmType CipherAlgorithm {
get {
CheckConnectionAuthenticated ();
switch (ssl_stream.CipherAlgorithm) {
case MonoCipherAlgorithmType.Des:
return CipherAlgorithmType.Des;
case MonoCipherAlgorithmType.None:
return CipherAlgorithmType.None;
case MonoCipherAlgorithmType.Rc2:
return CipherAlgorithmType.Rc2;
case MonoCipherAlgorithmType.Rc4:
return CipherAlgorithmType.Rc4;
case MonoCipherAlgorithmType.SkipJack:
break;
case MonoCipherAlgorithmType.TripleDes:
return CipherAlgorithmType.TripleDes;
case MonoCipherAlgorithmType.Rijndael:
switch (ssl_stream.CipherStrength) {
case 128:
return CipherAlgorithmType.Aes128;
case 192:
return CipherAlgorithmType.Aes192;
case 256:
return CipherAlgorithmType.Aes256;
}
break;
}
throw new InvalidOperationException ("Not supported cipher algorithm is in use. It is likely a bug in SslStream.");
}
}
public virtual int CipherStrength {
get {
CheckConnectionAuthenticated ();
return ssl_stream.CipherStrength;
}
}
public virtual HashAlgorithmType HashAlgorithm {
get {
CheckConnectionAuthenticated ();
switch (ssl_stream.HashAlgorithm) {
case MonoHashAlgorithmType.Md5:
return HashAlgorithmType.Md5;
case MonoHashAlgorithmType.None:
return HashAlgorithmType.None;
case MonoHashAlgorithmType.Sha1:
return HashAlgorithmType.Sha1;
}
throw new InvalidOperationException ("Not supported hash algorithm is in use. It is likely a bug in SslStream.");
}
}
public virtual int HashStrength {
get {
CheckConnectionAuthenticated ();
return ssl_stream.HashStrength;
}
}
public virtual ExchangeAlgorithmType KeyExchangeAlgorithm {
get {
CheckConnectionAuthenticated ();
switch (ssl_stream.KeyExchangeAlgorithm) {
case MonoExchangeAlgorithmType.DiffieHellman:
return ExchangeAlgorithmType.DiffieHellman;
case MonoExchangeAlgorithmType.Fortezza:
break;
case MonoExchangeAlgorithmType.None:
return ExchangeAlgorithmType.None;
case MonoExchangeAlgorithmType.RsaKeyX:
return ExchangeAlgorithmType.RsaKeyX;
case MonoExchangeAlgorithmType.RsaSign:
return ExchangeAlgorithmType.RsaSign;
}
throw new InvalidOperationException ("Not supported exchange algorithm is in use. It is likely a bug in SslStream.");
}
}
public virtual int KeyExchangeStrength {
get {
CheckConnectionAuthenticated ();
return ssl_stream.KeyExchangeStrength;
}
}
public virtual X509Certificate LocalCertificate {
get {
CheckConnectionAuthenticated ();
return IsServer ? ssl_stream.ServerCertificate : ((SslClientStream) ssl_stream).SelectedClientCertificate;
}
}
public virtual X509Certificate RemoteCertificate {
get {
CheckConnectionAuthenticated ();
return !IsServer ? ssl_stream.ServerCertificate : ((SslServerStream) ssl_stream).ClientCertificate;
}
}
public virtual SslProtocols SslProtocol {
get {
CheckConnectionAuthenticated ();
switch (ssl_stream.SecurityProtocol) {
case MonoSecurityProtocolType.Default:
return SslProtocols.Default;
case MonoSecurityProtocolType.Ssl2:
return SslProtocols.Ssl2;
case MonoSecurityProtocolType.Ssl3:
return SslProtocols.Ssl3;
case MonoSecurityProtocolType.Tls:
return SslProtocols.Tls;
}
throw new InvalidOperationException ("Not supported SSL/TLS protocol is in use. It is likely a bug in SslStream.");
}
}
#endregion // Properties
#region Methods
/*
AsymmetricAlgorithm GetPrivateKey (X509Certificate cert, string targetHost)
{
// FIXME: what can I do for non-X509Certificate2 ?
X509Certificate2 cert2 = cert as X509Certificate2;
return cert2 != null ? cert2.PrivateKey : null;
}
*/
X509Certificate OnCertificateSelection (X509CertificateCollection clientCerts, X509Certificate serverCert, string targetHost, X509CertificateCollection serverRequestedCerts)
{
string [] acceptableIssuers = new string [serverRequestedCerts != null ? serverRequestedCerts.Count : 0];
for (int i = 0; i < acceptableIssuers.Length; i++)
acceptableIssuers [i] = serverRequestedCerts [i].GetIssuerName ();
return selection_callback (this, targetHost, clientCerts, serverCert, acceptableIssuers);
}
public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, AsyncCallback asyncCallback, object asyncState)
{
return BeginAuthenticateAsClient (targetHost, new X509CertificateCollection (), SslProtocols.Tls, false, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols sslProtocolType, bool checkCertificateRevocation, AsyncCallback asyncCallback, object asyncState)
{
if (IsAuthenticated)
throw new InvalidOperationException ("This SslStream is already authenticated");
SslClientStream s = new SslClientStream (InnerStream, targetHost, !LeaveInnerStreamOpen, GetMonoSslProtocol (sslProtocolType), clientCertificates);
s.CheckCertRevocationStatus = checkCertificateRevocation;
// Due to the Mono.Security internal, it cannot reuse
// the delegated argument, as Mono.Security creates
// another instance of X509Certificate which lacks
// private key but is filled the private key via this
// delegate.
s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string host) {
string hash = cert.GetCertHashString ();
// ... so, we cannot use the delegate argument.
foreach (X509Certificate cc in clientCertificates) {
if (cc.GetCertHashString () != hash)
continue;
X509Certificate2 cert2 = cc as X509Certificate2;
cert2 = cert2 ?? new X509Certificate2 (cc);
return cert2.PrivateKey;
}
return null;
};
if (validation_callback != null)
s.ServerCertValidationDelegate = delegate (X509Certificate cert, int [] certErrors) {
X509Chain chain = new X509Chain ();
X509Certificate2 x2 = (cert as X509Certificate2);
if (x2 == null)
x2 = new X509Certificate2 (cert);
if (!ServicePointManager.CheckCertificateRevocationList)
chain.ChainPolicy.RevocationMode = X509RevocationMode.NoCheck;
// SSL specific checks (done by Mono.Security.dll SSL/TLS implementation)
SslPolicyErrors errors = SslPolicyErrors.None;
foreach (int i in certErrors) {
switch (i) {
case -2146762490: // CERT_E_PURPOSE
errors |= SslPolicyErrors.RemoteCertificateNotAvailable;
break;
case -2146762481: // CERT_E_CN_NO_MATCH
errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
break;
default:
errors |= SslPolicyErrors.RemoteCertificateChainErrors;
break;
}
}
chain.Build (x2);
// non-SSL specific X509 checks (i.e. RFC3280 related checks)
foreach (X509ChainStatus status in chain.ChainStatus) {
if (status.Status == X509ChainStatusFlags.NoError)
continue;
if ((status.Status & X509ChainStatusFlags.PartialChain) != 0)
errors |= SslPolicyErrors.RemoteCertificateNotAvailable;
else
errors |= SslPolicyErrors.RemoteCertificateChainErrors;
}
return validation_callback (this, cert, chain, errors);
};
if (selection_callback != null)
s.ClientCertSelectionDelegate = OnCertificateSelection;
ssl_stream = s;
return BeginWrite (new byte [0], 0, 0, asyncCallback, asyncState);
}
public override IAsyncResult BeginRead (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
CheckConnectionAuthenticated ();
return ssl_stream.BeginRead (buffer, offset, count, asyncCallback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, AsyncCallback callback, object asyncState)
{
return BeginAuthenticateAsServer (serverCertificate, false, SslProtocols.Tls, false, callback, asyncState);
}
public virtual IAsyncResult BeginAuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols sslProtocolType, bool checkCertificateRevocation, AsyncCallback callback, object asyncState)
{
if (IsAuthenticated)
throw new InvalidOperationException ("This SslStream is already authenticated");
SslServerStream s = new SslServerStream (InnerStream, serverCertificate, clientCertificateRequired, !LeaveInnerStreamOpen, GetMonoSslProtocol (sslProtocolType));
s.CheckCertRevocationStatus = checkCertificateRevocation;
// Due to the Mono.Security internal, it cannot reuse
// the delegated argument, as Mono.Security creates
// another instance of X509Certificate which lacks
// private key but is filled the private key via this
// delegate.
s.PrivateKeyCertSelectionDelegate = delegate (X509Certificate cert, string targetHost) {
// ... so, we cannot use the delegate argument.
X509Certificate2 cert2 = serverCertificate as X509Certificate2 ?? new X509Certificate2 (serverCertificate);
return cert2 != null ? cert2.PrivateKey : null;
};
if (validation_callback != null)
s.ClientCertValidationDelegate = delegate (X509Certificate cert, int [] certErrors) {
X509Chain chain = null;
if (cert is X509Certificate2) {
chain = new X509Chain ();
chain.Build ((X509Certificate2) cert);
}
// FIXME: SslPolicyErrors is incomplete
SslPolicyErrors errors = certErrors.Length > 0 ? SslPolicyErrors.RemoteCertificateChainErrors : SslPolicyErrors.None;
return validation_callback (this, cert, chain, errors);
};
ssl_stream = s;
return BeginRead (new byte [0], 0, 0, callback, asyncState);
}
MonoSecurityProtocolType GetMonoSslProtocol (SslProtocols ms)
{
switch (ms) {
case SslProtocols.Ssl2:
return MonoSecurityProtocolType.Ssl2;
case SslProtocols.Ssl3:
return MonoSecurityProtocolType.Ssl3;
case SslProtocols.Tls:
return MonoSecurityProtocolType.Tls;
default:
return MonoSecurityProtocolType.Default;
}
}
public override IAsyncResult BeginWrite (byte[] buffer, int offset, int count, AsyncCallback asyncCallback, object asyncState)
{
CheckConnectionAuthenticated ();
return ssl_stream.BeginWrite (buffer, offset, count, asyncCallback, asyncState);
}
public virtual void AuthenticateAsClient (string targetHost)
{
AuthenticateAsClient (targetHost, new X509CertificateCollection (), SslProtocols.Tls, false);
}
public virtual void AuthenticateAsClient (string targetHost, X509CertificateCollection clientCertificates, SslProtocols sslProtocolType, bool checkCertificateRevocation)
{
EndAuthenticateAsClient (BeginAuthenticateAsClient (
targetHost, clientCertificates, sslProtocolType, checkCertificateRevocation, null, null));
}
public virtual void AuthenticateAsServer (X509Certificate serverCertificate)
{
AuthenticateAsServer (serverCertificate, false, SslProtocols.Tls, false);
}
public virtual void AuthenticateAsServer (X509Certificate serverCertificate, bool clientCertificateRequired, SslProtocols sslProtocolType, bool checkCertificateRevocation)
{
EndAuthenticateAsServer (BeginAuthenticateAsServer (
serverCertificate, clientCertificateRequired, sslProtocolType, checkCertificateRevocation, null, null));
}
protected override void Dispose (bool disposing)
{
if (disposing) {
if (ssl_stream != null)
ssl_stream.Dispose ();
ssl_stream = null;
}
base.Dispose (disposing);
}
public virtual void EndAuthenticateAsClient (IAsyncResult asyncResult)
{
CheckConnectionAuthenticated ();
if (CanRead)
ssl_stream.EndRead (asyncResult);
else
ssl_stream.EndWrite (asyncResult);
}
public virtual void EndAuthenticateAsServer (IAsyncResult asyncResult)
{
CheckConnectionAuthenticated ();
if (CanRead)
ssl_stream.EndRead (asyncResult);
else
ssl_stream.EndWrite (asyncResult);
}
public override int EndRead (IAsyncResult asyncResult)
{
CheckConnectionAuthenticated ();
return ssl_stream.EndRead (asyncResult);
}
public override void EndWrite (IAsyncResult asyncResult)
{
CheckConnectionAuthenticated ();
ssl_stream.EndWrite (asyncResult);
}
public override void Flush ()
{
CheckConnectionAuthenticated ();
InnerStream.Flush ();
}
public override int Read (byte[] buffer, int offset, int count)
{
return EndRead (BeginRead (buffer, offset, count, null, null));
}
public override long Seek (long offset, SeekOrigin origin)
{
throw new NotSupportedException ("This stream does not support seek operations");
}
public override void SetLength (long value)
{
InnerStream.SetLength (value);
}
public override void Write (byte[] buffer, int offset, int count)
{
EndWrite (BeginWrite (buffer, offset, count, null, null));
}
public void Write (byte[] buffer)
{
Write (buffer, 0, buffer.Length);
}
void CheckConnectionAuthenticated ()
{
if (!IsAuthenticated)
throw new InvalidOperationException ("This operation is invalid until it is successfully authenticated");
}
#endregion // Methods
}
}
#endif
|