ServicePointManager.cs 26 KB

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