ServicePointManager.cs 25 KB

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