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