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