ServicePointManager.cs 22 KB

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