Avoid deadlocking when getting the ServicePoint
[mono.git] / mcs / class / System / System.Net / ServicePointManager.cs
1 //
2 // System.Net.ServicePointManager
3 //
4 // Authors:
5 //   Lawrence Pit (loz@cable.a2000.nl)
6 //   Gonzalo Paniagua Javier (gonzalo@novell.com)
7 //
8 // Copyright (c) 2003-2010 Novell, Inc (http://www.novell.com)
9 //
10
11 //
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:
19 // 
20 // The above copyright notice and this permission notice shall be
21 // included in all copies or substantial portions of the Software.
22 // 
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.
30 //
31
32 using System;
33 using System.Collections;
34 using System.Collections.Specialized;
35 using System.Configuration;
36 using System.Net.Configuration;
37 using System.Security.Cryptography.X509Certificates;
38
39 using System.Globalization;
40 using System.Net.Security;
41 #if SECURITY_DEP
42 using System.Text.RegularExpressions;
43 using Mono.Security;
44 using Mono.Security.Cryptography;
45 using Mono.Security.X509.Extensions;
46 using Mono.Security.Protocol.Tls;
47 using MSX = Mono.Security.X509;
48 #endif
49
50 //
51 // notes:
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.
57 // 
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
63 // 5. execute request
64 // 6. when finished, return connection
65 //
66
67
68 namespace System.Net 
69 {
70 #if MOONLIGHT
71         internal class ServicePointManager {
72 #else
73         public class ServicePointManager {
74 #endif
75                 class SPKey {
76                         Uri uri; // schema/host/port
77                         bool use_connect;
78
79                         public SPKey (Uri uri, bool use_connect) {
80                                 this.uri = uri;
81                                 this.use_connect = use_connect;
82                         }
83
84                         public Uri Uri {
85                                 get { return uri; }
86                         }
87
88                         public bool UseConnect {
89                                 get { return use_connect; }
90                         }
91
92                         public override int GetHashCode () {
93                                 return uri.GetHashCode () + ((use_connect) ? 1 : 0);
94                         }
95
96                         public override bool Equals (object obj) {
97                                 SPKey other = obj as SPKey;
98                                 if (obj == null) {
99                                         return false;
100                                 }
101
102                                 return (uri.Equals (other.uri) && other.use_connect == use_connect);
103                         }
104                 }
105
106                 private static HybridDictionary servicePoints = new HybridDictionary ();
107                 
108                 // Static properties
109                 
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;
116
117 #if NET_1_1
118 #if TARGET_JVM
119                 static bool expectContinue = false;
120 #else
121                 static bool expectContinue = true;
122 #endif
123                 static bool useNagle;
124 #endif
125                 static RemoteCertificateValidationCallback server_cert_cb;
126                 static bool tcp_keepalive;
127                 static int tcp_keepalive_time;
128                 static int tcp_keepalive_interval;
129
130                 // Fields
131                 
132                 public const int DefaultNonPersistentConnectionLimit = 4;
133                 public const int DefaultPersistentConnectionLimit = 2;
134
135 #if !NET_2_1
136                 const string configKey = "system.net/connectionManagement";
137                 static ConnectionManagementData manager;
138 #endif
139                 
140                 static ServicePointManager ()
141                 {
142 #if !NET_2_1
143 #if NET_2_0 && CONFIGURATION_DEP
144                         object cfg = ConfigurationManager.GetSection (configKey);
145                         ConnectionManagementSection s = cfg as ConnectionManagementSection;
146                         if (s != null) {
147                                 manager = new ConnectionManagementData (null);
148                                 foreach (ConnectionManagementElement e in s.ConnectionManagement)
149                                         manager.Add (e.Address, e.MaxConnection);
150
151                                 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");                         
152                                 return;
153                         }
154 #endif
155                         manager = (ConnectionManagementData) ConfigurationSettings.GetConfig (configKey);
156                         if (manager != null) {
157                                 defaultConnectionLimit = (int) manager.GetMaxConnections ("*");                         
158                         }
159 #endif
160                 }
161
162                 // Constructors
163                 private ServicePointManager ()
164                 {
165                 }               
166                 
167                 // Properties
168                 
169 #if NET_2_0
170                 [Obsolete ("Use ServerCertificateValidationCallback instead", false)]
171 #endif
172                 public static ICertificatePolicy CertificatePolicy {
173                         get { return policy; }
174                         set { policy = value; }
175                 }
176
177 #if NET_1_0
178                 // we need it for SslClientStream
179                 internal
180 #else
181                 [MonoTODO("CRL checks not implemented")]
182                 public
183 #endif
184                 static bool CheckCertificateRevocationList {
185                         get { return _checkCRL; }
186                         set { _checkCRL = false; }      // TODO - don't yet accept true
187                 }
188                 
189                 public static int DefaultConnectionLimit {
190                         get { return defaultConnectionLimit; }
191                         set { 
192                                 if (value <= 0)
193                                         throw new ArgumentOutOfRangeException ("value");
194
195                                 defaultConnectionLimit = value; 
196                         }
197                 }
198
199 #if NET_2_0
200                 static Exception GetMustImplement ()
201                 {
202                         return new NotImplementedException ();
203                 }
204                 
205                 [MonoTODO]
206                 public static int DnsRefreshTimeout
207                 {
208                         get {
209                                 throw GetMustImplement ();
210                         }
211                         set {
212                                 throw GetMustImplement ();
213                         }
214                 }
215                 
216                 [MonoTODO]
217                 public static bool EnableDnsRoundRobin
218                 {
219                         get {
220                                 throw GetMustImplement ();
221                         }
222                         set {
223                                 throw GetMustImplement ();
224                         }
225                 }
226 #endif
227                 
228                 public static int MaxServicePointIdleTime {
229                         get { 
230                                 return maxServicePointIdleTime;
231                         }
232                         set { 
233                                 if (value < -2 || value > Int32.MaxValue)
234                                         throw new ArgumentOutOfRangeException ("value");
235                                 maxServicePointIdleTime = value;
236                         }
237                 }
238                 
239                 public static int MaxServicePoints {
240                         get { 
241                                 return maxServicePoints; 
242                         }
243                         set {  
244                                 if (value < 0)
245                                         throw new ArgumentException ("value");                          
246
247                                 maxServicePoints = value;
248                                 RecycleServicePoints ();
249                         }
250                 }
251
252 #if NET_1_0
253                 // we need it for SslClientStream
254                 internal
255 #else
256                 public
257 #endif
258                 static SecurityProtocolType SecurityProtocol {
259                         get { return _securityProtocol; }
260                         set { _securityProtocol = value; }
261                 }
262
263                 public static RemoteCertificateValidationCallback ServerCertificateValidationCallback
264                 {
265                         get {
266                                 return server_cert_cb;
267                         }
268                         set {
269                                 server_cert_cb = value;
270                         }
271                 }
272
273 #if NET_1_1
274                 public static bool Expect100Continue {
275                         get { return expectContinue; }
276                         set { expectContinue = value; }
277                 }
278
279                 public static bool UseNagleAlgorithm {
280                         get { return useNagle; }
281                         set { useNagle = value; }
282                 }
283 #endif
284                 // Methods
285                 public static void SetTcpKeepAlive (bool enabled, int keepAliveTime, int keepAliveInterval)
286                 {
287                         if (enabled) {
288                                 if (keepAliveTime <= 0)
289                                         throw new ArgumentOutOfRangeException ("keepAliveTime", "Must be greater than 0");
290                                 if (keepAliveInterval <= 0)
291                                         throw new ArgumentOutOfRangeException ("keepAliveInterval", "Must be greater than 0");
292                         }
293
294                         tcp_keepalive = enabled;
295                         tcp_keepalive_time = keepAliveTime;
296                         tcp_keepalive_interval = keepAliveInterval;
297                 }
298
299                 public static ServicePoint FindServicePoint (Uri address) 
300                 {
301                         return FindServicePoint (address, GlobalProxySelection.Select);
302                 }
303                 
304                 public static ServicePoint FindServicePoint (string uriString, IWebProxy proxy)
305                 {
306                         return FindServicePoint (new Uri(uriString), proxy);
307                 }
308
309                 public static ServicePoint FindServicePoint (Uri address, IWebProxy proxy)
310                 {
311                         if (address == null)
312                                 throw new ArgumentNullException ("address");
313
314                         RecycleServicePoints ();
315                         
316                         bool usesProxy = false;
317                         bool useConnect = false;
318                         if (proxy != null && !proxy.IsBypassed(address)) {
319                                 usesProxy = true;
320                                 bool isSecure = address.Scheme == "https";
321                                 address = proxy.GetProxy (address);
322                                 if (address.Scheme != "http" && !isSecure)
323                                         throw new NotSupportedException ("Proxy scheme not supported.");
324
325                                 if (isSecure && address.Scheme == "http")
326                                         useConnect = true;
327                         } 
328
329                         address = new Uri (address.Scheme + "://" + address.Authority);
330                         
331                         ServicePoint sp = null;
332                         lock (servicePoints) {
333                                 SPKey key = new SPKey (address, useConnect);
334                                 sp = servicePoints [key] as ServicePoint;
335                                 if (sp != null)
336                                         return sp;
337
338                                 if (maxServicePoints > 0 && servicePoints.Count >= maxServicePoints)
339                                         throw new InvalidOperationException ("maximum number of service points reached");
340
341                                 string addr = address.ToString ();
342 #if NET_2_1
343                                 int limit = defaultConnectionLimit;
344 #else
345                                 int limit = (int) manager.GetMaxConnections (addr);
346 #endif
347                                 sp = new ServicePoint (address, limit, maxServicePointIdleTime);
348                                 sp.Expect100Continue = expectContinue;
349                                 sp.UseNagleAlgorithm = useNagle;
350                                 sp.UsesProxy = usesProxy;
351                                 sp.UseConnect = useConnect;
352                                 sp.SetTcpKeepAlive (tcp_keepalive, tcp_keepalive_time, tcp_keepalive_interval);
353                                 servicePoints.Add (key, sp);
354                         }
355                         
356                         return sp;
357                 }
358                 
359                 // Internal Methods
360
361                 internal static void RecycleServicePoints ()
362                 {
363                         ArrayList toRemove = new ArrayList ();
364                         lock (servicePoints) {
365                                 IDictionaryEnumerator e = servicePoints.GetEnumerator ();
366                                 while (e.MoveNext ()) {
367                                         ServicePoint sp = (ServicePoint) e.Value;
368                                         if (sp.AvailableForRecycling) {
369                                                 toRemove.Add (e.Key);
370                                         }
371                                 }
372                                 
373                                 for (int i = 0; i < toRemove.Count; i++) 
374                                         servicePoints.Remove (toRemove [i]);
375
376                                 if (maxServicePoints == 0 || servicePoints.Count <= maxServicePoints)
377                                         return;
378
379                                 // get rid of the ones with the longest idle time
380                                 SortedList list = new SortedList (servicePoints.Count);
381                                 e = servicePoints.GetEnumerator ();
382                                 while (e.MoveNext ()) {
383                                         ServicePoint sp = (ServicePoint) e.Value;
384                                         if (sp.CurrentConnections == 0) {
385                                                 while (list.ContainsKey (sp.IdleSince))
386                                                         sp.IdleSince = sp.IdleSince.AddMilliseconds (1);
387                                                 list.Add (sp.IdleSince, sp.Address);
388                                         }
389                                 }
390                                 
391                                 for (int i = 0; i < list.Count && servicePoints.Count > maxServicePoints; i++)
392                                         servicePoints.Remove (list.GetByIndex (i));
393                         }
394                 }
395 #if MOONLIGHT && SECURITY_DEP
396                 internal class ChainValidationHelper {
397                         object sender;
398
399                         public ChainValidationHelper (object sender)
400                         {
401                                 this.sender = sender;
402                         }
403
404                         // no need to check certificates since we are either
405                         // (a) loading from the site of origin (and we accepted its certificate to load from it)
406                         // (b) loading from a cross-domain site and we downloaded the policy file using the browser stack
407                         //     i.e. the certificate was accepted (or the policy would not be valid)
408                         internal ValidationResult ValidateChain (Mono.Security.X509.X509CertificateCollection certs)
409                         {
410                                 return new ValidationResult (true, false, 0);
411                         }
412                 }
413 #elif NET_2_0 && SECURITY_DEP
414                 internal class ChainValidationHelper {
415                         object sender;
416                         string host;
417                         static bool is_macosx = System.IO.File.Exists (MSX.OSX509Certificates.SecurityLibrary);
418                         static X509RevocationMode revocation_mode;
419
420 #if MONODROID
421                         static readonly Converter<Mono.Security.X509.X509CertificateCollection, bool> monodroidCallback;
422 #endif
423
424                         static ChainValidationHelper ()
425                         {
426 #if MONODROID
427                                 monodroidCallback = (Converter<Mono.Security.X509.X509CertificateCollection, bool>)
428                                         Delegate.CreateDelegate (typeof(Converter<Mono.Security.X509.X509CertificateCollection, bool>), 
429                                                         Type.GetType ("Android.Runtime.AndroidEnvironment, Mono.Android", true)
430                                                         .GetMethod ("TrustEvaluateSsl", 
431                                                                 System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.NonPublic));
432 #endif
433 #if !MONOTOUCH
434                                 revocation_mode = X509RevocationMode.NoCheck;
435                                 try {
436                                         string str = Environment.GetEnvironmentVariable ("MONO_X509_REVOCATION_MODE");
437                                         if (String.IsNullOrEmpty (str))
438                                                 return;
439                                         revocation_mode = (X509RevocationMode) Enum.Parse (typeof (X509RevocationMode), str, true);
440                                 } catch {
441                                 }
442 #endif
443                         }
444
445                         public ChainValidationHelper (object sender)
446                         {
447                                 this.sender = sender;
448                         }
449
450                         public string Host {
451                                 get {
452                                         if (host == null && sender is HttpWebRequest)
453                                                 host = ((HttpWebRequest) sender).Address.Host;
454                                         return host;
455                                 }
456
457                                 set { host = value; }
458                         }
459
460                         // Used when the obsolete ICertificatePolicy is set to DefaultCertificatePolicy
461                         // and the new ServerCertificateValidationCallback is not null
462                         internal ValidationResult ValidateChain (Mono.Security.X509.X509CertificateCollection certs)
463                         {
464                                 // user_denied is true if the user callback is called and returns false
465                                 bool user_denied = false;
466                                 if (certs == null || certs.Count == 0)
467                                         return null;
468
469                                 ICertificatePolicy policy = ServicePointManager.CertificatePolicy;
470                                 RemoteCertificateValidationCallback cb = ServicePointManager.ServerCertificateValidationCallback;
471
472                                 X509Certificate2 leaf = new X509Certificate2 (certs [0].RawData);
473                                 int status11 = 0; // Error code passed to the obsolete ICertificatePolicy callback
474                                 SslPolicyErrors errors = 0;
475                                 X509Chain chain = null;
476 #if !MONOTOUCH
477                                 chain = new X509Chain ();
478                                 chain.ChainPolicy = new X509ChainPolicy ();
479                                 chain.ChainPolicy.RevocationMode = revocation_mode;
480                                 for (int i = 1; i < certs.Count; i++) {
481                                         X509Certificate2 c2 = new X509Certificate2 (certs [i].RawData);
482                                         chain.ChainPolicy.ExtraStore.Add (c2);
483                                 }
484
485                                 try {
486                                         if (!chain.Build (leaf))
487                                                 errors |= GetErrorsFromChain (chain);
488                                 } catch (Exception e) {
489                                         Console.Error.WriteLine ("ERROR building certificate chain: {0}", e);
490                                         Console.Error.WriteLine ("Please, report this problem to the Mono team");
491                                         errors |= SslPolicyErrors.RemoteCertificateChainErrors;
492                                 }
493 #endif
494                                 if (!CheckCertificateUsage (leaf)) {
495                                         errors |= SslPolicyErrors.RemoteCertificateChainErrors;
496                                         status11 = -2146762490; //CERT_E_PURPOSE 0x800B0106
497                                 }
498
499                                 if (!CheckServerIdentity (certs [0], Host)) {
500                                         errors |= SslPolicyErrors.RemoteCertificateNameMismatch;
501                                         status11 = -2146762481; // CERT_E_CN_NO_MATCH 0x800B010F
502                                 }
503
504                                 bool result = false;
505                                 // No certificate root found means no mozroots or monotouch
506 #if !MONOTOUCH
507                                 if (is_macosx) {
508 #endif
509                                         // Attempt to use OSX certificates
510                                         // Ideally we should return the SecTrustResult
511                                         MSX.OSX509Certificates.SecTrustResult trustResult;
512                                         try {
513                                                 trustResult = MSX.OSX509Certificates.TrustEvaluateSsl (certs);
514                                                 // We could use the other values of trustResult to pass this extra information
515                                                 // to the .NET 2 callback for values like SecTrustResult.Confirm
516                                                 result = (trustResult == MSX.OSX509Certificates.SecTrustResult.Proceed ||
517                                                                   trustResult == MSX.OSX509Certificates.SecTrustResult.Unspecified);
518
519                                         } catch {
520                                                 // Ignore
521                                         }
522                                         // Clear error status if the OS told us to trust the certificate
523                                         if (result) {
524                                                 status11 = 0;
525                                                 errors = 0;
526                                         }
527 #if !MONOTOUCH
528                                 }
529 #endif
530
531 #if MONODROID
532                                 result = monodroidCallback (certs);
533                                 if (result) {
534                                         status11 = 0;
535                                         errors = 0;
536                                 }
537 #endif
538
539                                 if (policy != null && (!(policy is DefaultCertificatePolicy) || cb == null)) {
540                                         ServicePoint sp = null;
541                                         HttpWebRequest req = sender as HttpWebRequest;
542                                         if (req != null)
543                                                 sp = req.ServicePointNoLock;
544                                         if (status11 == 0 && errors != 0)
545                                                 status11 = GetStatusFromChain (chain);
546
547                                         // pre 2.0 callback
548                                         result = policy.CheckValidationResult (sp, leaf, req, status11);
549                                         user_denied = !result && !(policy is DefaultCertificatePolicy);
550                                 }
551                                 // If there's a 2.0 callback, it takes precedence
552                                 if (cb != null) {
553                                         result = cb (sender, leaf, chain, errors);
554                                         user_denied = !result;
555                                 }
556                                 return new ValidationResult (result, user_denied, status11);
557                         }
558
559                         static int GetStatusFromChain (X509Chain chain)
560                         {
561                                 long result = 0;
562                                 foreach (var status in chain.ChainStatus) {
563                                         X509ChainStatusFlags flags = status.Status;
564                                         if (flags == X509ChainStatusFlags.NoError)
565                                                 continue;
566
567                                         // CERT_E_EXPIRED
568                                         if ((flags & X509ChainStatusFlags.NotTimeValid) != 0) result = 0x800B0101;
569                                         // CERT_E_VALIDITYPERIODNESTING
570                                         else if ((flags & X509ChainStatusFlags.NotTimeNested) != 0) result = 0x800B0102;
571                                         // CERT_E_REVOKED
572                                         else if ((flags & X509ChainStatusFlags.Revoked) != 0) result = 0x800B010C;
573                                         // TRUST_E_CERT_SIGNATURE
574                                         else if ((flags & X509ChainStatusFlags.NotSignatureValid) != 0) result = 0x80096004;
575                                         // CERT_E_WRONG_USAGE
576                                         else if ((flags & X509ChainStatusFlags.NotValidForUsage) != 0) result = 0x800B0110;
577                                         // CERT_E_UNTRUSTEDROOT
578                                         else if ((flags & X509ChainStatusFlags.UntrustedRoot) != 0) result = 0x800B0109;
579                                         // CRYPT_E_NO_REVOCATION_CHECK
580                                         else if ((flags & X509ChainStatusFlags.RevocationStatusUnknown) != 0) result = 0x80092012;
581                                         // CERT_E_CHAINING
582                                         else if ((flags & X509ChainStatusFlags.Cyclic) != 0) result = 0x800B010A;
583                                         // TRUST_E_FAIL - generic
584                                         else if ((flags & X509ChainStatusFlags.InvalidExtension) != 0) result = 0x800B010B;
585                                         // CERT_E_UNTRUSTEDROOT
586                                         else if ((flags & X509ChainStatusFlags.InvalidPolicyConstraints) != 0) result = 0x800B010D;
587                                         // TRUST_E_BASIC_CONSTRAINTS
588                                         else if ((flags & X509ChainStatusFlags.InvalidBasicConstraints) != 0) result = 0x80096019;
589                                         // CERT_E_INVALID_NAME
590                                         else if ((flags & X509ChainStatusFlags.InvalidNameConstraints) != 0) result = 0x800B0114;
591                                         // CERT_E_INVALID_NAME
592                                         else if ((flags & X509ChainStatusFlags.HasNotSupportedNameConstraint) != 0) result = 0x800B0114;
593                                         // CERT_E_INVALID_NAME
594                                         else if ((flags & X509ChainStatusFlags.HasNotDefinedNameConstraint) != 0) result = 0x800B0114;
595                                         // CERT_E_INVALID_NAME
596                                         else if ((flags & X509ChainStatusFlags.HasNotPermittedNameConstraint) != 0) result = 0x800B0114;
597                                         // CERT_E_INVALID_NAME
598                                         else if ((flags & X509ChainStatusFlags.HasExcludedNameConstraint) != 0) result = 0x800B0114;
599                                         // CERT_E_CHAINING
600                                         else if ((flags & X509ChainStatusFlags.PartialChain) != 0) result = 0x800B010A;
601                                         // CERT_E_EXPIRED
602                                         else if ((flags & X509ChainStatusFlags.CtlNotTimeValid) != 0) result = 0x800B0101;
603                                         // TRUST_E_CERT_SIGNATURE
604                                         else if ((flags & X509ChainStatusFlags.CtlNotSignatureValid) != 0) result = 0x80096004;
605                                         // CERT_E_WRONG_USAGE
606                                         else if ((flags & X509ChainStatusFlags.CtlNotValidForUsage) != 0) result = 0x800B0110;
607                                         // CRYPT_E_NO_REVOCATION_CHECK
608                                         else if ((flags & X509ChainStatusFlags.OfflineRevocation) != 0) result = 0x80092012;
609                                         // CERT_E_ISSUERCHAINING
610                                         else if ((flags & X509ChainStatusFlags.NoIssuanceChainPolicy) != 0) result = 0x800B0107;
611                                         else result = 0x800B010B; // TRUST_E_FAIL - generic
612
613                                         break; // Exit the loop on the first error
614                                 }
615                                 return (int) result;
616                         }
617
618                         static SslPolicyErrors GetErrorsFromChain (X509Chain chain)
619                         {
620                                 SslPolicyErrors errors = SslPolicyErrors.None;
621                                 foreach (var status in chain.ChainStatus) {
622                                         if (status.Status == X509ChainStatusFlags.NoError)
623                                                 continue;
624                                         errors |= SslPolicyErrors.RemoteCertificateChainErrors;
625                                         break;
626                                 }
627                                 return errors;
628                         }
629
630                         static X509KeyUsageFlags s_flags = X509KeyUsageFlags.DigitalSignature  | 
631                                                         X509KeyUsageFlags.KeyAgreement |
632                                                         X509KeyUsageFlags.KeyEncipherment;
633                         // Adapted to System 2.0+ from TlsServerCertificate.cs
634                         //------------------------------
635                         // Note: this method only works for RSA certificates
636                         // DH certificates requires some changes - does anyone use one ?
637                         static bool CheckCertificateUsage (X509Certificate2 cert) 
638                         {
639                                 try {
640                                         // certificate extensions are required for this
641                                         // we "must" accept older certificates without proofs
642                                         if (cert.Version < 3)
643                                                 return true;
644
645                                         X509KeyUsageExtension kux = (cert.Extensions ["2.5.29.15"] as X509KeyUsageExtension);
646                                         X509EnhancedKeyUsageExtension eku = (cert.Extensions ["2.5.29.37"] as X509EnhancedKeyUsageExtension);
647                                         if (kux != null && eku != null) {
648                                                 // RFC3280 states that when both KeyUsageExtension and 
649                                                 // ExtendedKeyUsageExtension are present then BOTH should
650                                                 // be valid
651                                                 if ((kux.KeyUsages & s_flags) == 0)
652                                                         return false;
653                                                 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
654                                                         eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
655                                         } else if (kux != null) {
656                                                 return ((kux.KeyUsages & s_flags) != 0);
657                                         } else if (eku != null) {
658                                                 // Server Authentication (1.3.6.1.5.5.7.3.1) or
659                                                 // Netscape Server Gated Crypto (2.16.840.1.113730.4)
660                                                 return eku.EnhancedKeyUsages ["1.3.6.1.5.5.7.3.1"] != null ||
661                                                         eku.EnhancedKeyUsages ["2.16.840.1.113730.4.1"] != null;
662                                         }
663
664                                         // last chance - try with older (deprecated) Netscape extensions
665                                         X509Extension ext = cert.Extensions ["2.16.840.1.113730.1.1"];
666                                         if (ext != null) {
667                                                 string text = ext.NetscapeCertType (false);
668                                                 return text.IndexOf ("SSL Server Authentication", StringComparison.Ordinal) != -1;
669                                         }
670                                         return true;
671                                 } catch (Exception e) {
672                                         Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
673                                         Console.Error.WriteLine ("Please, report this problem to the Mono team");
674                                         return false;
675                                 }
676                         }
677
678                         // RFC2818 - HTTP Over TLS, Section 3.1
679                         // http://www.ietf.org/rfc/rfc2818.txt
680                         // 
681                         // 1.   if present MUST use subjectAltName dNSName as identity
682                         // 1.1.         if multiples entries a match of any one is acceptable
683                         // 1.2.         wildcard * is acceptable
684                         // 2.   URI may be an IP address -> subjectAltName.iPAddress
685                         // 2.1.         exact match is required
686                         // 3.   Use of the most specific Common Name (CN=) in the Subject
687                         // 3.1          Existing practice but DEPRECATED
688                         static bool CheckServerIdentity (Mono.Security.X509.X509Certificate cert, string targetHost) 
689                         {
690                                 try {
691                                         Mono.Security.X509.X509Extension ext = cert.Extensions ["2.5.29.17"];
692                                         // 1. subjectAltName
693                                         if (ext != null) {
694                                                 SubjectAltNameExtension subjectAltName = new SubjectAltNameExtension (ext);
695                                                 // 1.1 - multiple dNSName
696                                                 foreach (string dns in subjectAltName.DNSNames) {
697                                                         // 1.2 TODO - wildcard support
698                                                         if (Match (targetHost, dns))
699                                                                 return true;
700                                                 }
701                                                 // 2. ipAddress
702                                                 foreach (string ip in subjectAltName.IPAddresses) {
703                                                         // 2.1. Exact match required
704                                                         if (ip == targetHost)
705                                                                 return true;
706                                                 }
707                                         }
708                                         // 3. Common Name (CN=)
709                                         return CheckDomainName (cert.SubjectName, targetHost);
710                                 } catch (Exception e) {
711                                         Console.Error.WriteLine ("ERROR processing certificate: {0}", e);
712                                         Console.Error.WriteLine ("Please, report this problem to the Mono team");
713                                         return false;
714                                 }
715                         }
716
717                         static bool CheckDomainName (string subjectName, string targetHost)
718                         {
719                                 string  domainName = String.Empty;
720                                 Regex search = new Regex(@"CN\s*=\s*([^,]*)");
721                                 MatchCollection elements = search.Matches(subjectName);
722                                 if (elements.Count == 1) {
723                                         if (elements[0].Success)
724                                                 domainName = elements[0].Groups[1].Value.ToString();
725                                 }
726
727                                 return Match (targetHost, domainName);
728                         }
729
730                         // ensure the pattern is valid wrt to RFC2595 and RFC2818
731                         // http://www.ietf.org/rfc/rfc2595.txt
732                         // http://www.ietf.org/rfc/rfc2818.txt
733                         static bool Match (string hostname, string pattern)
734                         {
735                                 // check if this is a pattern
736                                 int index = pattern.IndexOf ('*');
737                                 if (index == -1) {
738                                         // not a pattern, do a direct case-insensitive comparison
739                                         return (String.Compare (hostname, pattern, true, CultureInfo.InvariantCulture) == 0);
740                                 }
741
742                                 // check pattern validity
743                                 // A "*" wildcard character MAY be used as the left-most name component in the certificate.
744
745                                 // unless this is the last char (valid)
746                                 if (index != pattern.Length - 1) {
747                                         // then the next char must be a dot .'.
748                                         if (pattern [index + 1] != '.')
749                                                 return false;
750                                 }
751
752                                 // only one (A) wildcard is supported
753                                 int i2 = pattern.IndexOf ('*', index + 1);
754                                 if (i2 != -1)
755                                         return false;
756
757                                 // match the end of the pattern
758                                 string end = pattern.Substring (index + 1);
759                                 int length = hostname.Length - end.Length;
760                                 // no point to check a pattern that is longer than the hostname
761                                 if (length <= 0)
762                                         return false;
763
764                                 if (String.Compare (hostname, length, end, 0, end.Length, true, CultureInfo.InvariantCulture) != 0)
765                                         return false;
766
767                                 // special case, we start with the wildcard
768                                 if (index == 0) {
769                                         // ensure we hostname non-matched part (start) doesn't contain a dot
770                                         int i3 = hostname.IndexOf ('.');
771                                         return ((i3 == -1) || (i3 >= (hostname.Length - end.Length)));
772                                 }
773
774                                 // match the start of the pattern
775                                 string start = pattern.Substring (0, index);
776                                 return (String.Compare (hostname, 0, start, 0, start.Length, true, CultureInfo.InvariantCulture) == 0);
777                         }
778                 }
779 #endif
780         }
781 }
782