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