ServicePointManager.cs 25 KB

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