SslSettings.cs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  1. /* Copyright 2010-present MongoDB Inc.
  2. *
  3. * Licensed under the Apache License, Version 2.0 (the "License");
  4. * you may not use this file except in compliance with the License.
  5. * You may obtain a copy of the License at
  6. *
  7. * http://www.apache.org/licenses/LICENSE-2.0
  8. *
  9. * Unless required by applicable law or agreed to in writing, software
  10. * distributed under the License is distributed on an "AS IS" BASIS,
  11. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. * See the License for the specific language governing permissions and
  13. * limitations under the License.
  14. */
  15. using System;
  16. using System.Collections;
  17. using System.Collections.Generic;
  18. using System.Linq;
  19. using System.Net.Security;
  20. using System.Reflection;
  21. using System.Security.Authentication;
  22. using System.Security.Cryptography.X509Certificates;
  23. using MongoDB.Shared;
  24. namespace MongoDB.Driver
  25. {
  26. /// <summary>
  27. /// Represents the settings for using SSL.
  28. /// </summary>
  29. public class SslSettings : IEquatable<SslSettings>
  30. {
  31. // private static fields
  32. private static readonly IEqualityComparer<X509CertificateCollection> __certificateCollectionEqualityComparer = new X509CertificateCollectionEqualityComparer();
  33. // private fields
  34. private bool _checkCertificateRevocation = false;
  35. private X509CertificateCollection _clientCertificateCollection;
  36. private LocalCertificateSelectionCallback _clientCertificateSelectionCallback;
  37. private SslProtocols _enabledSslProtocols = SslProtocols.Tls12 | SslProtocols.Tls11 | SslProtocols.Tls;
  38. private RemoteCertificateValidationCallback _serverCertificateValidationCallback;
  39. // the following fields are set when the SslSettings are frozen
  40. private bool _isFrozen;
  41. private int _hashCode;
  42. // public properties
  43. /// <summary>
  44. /// Gets or sets a value indicating whether to check for certificate revocation.
  45. /// </summary>
  46. public bool CheckCertificateRevocation
  47. {
  48. get { return _checkCertificateRevocation; }
  49. set
  50. {
  51. if (_isFrozen) { throw new InvalidOperationException("SslSettings is frozen."); }
  52. _checkCertificateRevocation = value;
  53. }
  54. }
  55. /// <summary>
  56. /// Gets or sets the client certificates.
  57. /// </summary>
  58. public IEnumerable<X509Certificate> ClientCertificates
  59. {
  60. get { return (_clientCertificateCollection == null) ? null : ((IEnumerable)_clientCertificateCollection).Cast<X509Certificate>(); }
  61. set
  62. {
  63. if (_isFrozen) { throw new InvalidOperationException("SslSettings is frozen."); }
  64. _clientCertificateCollection = (value == null) ? null : new X509CertificateCollection(value.ToArray());
  65. }
  66. }
  67. /// <summary>
  68. /// Gets or sets the client certificate selection callback.
  69. /// </summary>
  70. public LocalCertificateSelectionCallback ClientCertificateSelectionCallback
  71. {
  72. get { return _clientCertificateSelectionCallback; }
  73. set
  74. {
  75. if (_isFrozen) { throw new InvalidOperationException("SslSettings is frozen."); }
  76. _clientCertificateSelectionCallback = value;
  77. }
  78. }
  79. /// <summary>
  80. /// Gets or sets the enabled SSL protocols.
  81. /// </summary>
  82. public SslProtocols EnabledSslProtocols
  83. {
  84. get { return _enabledSslProtocols; }
  85. set
  86. {
  87. if (_isFrozen) { throw new InvalidOperationException("SslSettings is frozen."); }
  88. _enabledSslProtocols = value;
  89. }
  90. }
  91. /// <summary>
  92. /// Gets or sets the server certificate validation callback.
  93. /// </summary>
  94. public RemoteCertificateValidationCallback ServerCertificateValidationCallback
  95. {
  96. get { return _serverCertificateValidationCallback; }
  97. set
  98. {
  99. if (_isFrozen) { throw new InvalidOperationException("SslSettings is frozen."); }
  100. _serverCertificateValidationCallback = value;
  101. }
  102. }
  103. // internal properties
  104. internal X509CertificateCollection ClientCertificateCollection
  105. {
  106. get { return _clientCertificateCollection; }
  107. }
  108. // public operators
  109. /// <summary>
  110. /// Determines whether two <see cref="SslSettings"/> instances are equal.
  111. /// </summary>
  112. /// <param name="lhs">The LHS.</param>
  113. /// <param name="rhs">The RHS.</param>
  114. /// <returns>
  115. /// <c>true</c> if the left hand side is equal to the right hand side; otherwise, <c>false</c>.
  116. /// </returns>
  117. public static bool operator ==(SslSettings lhs, SslSettings rhs)
  118. {
  119. return object.Equals(lhs, rhs); // handles lhs == null correctly
  120. }
  121. /// <summary>
  122. /// Determines whether two <see cref="SslSettings"/> instances are not equal.
  123. /// </summary>
  124. /// <param name="lhs">The LHS.</param>
  125. /// <param name="rhs">The RHS.</param>
  126. /// <returns>
  127. /// <c>true</c> if the left hand side is not equal to the right hand side; otherwise, <c>false</c>.
  128. /// </returns>
  129. public static bool operator !=(SslSettings lhs, SslSettings rhs)
  130. {
  131. return !(lhs == rhs);
  132. }
  133. // public methods
  134. /// <summary>
  135. /// Clones an SslSettings.
  136. /// </summary>
  137. /// <returns>The cloned SslSettings.</returns>
  138. public SslSettings Clone()
  139. {
  140. var clone = new SslSettings();
  141. clone._checkCertificateRevocation = _checkCertificateRevocation;
  142. clone._clientCertificateCollection = _clientCertificateCollection; // is immutable
  143. clone._clientCertificateSelectionCallback = _clientCertificateSelectionCallback;
  144. clone._enabledSslProtocols = _enabledSslProtocols;
  145. clone._serverCertificateValidationCallback = _serverCertificateValidationCallback;
  146. return clone;
  147. }
  148. /// <summary>
  149. /// Determines whether the specified <see cref="SslSettings" /> is equal to this instance.
  150. /// </summary>
  151. /// <param name="obj">The <see cref="SslSettings" /> to compare with this instance.</param>
  152. /// <returns>
  153. /// <c>true</c> if the specified <see cref="SslSettings" /> is equal to this instance; otherwise, <c>false</c>.
  154. /// </returns>
  155. public bool Equals(SslSettings obj)
  156. {
  157. return Equals((object)obj); // handles obj == null correctly
  158. }
  159. /// <summary>
  160. /// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
  161. /// </summary>
  162. /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param>
  163. /// <returns>
  164. /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
  165. /// </returns>
  166. public override bool Equals(object obj)
  167. {
  168. if (object.ReferenceEquals(obj, null) || GetType() != obj.GetType()) { return false; }
  169. var rhs = (SslSettings)obj;
  170. return
  171. _checkCertificateRevocation == rhs._checkCertificateRevocation &&
  172. __certificateCollectionEqualityComparer.Equals(_clientCertificateCollection, rhs._clientCertificateCollection) &&
  173. object.Equals(_clientCertificateSelectionCallback, rhs._clientCertificateSelectionCallback) &&
  174. _enabledSslProtocols == rhs._enabledSslProtocols &&
  175. object.Equals(_serverCertificateValidationCallback, rhs._serverCertificateValidationCallback);
  176. }
  177. /// <summary>
  178. /// Freezes the settings.
  179. /// </summary>
  180. /// <returns>The frozen settings.</returns>
  181. public SslSettings Freeze()
  182. {
  183. if (!_isFrozen)
  184. {
  185. _hashCode = GetHashCode();
  186. _isFrozen = true;
  187. }
  188. return this;
  189. }
  190. /// <summary>
  191. /// Returns a hash code for this instance.
  192. /// </summary>
  193. /// <returns>
  194. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
  195. /// </returns>
  196. public override int GetHashCode()
  197. {
  198. if (_isFrozen)
  199. {
  200. return _hashCode;
  201. }
  202. return new Hasher()
  203. .Hash(_checkCertificateRevocation)
  204. .HashElements(_clientCertificateCollection)
  205. .Hash(_clientCertificateSelectionCallback)
  206. .Hash(_enabledSslProtocols)
  207. .Hash(_serverCertificateValidationCallback)
  208. .GetHashCode();
  209. }
  210. /// <summary>
  211. /// Returns a string representation of the settings.
  212. /// </summary>
  213. /// <returns>A string representation of the settings.</returns>
  214. public override string ToString()
  215. {
  216. var parts = new List<string>();
  217. parts.Add(string.Format("CheckCertificateRevocation={0}", _checkCertificateRevocation));
  218. if (_clientCertificateCollection != null)
  219. {
  220. parts.Add(string.Format("ClientCertificates=[{0}]", string.Join(",", ((IEnumerable)_clientCertificateCollection).Cast<X509Certificate>().Select(c => c.Subject).ToArray())));
  221. }
  222. if (_clientCertificateSelectionCallback != null)
  223. {
  224. parts.Add(string.Format("ClientCertificateSelectionCallback={0}", _clientCertificateSelectionCallback.GetMethodInfo().Name));
  225. }
  226. parts.Add(string.Format("EnabledProtocols={0}", _enabledSslProtocols));
  227. if (_serverCertificateValidationCallback != null)
  228. {
  229. parts.Add(string.Format("ServerCertificateValidationCallback={0}", _serverCertificateValidationCallback.GetMethodInfo().Name));
  230. }
  231. return string.Format("{{{0}}}", string.Join(",", parts.ToArray()));
  232. }
  233. // nested classes
  234. private class X509CertificateCollectionEqualityComparer : IEqualityComparer<X509CertificateCollection>
  235. {
  236. public bool Equals(X509CertificateCollection lhs, X509CertificateCollection rhs)
  237. {
  238. if (lhs == null) { return rhs == null; }
  239. return ((IEnumerable)lhs).Cast<X509Certificate>().SequenceEqual(((IEnumerable)rhs).Cast<X509Certificate>());
  240. }
  241. public int GetHashCode(X509CertificateCollection obj)
  242. {
  243. if (obj == null)
  244. {
  245. throw new ArgumentNullException("obj");
  246. }
  247. var hash = 17;
  248. foreach (X509Certificate certificate in obj)
  249. {
  250. hash += 37 * hash + certificate.GetHashCode();
  251. }
  252. return hash;
  253. }
  254. }
  255. }
  256. }