2 // System.Net.ServicePointManager
5 // Lawrence Pit (loz@cable.a2000.nl)
6 // Gonzalo Paniagua Javier (gonzalo@novell.com)
8 // Copyright (c) 2003-2010 Novell, Inc (http://www.novell.com)
12 // Permission is hereby granted, free of charge, to any person obtaining
13 // a copy of this software and associated documentation files (the
14 // "Software"), to deal in the Software without restriction, including
15 // without limitation the rights to use, copy, modify, merge, publish,
16 // distribute, sublicense, and/or sell copies of the Software, and to
17 // permit persons to whom the Software is furnished to do so, subject to
18 // the following conditions:
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
23 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
24 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
25 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
26 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
27 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
28 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
29 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 #if MONOTOUCH || MONODROID
35 using Mono.Security.Protocol.Tls;
36 using MSX = Mono.Security.X509;
37 using Mono.Security.X509.Extensions;
39 extern alias MonoSecurity;
40 using MonoSecurity::Mono.Security.X509.Extensions;
41 using MonoSecurity::Mono.Security.Protocol.Tls;
42 using MSX = MonoSecurity::Mono.Security.X509;
45 using System.Text.RegularExpressions;
49 using System.Threading;
50 using System.Collections;
51 using System.Collections.Generic;
52 using System.Collections.Specialized;
53 using System.Configuration;
54 using System.Net.Configuration;
55 using System.Security.Cryptography.X509Certificates;
57 using System.Globalization;
58 using System.Net.Security;
59 using System.Diagnostics;
63 // A service point manager manages service points (duh!).
64 // A service point maintains a list of connections (per scheme + authority).
65 // According to HttpWebRequest.ConnectionGroupName each connection group
66 // creates additional connections. therefor, a service point has a hashtable
67 // of connection groups where each value is a list of connections.
69 // when we need to make an HttpWebRequest, we need to do the following:
70 // 1. find service point, given Uri and Proxy
71 // 2. find connection group, given service point and group name
72 // 3. find free connection in connection group, or create one (if ok due to limits)
73 // 4. lease connection
75 // 6. when finished, return connection
81 public partial class ServicePointManager {
83 Uri uri; // schema/host/port
87 public SPKey (Uri uri, Uri proxy, bool use_connect) {
90 this.use_connect = use_connect;
97 public bool UseConnect {
98 get { return use_connect; }
101 public bool UsesProxy {
102 get { return proxy != null; }
105 public override int GetHashCode () {
107 hash = hash * 31 + ((use_connect) ? 1 : 0);
108 hash = hash * 31 + uri.GetHashCode ();
109 hash = hash * 31 + (proxy != null ? proxy.GetHashCode () : 0);
113 public override bool Equals (object obj) {
114 SPKey other = obj as SPKey;
119 if (!uri.Equals (other.uri))
121 if (use_connect != other.use_connect || UsesProxy != other.UsesProxy)
123 if (UsesProxy && !proxy.Equals (other.proxy))
129 private static HybridDictionary servicePoints = new HybridDictionary ();
133 private static ICertificatePolicy policy = new DefaultCertificatePolicy ();
134 private static int defaultConnectionLimit = DefaultPersistentConnectionLimit;
135 private static int maxServicePointIdleTime = 100000; // 100 seconds
136 private static int maxServicePoints = 0;
137 private static bool _checkCRL = false;
138 private static SecurityProtocolType _securityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
141 static bool expectContinue = false;
143 static bool expectContinue = true;
145 static bool useNagle;
146 static RemoteCertificateValidationCallback server_cert_cb;
147 static bool tcp_keepalive;
148 static int tcp_keepalive_time;
149 static int tcp_keepalive_interval;
153 public const int DefaultNonPersistentConnectionLimit = 4;
155 public const int DefaultPersistentConnectionLimit = 10;
157 public const int DefaultPersistentConnectionLimit = 2;
161 const string configKey = "system.net/connectionManagement";
162 static ConnectionManagementData manager;
165 static ServicePointManager ()
168 #if CONFIGURATION_DEP
169 object cfg = ConfigurationManager.GetSection (configKey);
170 ConnectionManagementSection s = cfg as ConnectionManagementSection;
172 manager = new ConnectionManagementData (null);
173 foreach (ConnectionManagementElement e in s.ConnectionManagement)
174 manager.Add (e.Address, e.MaxConnection);
176 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
180 manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
181 if (manager != null) {
182 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
188 private ServicePointManager ()
194 [Obsolete ("Use ServerCertificateValidationCallback instead", false)]
195 public static ICertificatePolicy CertificatePolicy {
196 get { return policy; }
197 set { policy = value; }
200 [MonoTODO("CRL checks not implemented")]
201 public static bool CheckCertificateRevocationList {
202 get { return _checkCRL; }
203 set { _checkCRL = false; } // TODO - don't yet accept true
206 public static int DefaultConnectionLimit {
207 get { return defaultConnectionLimit; }
210 throw new ArgumentOutOfRangeException ("value");
212 defaultConnectionLimit = value;
215 manager.Add ("*", defaultConnectionLimit);
220 static Exception GetMustImplement ()
222 return new NotImplementedException ();
226 public static int DnsRefreshTimeout
229 throw GetMustImplement ();
232 throw GetMustImplement ();
237 public static bool EnableDnsRoundRobin
240 throw GetMustImplement ();
243 throw GetMustImplement ();
247 public static int MaxServicePointIdleTime {
249 return maxServicePointIdleTime;
252 if (value < -2 || value > Int32.MaxValue)
253 throw new ArgumentOutOfRangeException ("value");
254 maxServicePointIdleTime = value;
258 public static int MaxServicePoints {
260 return maxServicePoints;
264 throw new ArgumentException ("value");
266 maxServicePoints = value;
271 // we need it for SslClientStream
276 static SecurityProtocolType SecurityProtocol {
277 get { return _securityProtocol; }
278 set { _securityProtocol = value; }
281 public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
284 return server_cert_cb;
287 server_cert_cb = value;
291 public static bool Expect100Continue {
292 get { return expectContinue; }
293 set { expectContinue = value; }
296 public static bool UseNagleAlgorithm {
297 get { return useNagle; }
298 set { useNagle = value; }
302 public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
305 if (keepAliveTime <= 0)
306 throw new ArgumentOutOfRangeException ("keepAliveTime", "Must be greater than 0");
307 if (keepAliveInterval <= 0)
308 throw new ArgumentOutOfRangeException ("keepAliveInterval", "Must be greater than 0");
311 tcp_keepalive = enabled;
312 tcp_keepalive_time = keepAliveTime;
313 tcp_keepalive_interval = keepAliveInterval;
316 public static ServicePoint FindServicePoint (Uri address)
318 return FindServicePoint (address, GlobalProxySelection.Select);
321 public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
323 return FindServicePoint (new Uri(uriString), proxy);
326 public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
329 throw new ArgumentNullException ("address");
331 var origAddress = new Uri (address.Scheme + "://" + address.Authority);
333 bool usesProxy = false;
334 bool useConnect = false;
335 if (proxy != null && !proxy.IsBypassed(address)) {
337 bool isSecure = address.Scheme == "https";
338 address = proxy.GetProxy (address);
339 if (address.Scheme != "http" && !isSecure)
340 throw new NotSupportedException ("Proxy scheme not supported.");
342 if (isSecure && address.Scheme == "http")
346 address = new Uri (address.Scheme + "://" + address.Authority);
348 ServicePoint sp = null;
349 SPKey key = new SPKey (origAddress, usesProxy ? address : null, useConnect);
350 lock (servicePoints) {
351 sp = servicePoints [key] as ServicePoint;
355 if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
356 throw new InvalidOperationException ("maximum number of service points reached");
360 limit = defaultConnectionLimit;
362 string addr = address.ToString ();
363 limit = (int) manager.GetMaxConnections (addr);
365 sp = new ServicePoint (address, limit, maxServicePointIdleTime);
366 sp.Expect100Continue = expectContinue;
367 sp.UseNagleAlgorithm = useNagle;
368 sp.UsesProxy = usesProxy;
369 sp.UseConnect = useConnect;
370 sp.SetTcpKeepAlive (tcp_keepalive, tcp_keepalive_time, tcp_keepalive_interval);
371 servicePoints.Add (key, sp);
378 internal class ChainValidationHelper {
381 RemoteCertificateValidationCallback cb;
384 static bool is_macosx = System.IO.File.Exists (OSX509Certificates.SecurityLibrary);
385 static X509RevocationMode revocation_mode;
387 static ChainValidationHelper ()
389 revocation_mode = X509RevocationMode.NoCheck;
391 string str = Environment.GetEnvironmentVariable ("MONO_X509_REVOCATION_MODE");
392 if (String.IsNullOrEmpty (str))
394 revocation_mode = (X509RevocationMode) Enum.Parse (typeof (X509RevocationMode), str, true);
400 public ChainValidationHelper (object sender, string hostName)
402 this.sender = sender;
406 public RemoteCertificateValidationCallback ServerCertificateValidationCallback {
409 cb = ServicePointManager.ServerCertificateValidationCallback;
415 // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
416 // and the new ServerCertificateValidationCallback is not null
417 internal ValidationResult ValidateChain (MSX.X509CertificateCollection certs)
419 // user_denied is true if the user callback is called and returns false
420 bool user_denied = false;
421 if (certs == null || certs.Count == 0)
424 ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
426 X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
427 int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
428 SslPolicyErrors errors = 0;
429 X509Chain chain = null;
432 // The X509Chain is not really usable with MonoTouch (since the decision is not based on this data)
433 // However if someone wants to override the results (good or bad) from iOS then they will want all
434 // the certificates that the server provided (which generally does not include the root) so, only
435 // if there's a user callback, we'll create the X509Chain but won't build it
436 // ref: https://bugzilla.xamarin.com/show_bug.cgi?id=7245
437 if (ServerCertificateValidationCallback != null) {
439 chain = new X509Chain ();
440 chain.ChainPolicy = new X509ChainPolicy ();
442 chain.ChainPolicy.RevocationMode = revocation_mode;
444 for (int i = 1; i < certs.Count; i++) {
445 X509Certificate2 c2 = new X509Certificate2 (certs [i].RawData);
446 chain.ChainPolicy.ExtraStore.Add (c2);
452 if (!chain.Build (leaf))
453 errors |= GetErrorsFromChain (chain);
454 } catch (Exception e) {
455 Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
456 Console.Error.WriteLine ("Please, report this problem to the Mono team");
457 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
460 // for OSX and iOS we're using the native API to check for the SSL server policy and host names
462 if (!CheckCertificateUsage (leaf)) {
463 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
464 status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
467 if (!CheckServerIdentity (certs [0], host)) {
468 errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
469 status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
473 // Attempt to use OSX certificates
474 // Ideally we should return the SecTrustResult
475 OSX509Certificates.SecTrustResult trustResult = OSX509Certificates.SecTrustResult.Deny;
477 trustResult = OSX509Certificates.TrustEvaluateSsl (certs, host);
478 // We could use the other values of trustResult to pass this extra information
479 // to the .NET 2 callback for values like SecTrustResult.Confirm
480 result = (trustResult == OSX509Certificates.SecTrustResult.Proceed ||
481 trustResult == OSX509Certificates.SecTrustResult.Unspecified);
487 // TrustEvaluateSsl was successful so there's no trust error
488 // IOW we discard our own chain (since we trust OSX one instead)
491 // callback and DefaultCertificatePolicy needs this since 'result' is not specified
492 status11 = (int) trustResult;
493 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
499 #if MONODROID && SECURITY_DEP
500 result = AndroidPlatform.TrustEvaluateSsl (certs, sender, leaf, chain, errors);
502 // chain.Build() + GetErrorsFromChain() (above) will ALWAYS fail on
503 // Android (there are no mozroots or preinstalled root certificates),
504 // thus `errors` will ALWAYS have RemoteCertificateChainErrors.
505 // Android just verified the chain; clear RemoteCertificateChainErrors.
506 errors &= ~SslPolicyErrors.RemoteCertificateChainErrors;
510 if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
511 ServicePoint sp = null;
512 HttpWebRequest req = sender as HttpWebRequest;
514 sp = req.ServicePointNoLock;
515 if (status11 == 0 && errors != 0)
516 status11 = GetStatusFromChain (chain);
519 result = policy.CheckValidationResult (sp, leaf, req, status11);
520 user_denied = !result && !(policy is DefaultCertificatePolicy);
522 // If there's a 2.0 callback, it takes precedence
523 if (ServerCertificateValidationCallback != null) {
524 result = ServerCertificateValidationCallback (sender, leaf, chain, errors);
525 user_denied = !result;
527 return new ValidationResult (result, user_denied, status11);
530 static int GetStatusFromChain (X509Chain chain)
533 foreach (var status in chain.ChainStatus) {
534 X509ChainStatusFlags flags = status.Status;
535 if (flags == X509ChainStatusFlags.NoError)
539 if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) result = 0x800B0101;
540 // CERT_E_VALIDITYPERIODNESTING
541 else if ((flags & X509ChainStatusFlags.NotTimeNested) != 0) result = 0x800B0102;
543 else if ((flags & X509ChainStatusFlags.Revoked) != 0) result = 0x800B010C;
544 // TRUST_E_CERT_SIGNATURE
545 else if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) result = 0x80096004;
546 // CERT_E_WRONG_USAGE
547 else if ((flags & X509ChainStatusFlags.NotValidForUsage) != 0) result = 0x800B0110;
548 // CERT_E_UNTRUSTEDROOT
549 else if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0) result = 0x800B0109;
550 // CRYPT_E_NO_REVOCATION_CHECK
551 else if ((flags & X509ChainStatusFlags.RevocationStatusUnknown) != 0) result = 0x80092012;
553 else if ((flags & X509ChainStatusFlags.Cyclic) != 0) result = 0x800B010A;
554 // TRUST_E_FAIL - generic
555 else if ((flags & X509ChainStatusFlags.InvalidExtension) != 0) result = 0x800B010B;
556 // CERT_E_UNTRUSTEDROOT
557 else if ((flags & X509ChainStatusFlags.InvalidPolicyConstraints) != 0) result = 0x800B010D;
558 // TRUST_E_BASIC_CONSTRAINTS
559 else if ((flags & X509ChainStatusFlags.InvalidBasicConstraints) != 0) result = 0x80096019;
560 // CERT_E_INVALID_NAME
561 else if ((flags & X509ChainStatusFlags.InvalidNameConstraints) != 0) result = 0x800B0114;
562 // CERT_E_INVALID_NAME
563 else if ((flags & X509ChainStatusFlags.HasNotSupportedNameConstraint) != 0) result = 0x800B0114;
564 // CERT_E_INVALID_NAME
565 else if ((flags & X509ChainStatusFlags.HasNotDefinedNameConstraint) != 0) result = 0x800B0114;
566 // CERT_E_INVALID_NAME
567 else if ((flags & X509ChainStatusFlags.HasNotPermittedNameConstraint) != 0) result = 0x800B0114;
568 // CERT_E_INVALID_NAME
569 else if ((flags & X509ChainStatusFlags.HasExcludedNameConstraint) != 0) result = 0x800B0114;
571 else if ((flags & X509ChainStatusFlags.PartialChain) != 0) result = 0x800B010A;
573 else if ((flags & X509ChainStatusFlags.CtlNotTimeValid) != 0) result = 0x800B0101;
574 // TRUST_E_CERT_SIGNATURE
575 else if ((flags & X509ChainStatusFlags.CtlNotSignatureValid) != 0) result = 0x80096004;
576 // CERT_E_WRONG_USAGE
577 else if ((flags & X509ChainStatusFlags.CtlNotValidForUsage) != 0) result = 0x800B0110;
578 // CRYPT_E_NO_REVOCATION_CHECK
579 else if ((flags & X509ChainStatusFlags.OfflineRevocation) != 0) result = 0x80092012;
580 // CERT_E_ISSUERCHAINING
581 else if ((flags & X509ChainStatusFlags.NoIssuanceChainPolicy) != 0) result = 0x800B0107;
582 else result = 0x800B010B; // TRUST_E_FAIL - generic
584 break; // Exit the loop on the first error
589 static SslPolicyErrors GetErrorsFromChain (X509Chain chain)
591 SslPolicyErrors errors = SslPolicyErrors.None;
592 foreach (var status in chain.ChainStatus) {
593 if (status.Status == X509ChainStatusFlags.NoError)
595 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
601 static X509KeyUsageFlags s_flags = X509KeyUsageFlags.DigitalSignature |
602 X509KeyUsageFlags.KeyAgreement |
603 X509KeyUsageFlags.KeyEncipherment;
604 // Adapted to System 2.0+ from TlsServerCertificate.cs
605 //------------------------------
606 // Note: this method only works for RSA certificates
607 // DH certificates requires some changes - does anyone use one ?
608 static bool CheckCertificateUsage (X509Certificate2 cert)
611 // certificate extensions are required for this
612 // we "must" accept older certificates without proofs
613 if (cert.Version < 3)
616 X509KeyUsageExtension kux = (cert.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
617 X509EnhancedKeyUsageExtension eku = (cert.Extensions ["2.5.29.37"] as X509EnhancedKeyUsageExtension);
618 if (kux != null && eku != null) {
619 // RFC3280 states that when both KeyUsageExtension and
620 // ExtendedKeyUsageExtension are present then BOTH should
622 if ((kux.KeyUsages & s_flags) == 0)
624 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
625 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
626 } else if (kux != null) {
627 return ((kux.KeyUsages & s_flags) != 0);
628 } else if (eku != null) {
629 // Server Authentication (1.3.6.1.5.5.7.3.1) or
630 // Netscape Server Gated Crypto (2.16.840.1.113730.4)
631 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
632 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
635 // last chance - try with older (deprecated) Netscape extensions
636 X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
638 string text = ext.NetscapeCertType (false);
639 return text.IndexOf ("SSL Server Authentication", StringComparison.Ordinal) != -1;
642 } catch (Exception e) {
643 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
644 Console.Error.WriteLine ("Please, report this problem to the Mono team");
649 // RFC2818 - HTTP Over TLS, Section 3.1
650 // http://www.ietf.org/rfc/rfc2818.txt
652 // 1. if present MUST use subjectAltName dNSName as identity
653 // 1.1. if multiples entries a match of any one is acceptable
654 // 1.2. wildcard * is acceptable
655 // 2. URI may be an IP address -> subjectAltName.iPAddress
656 // 2.1. exact match is required
657 // 3. Use of the most specific Common Name (CN=) in the Subject
658 // 3.1 Existing practice but DEPRECATED
659 static bool CheckServerIdentity (MSX.X509Certificate cert, string targetHost)
662 MSX.X509Extension ext = cert.Extensions ["2.5.29.17"];
665 SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
666 // 1.1 - multiple dNSName
667 foreach (string dns in subjectAltName.DNSNames) {
668 // 1.2 TODO - wildcard support
669 if (Match (targetHost, dns))
673 foreach (string ip in subjectAltName.IPAddresses) {
674 // 2.1. Exact match required
675 if (ip == targetHost)
679 // 3. Common Name (CN=)
680 return CheckDomainName (cert.SubjectName, targetHost);
681 } catch (Exception e) {
682 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
683 Console.Error.WriteLine ("Please, report this problem to the Mono team");
688 static bool CheckDomainName (string subjectName, string targetHost)
690 string domainName = String.Empty;
691 Regex search = new Regex(@"CN\s*=\s*([^,]*)");
692 MatchCollection elements = search.Matches(subjectName);
693 if (elements.Count == 1) {
694 if (elements[0].Success)
695 domainName = elements[0].Groups[1].Value.ToString();
698 return Match (targetHost, domainName);
701 // ensure the pattern is valid wrt to RFC2595 and RFC2818
702 // http://www.ietf.org/rfc/rfc2595.txt
703 // http://www.ietf.org/rfc/rfc2818.txt
704 static bool Match (string hostname, string pattern)
706 // check if this is a pattern
707 int index = pattern.IndexOf ('*');
709 // not a pattern, do a direct case-insensitive comparison
710 return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
713 // check pattern validity
714 // A "*" wildcard character MAY be used as the left-most name component in the certificate.
716 // unless this is the last char (valid)
717 if (index != pattern.Length - 1) {
718 // then the next char must be a dot .'.
719 if (pattern [index + 1] != '.')
723 // only one (A) wildcard is supported
724 int i2 = pattern.IndexOf ('*', index + 1);
728 // match the end of the pattern
729 string end = pattern.Substring (index + 1);
730 int length = hostname.Length - end.Length;
731 // no point to check a pattern that is longer than the hostname
735 if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
738 // special case, we start with the wildcard
740 // ensure we hostname non-matched part (start) doesn't contain a dot
741 int i3 = hostname.IndexOf ('.');
742 return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
745 // match the start of the pattern
746 string start = pattern.Substring (0, index);
747 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);