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