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