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