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.
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.Configuration;
36 using System.Net.Configuration;
37 using System.Security.Cryptography.X509Certificates;
39 using System.Globalization;
40 using System.Net.Security;
42 using System.Text.RegularExpressions;
44 using Mono.Security.Cryptography;
45 using Mono.Security.X509.Extensions;
46 using Mono.Security.Protocol.Tls;
47 using MSX = Mono.Security.X509;
52 // A service point manager manages service points (duh!).
53 // A service point maintains a list of connections (per scheme + authority).
54 // According to HttpWebRequest.ConnectionGroupName each connection group
55 // creates additional connections. therefor, a service point has a hashtable
56 // of connection groups where each value is a list of connections.
58 // when we need to make an HttpWebRequest, we need to do the following:
59 // 1. find service point, given Uri and Proxy
60 // 2. find connection group, given service point and group name
61 // 3. find free connection in connection group, or create one (if ok due to limits)
62 // 4. lease connection
64 // 6. when finished, return connection
71 internal class ServicePointManager {
73 public class ServicePointManager {
76 Uri uri; // schema/host/port
79 public SPKey (Uri uri, bool use_connect) {
81 this.use_connect = use_connect;
88 public bool UseConnect {
89 get { return use_connect; }
92 public override int GetHashCode () {
93 return uri.GetHashCode () + ((use_connect) ? 1 : 0);
96 public override bool Equals (object obj) {
97 SPKey other = obj as SPKey;
102 return (uri.Equals (other.uri) && other.use_connect == use_connect);
106 private static HybridDictionary servicePoints = new HybridDictionary ();
110 private static ICertificatePolicy policy = new DefaultCertificatePolicy ();
111 private static int defaultConnectionLimit = DefaultPersistentConnectionLimit;
112 private static int maxServicePointIdleTime = 900000; // 15 minutes
113 private static int maxServicePoints = 0;
114 private static bool _checkCRL = false;
115 private static SecurityProtocolType _securityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls;
119 static bool expectContinue = false;
121 static bool expectContinue = true;
123 static bool useNagle;
125 static RemoteCertificateValidationCallback server_cert_cb;
129 public const int DefaultNonPersistentConnectionLimit = 4;
130 public const int DefaultPersistentConnectionLimit = 2;
133 const string configKey = "system.net/connectionManagement";
134 static ConnectionManagementData manager;
137 static ServicePointManager ()
140 #if NET_2_0 && CONFIGURATION_DEP
141 object cfg = ConfigurationManager.GetSection (configKey);
142 ConnectionManagementSection s = cfg as ConnectionManagementSection;
144 manager = new ConnectionManagementData (null);
145 foreach (ConnectionManagementElement e in s.ConnectionManagement)
146 manager.Add (e.Address, e.MaxConnection);
148 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
152 manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
153 if (manager != null) {
154 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");
160 private ServicePointManager ()
167 [Obsolete ("Use ServerCertificateValidationCallback instead", false)]
169 public static ICertificatePolicy CertificatePolicy {
170 get { return policy; }
171 set { policy = value; }
175 // we need it for SslClientStream
178 [MonoTODO("CRL checks not implemented")]
181 static bool CheckCertificateRevocationList {
182 get { return _checkCRL; }
183 set { _checkCRL = false; } // TODO - don't yet accept true
186 public static int DefaultConnectionLimit {
187 get { return defaultConnectionLimit; }
190 throw new ArgumentOutOfRangeException ("value");
192 defaultConnectionLimit = value;
197 static Exception GetMustImplement ()
199 return new NotImplementedException ();
203 public static int DnsRefreshTimeout
206 throw GetMustImplement ();
209 throw GetMustImplement ();
214 public static bool EnableDnsRoundRobin
217 throw GetMustImplement ();
220 throw GetMustImplement ();
225 public static int MaxServicePointIdleTime {
227 return maxServicePointIdleTime;
230 if (value < -2 || value > Int32.MaxValue)
231 throw new ArgumentOutOfRangeException ("value");
232 maxServicePointIdleTime = value;
236 public static int MaxServicePoints {
238 return maxServicePoints;
242 throw new ArgumentException ("value");
244 maxServicePoints = value;
245 RecycleServicePoints ();
250 // we need it for SslClientStream
255 static SecurityProtocolType SecurityProtocol {
256 get { return _securityProtocol; }
257 set { _securityProtocol = value; }
260 public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
263 return server_cert_cb;
266 server_cert_cb = value;
271 public static bool Expect100Continue {
272 get { return expectContinue; }
273 set { expectContinue = value; }
276 public static bool UseNagleAlgorithm {
277 get { return useNagle; }
278 set { useNagle = value; }
283 public static ServicePoint FindServicePoint (Uri address)
285 return FindServicePoint (address, GlobalProxySelection.Select);
288 public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
290 return FindServicePoint (new Uri(uriString), proxy);
293 public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
296 throw new ArgumentNullException ("address");
298 RecycleServicePoints ();
300 bool usesProxy = false;
301 bool useConnect = false;
302 if (proxy != null && !proxy.IsBypassed(address)) {
304 bool isSecure = address.Scheme == "https";
305 address = proxy.GetProxy (address);
306 if (address.Scheme != "http" && !isSecure)
307 throw new NotSupportedException ("Proxy scheme not supported.");
309 if (isSecure && address.Scheme == "http")
313 address = new Uri (address.Scheme + "://" + address.Authority);
315 ServicePoint sp = null;
316 lock (servicePoints) {
317 SPKey key = new SPKey (address, useConnect);
318 sp = servicePoints [key] as ServicePoint;
322 if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
323 throw new InvalidOperationException ("maximum number of service points reached");
325 string addr = address.ToString ();
327 int limit = defaultConnectionLimit;
329 int limit = (int) manager.GetMaxConnections (addr);
331 sp = new ServicePoint (address, limit, maxServicePointIdleTime);
333 sp.Expect100Continue = expectContinue;
334 sp.UseNagleAlgorithm = useNagle;
336 sp.UsesProxy = usesProxy;
337 sp.UseConnect = useConnect;
338 servicePoints.Add (key, sp);
346 internal static void RecycleServicePoints ()
348 ArrayList toRemove = new ArrayList ();
349 lock (servicePoints) {
350 IDictionaryEnumerator e = servicePoints.GetEnumerator ();
351 while (e.MoveNext ()) {
352 ServicePoint sp = (ServicePoint) e.Value;
353 if (sp.AvailableForRecycling) {
354 toRemove.Add (e.Key);
358 for (int i = 0; i < toRemove.Count; i++)
359 servicePoints.Remove (toRemove [i]);
361 if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
364 // get rid of the ones with the longest idle time
365 SortedList list = new SortedList (servicePoints.Count);
366 e = servicePoints.GetEnumerator ();
367 while (e.MoveNext ()) {
368 ServicePoint sp = (ServicePoint) e.Value;
369 if (sp.CurrentConnections == 0) {
370 while (list.ContainsKey (sp.IdleSince))
371 sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
372 list.Add (sp.IdleSince, sp.Address);
376 for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
377 servicePoints.Remove (list.GetByIndex (i));
380 #if NET_2_0 && SECURITY_DEP
381 internal class ChainValidationHelper {
384 static bool is_macosx = System.IO.File.Exists (MSX.OSX509Certificates.SecurityLibrary);
386 public ChainValidationHelper (object sender)
388 this.sender = sender;
393 if (host == null && sender is HttpWebRequest)
394 host = ((HttpWebRequest) sender).Address.Host;
398 set { host = value; }
401 // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
402 // and the new ServerCertificateValidationCallback is not null
403 internal ValidationResult ValidateChain (Mono.Security.X509.X509CertificateCollection certs)
405 // user_denied is true if the user callback is called and returns false
406 bool user_denied = false;
407 if (certs == null || certs.Count == 0)
410 ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
411 RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
413 X509Chain chain = new X509Chain ();
414 chain.ChainPolicy = new X509ChainPolicy ();
415 for (int i = 1; i < certs.Count; i++) {
416 X509Certificate2 c2 = new X509Certificate2 (certs [i].RawData);
417 chain.ChainPolicy.ExtraStore.Add (c2);
420 X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
421 int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
422 SslPolicyErrors errors = 0;
424 if (!chain.Build (leaf))
425 errors |= GetErrorsFromChain (chain);
426 } catch (Exception e) {
427 Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
428 Console.Error.WriteLine ("Please, report this problem to the Mono team");
429 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
432 if (!CheckCertificateUsage (leaf)) {
433 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
434 status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
437 if (!CheckServerIdentity (certs [0], Host)) {
438 errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
439 status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
443 // No certificate root found means no mozroots or monotouch
447 // Attempt to use OSX certificates
448 // Ideally we should return the SecTrustResult
449 MSX.OSX509Certificates.SecTrustResult trustResult;
451 trustResult = MSX.OSX509Certificates.TrustEvaluateSsl (certs);
452 // We could use the other values of trustResult to pass this extra information
453 // to the .NET 2 callback for values like SecTrustResult.Confirm
454 result = (trustResult == MSX.OSX509Certificates.SecTrustResult.Proceed ||
455 trustResult == MSX.OSX509Certificates.SecTrustResult.Unspecified);
460 // Clear error status if the OS told us to trust the certificate
469 if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
470 ServicePoint sp = null;
471 HttpWebRequest req = sender as HttpWebRequest;
473 sp = req.ServicePoint;
474 if (status11 == 0 && errors != 0)
475 status11 = GetStatusFromChain (chain);
478 result = policy.CheckValidationResult (sp, leaf, req, status11);
479 user_denied = !result && !(policy is DefaultCertificatePolicy);
481 // If there's a 2.0 callback, it takes precedence
483 result = cb (sender, leaf, chain, errors);
484 user_denied = !result;
486 return new ValidationResult (result, user_denied, status11);
489 static int GetStatusFromChain (X509Chain chain)
492 foreach (var status in chain.ChainStatus) {
493 X509ChainStatusFlags flags = status.Status;
494 if (flags == X509ChainStatusFlags.NoError)
498 if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) result = 0x800B0101;
499 // CERT_E_VALIDITYPERIODNESTING
500 else if ((flags & X509ChainStatusFlags.NotTimeNested) != 0) result = 0x800B0102;
502 else if ((flags & X509ChainStatusFlags.Revoked) != 0) result = 0x800B010C;
503 // TRUST_E_CERT_SIGNATURE
504 else if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) result = 0x80096004;
505 // CERT_E_WRONG_USAGE
506 else if ((flags & X509ChainStatusFlags.NotValidForUsage) != 0) result = 0x800B0110;
507 // CERT_E_UNTRUSTEDROOT
508 else if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0) result = 0x800B0109;
509 // CRYPT_E_NO_REVOCATION_CHECK
510 else if ((flags & X509ChainStatusFlags.RevocationStatusUnknown) != 0) result = 0x80092012;
512 else if ((flags & X509ChainStatusFlags.Cyclic) != 0) result = 0x800B010A;
513 // TRUST_E_FAIL - generic
514 else if ((flags & X509ChainStatusFlags.InvalidExtension) != 0) result = 0x800B010B;
515 // CERT_E_UNTRUSTEDROOT
516 else if ((flags & X509ChainStatusFlags.InvalidPolicyConstraints) != 0) result = 0x800B010D;
517 // TRUST_E_BASIC_CONSTRAINTS
518 else if ((flags & X509ChainStatusFlags.InvalidBasicConstraints) != 0) result = 0x80096019;
519 // CERT_E_INVALID_NAME
520 else if ((flags & X509ChainStatusFlags.InvalidNameConstraints) != 0) result = 0x800B0114;
521 // CERT_E_INVALID_NAME
522 else if ((flags & X509ChainStatusFlags.HasNotSupportedNameConstraint) != 0) result = 0x800B0114;
523 // CERT_E_INVALID_NAME
524 else if ((flags & X509ChainStatusFlags.HasNotDefinedNameConstraint) != 0) result = 0x800B0114;
525 // CERT_E_INVALID_NAME
526 else if ((flags & X509ChainStatusFlags.HasNotPermittedNameConstraint) != 0) result = 0x800B0114;
527 // CERT_E_INVALID_NAME
528 else if ((flags & X509ChainStatusFlags.HasExcludedNameConstraint) != 0) result = 0x800B0114;
530 else if ((flags & X509ChainStatusFlags.PartialChain) != 0) result = 0x800B010A;
532 else if ((flags & X509ChainStatusFlags.CtlNotTimeValid) != 0) result = 0x800B0101;
533 // TRUST_E_CERT_SIGNATURE
534 else if ((flags & X509ChainStatusFlags.CtlNotSignatureValid) != 0) result = 0x80096004;
535 // CERT_E_WRONG_USAGE
536 else if ((flags & X509ChainStatusFlags.CtlNotValidForUsage) != 0) result = 0x800B0110;
537 // CRYPT_E_NO_REVOCATION_CHECK
538 else if ((flags & X509ChainStatusFlags.OfflineRevocation) != 0) result = 0x80092012;
539 // CERT_E_ISSUERCHAINING
540 else if ((flags & X509ChainStatusFlags.NoIssuanceChainPolicy) != 0) result = 0x800B0107;
541 else result = 0x800B010B; // TRUST_E_FAIL - generic
543 break; // Exit the loop on the first error
548 static SslPolicyErrors GetErrorsFromChain (X509Chain chain)
550 SslPolicyErrors errors = SslPolicyErrors.None;
551 foreach (var status in chain.ChainStatus) {
552 if (status.Status == X509ChainStatusFlags.NoError)
554 errors |= SslPolicyErrors.RemoteCertificateChainErrors;
560 static X509KeyUsageFlags s_flags = X509KeyUsageFlags.DigitalSignature |
561 X509KeyUsageFlags.KeyAgreement |
562 X509KeyUsageFlags.KeyEncipherment;
563 // Adapted to System 2.0+ from TlsServerCertificate.cs
564 //------------------------------
565 // Note: this method only works for RSA certificates
566 // DH certificates requires some changes - does anyone use one ?
567 static bool CheckCertificateUsage (X509Certificate2 cert)
570 // certificate extensions are required for this
571 // we "must" accept older certificates without proofs
572 if (cert.Version < 3)
575 X509KeyUsageExtension kux = (X509KeyUsageExtension) cert.Extensions ["2.5.29.15"];
576 X509EnhancedKeyUsageExtension eku = (X509EnhancedKeyUsageExtension) cert.Extensions ["2.5.29.37"];
577 if (kux != null && eku != null) {
578 // RFC3280 states that when both KeyUsageExtension and
579 // ExtendedKeyUsageExtension are present then BOTH should
581 if ((kux.KeyUsages & s_flags) == 0)
583 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
584 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
585 } else if (kux != null) {
586 return ((kux.KeyUsages & s_flags) != 0);
587 } else if (eku != null) {
588 // Server Authentication (1.3.6.1.5.5.7.3.1) or
589 // Netscape Server Gated Crypto (2.16.840.1.113730.4)
590 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
591 eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
594 // last chance - try with older (deprecated) Netscape extensions
595 X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
597 string text = ext.NetscapeCertType (false);
598 return text.IndexOf ("SSL Server Authentication") != -1;
601 } catch (Exception e) {
602 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
603 Console.Error.WriteLine ("Please, report this problem to the Mono team");
608 // RFC2818 - HTTP Over TLS, Section 3.1
609 // http://www.ietf.org/rfc/rfc2818.txt
611 // 1. if present MUST use subjectAltName dNSName as identity
612 // 1.1. if multiples entries a match of any one is acceptable
613 // 1.2. wildcard * is acceptable
614 // 2. URI may be an IP address -> subjectAltName.iPAddress
615 // 2.1. exact match is required
616 // 3. Use of the most specific Common Name (CN=) in the Subject
617 // 3.1 Existing practice but DEPRECATED
618 static bool CheckServerIdentity (Mono.Security.X509.X509Certificate cert, string targetHost)
621 Mono.Security.X509.X509Extension ext = cert.Extensions ["2.5.29.17"];
624 SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
625 // 1.1 - multiple dNSName
626 foreach (string dns in subjectAltName.DNSNames) {
627 // 1.2 TODO - wildcard support
628 if (Match (targetHost, dns))
632 foreach (string ip in subjectAltName.IPAddresses) {
633 // 2.1. Exact match required
634 if (ip == targetHost)
638 // 3. Common Name (CN=)
639 return CheckDomainName (cert.SubjectName, targetHost);
640 } catch (Exception e) {
641 Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
642 Console.Error.WriteLine ("Please, report this problem to the Mono team");
647 static bool CheckDomainName (string subjectName, string targetHost)
649 string domainName = String.Empty;
650 Regex search = new Regex(@"CN\s*=\s*([^,]*)");
651 MatchCollection elements = search.Matches(subjectName);
652 if (elements.Count == 1) {
653 if (elements[0].Success)
654 domainName = elements[0].Groups[1].Value.ToString();
657 return Match (targetHost, domainName);
660 // ensure the pattern is valid wrt to RFC2595 and RFC2818
661 // http://www.ietf.org/rfc/rfc2595.txt
662 // http://www.ietf.org/rfc/rfc2818.txt
663 static bool Match (string hostname, string pattern)
665 // check if this is a pattern
666 int index = pattern.IndexOf ('*');
668 // not a pattern, do a direct case-insensitive comparison
669 return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
672 // check pattern validity
673 // A "*" wildcard character MAY be used as the left-most name component in the certificate.
675 // unless this is the last char (valid)
676 if (index != pattern.Length - 1) {
677 // then the next char must be a dot .'.
678 if (pattern [index + 1] != '.')
682 // only one (A) wildcard is supported
683 int i2 = pattern.IndexOf ('*', index + 1);
687 // match the end of the pattern
688 string end = pattern.Substring (index + 1);
689 int length = hostname.Length - end.Length;
690 // no point to check a pattern that is longer than the hostname
694 if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
697 // special case, we start with the wildcard
699 // ensure we hostname non-matched part (start) doesn't contain a dot
700 int i3 = hostname.IndexOf ('.');
701 return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
704 // match the start of the pattern
705 string start = pattern.Substring (0, index);
706 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);