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