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