ServicePointManager.cs 23 KB

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