ServicePointManager.cs 22 KB

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