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