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