MongoCredential.cs 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. /* Copyright 2010-2016 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.Generic;
  17. using System.Linq;
  18. using System.Runtime.InteropServices;
  19. using System.Security;
  20. using MongoDB.Driver.Core.Authentication;
  21. using MongoDB.Shared;
  22. namespace MongoDB.Driver
  23. {
  24. /// <summary>
  25. /// Credential to access a MongoDB database.
  26. /// </summary>
  27. #if NET45
  28. [Serializable]
  29. #endif
  30. public class MongoCredential : IEquatable<MongoCredential>
  31. {
  32. // private fields
  33. private readonly MongoIdentityEvidence _evidence;
  34. private readonly MongoIdentity _identity;
  35. private readonly string _mechanism;
  36. private readonly Dictionary<string, object> _mechanismProperties;
  37. // constructors
  38. /// <summary>
  39. /// Initializes a new instance of the <see cref="MongoCredential" /> class.
  40. /// </summary>
  41. /// <param name="mechanism">Mechanism to authenticate with.</param>
  42. /// <param name="identity">The identity.</param>
  43. /// <param name="evidence">The evidence.</param>
  44. public MongoCredential(string mechanism, MongoIdentity identity, MongoIdentityEvidence evidence)
  45. {
  46. if (identity == null)
  47. {
  48. throw new ArgumentNullException("identity");
  49. }
  50. if (evidence == null)
  51. {
  52. throw new ArgumentNullException("evidence");
  53. }
  54. _mechanism = mechanism;
  55. _identity = identity;
  56. _evidence = evidence;
  57. _mechanismProperties = new Dictionary<string, object>();
  58. }
  59. // public properties
  60. /// <summary>
  61. /// Gets the evidence.
  62. /// </summary>
  63. public MongoIdentityEvidence Evidence
  64. {
  65. get { return _evidence; }
  66. }
  67. /// <summary>
  68. /// Gets the identity.
  69. /// </summary>
  70. public MongoIdentity Identity
  71. {
  72. get { return _identity; }
  73. }
  74. /// <summary>
  75. /// Gets the mechanism to authenticate with.
  76. /// </summary>
  77. public string Mechanism
  78. {
  79. get { return _mechanism; }
  80. }
  81. /// <summary>
  82. /// Gets the password.
  83. /// </summary>
  84. [Obsolete("Use Evidence instead.")]
  85. public string Password
  86. {
  87. get
  88. {
  89. var passwordEvidence = _evidence as PasswordEvidence;
  90. if (passwordEvidence != null)
  91. {
  92. return MongoUtils.ToInsecureString(passwordEvidence.SecurePassword);
  93. }
  94. return null;
  95. }
  96. }
  97. /// <summary>
  98. /// Gets the source.
  99. /// </summary>
  100. public string Source
  101. {
  102. get { return _identity.Source; }
  103. }
  104. /// <summary>
  105. /// Gets the username.
  106. /// </summary>
  107. public string Username
  108. {
  109. get { return _identity.Username; }
  110. }
  111. // public operators
  112. /// <summary>
  113. /// Compares two MongoCredentials.
  114. /// </summary>
  115. /// <param name="lhs">The first MongoCredential.</param>
  116. /// <param name="rhs">The other MongoCredential.</param>
  117. /// <returns>True if the two MongoCredentials are equal (or both null).</returns>
  118. public static bool operator ==(MongoCredential lhs, MongoCredential rhs)
  119. {
  120. return object.Equals(lhs, rhs);
  121. }
  122. /// <summary>
  123. /// Compares two MongoCredentials.
  124. /// </summary>
  125. /// <param name="lhs">The first MongoCredential.</param>
  126. /// <param name="rhs">The other MongoCredential.</param>
  127. /// <returns>True if the two MongoCredentials are not equal (or one is null and the other is not).</returns>
  128. public static bool operator !=(MongoCredential lhs, MongoCredential rhs)
  129. {
  130. return !(lhs == rhs);
  131. }
  132. // public static methods
  133. /// <summary>
  134. /// Creates a default credential.
  135. /// </summary>
  136. /// <param name="databaseName">Name of the database.</param>
  137. /// <param name="username">The username.</param>
  138. /// <param name="password">The password.</param>
  139. /// <returns>A default credential.</returns>
  140. public static MongoCredential CreateCredential(string databaseName, string username, string password)
  141. {
  142. return FromComponents(null,
  143. databaseName,
  144. username,
  145. new PasswordEvidence(password));
  146. }
  147. /// <summary>
  148. /// Creates a default credential.
  149. /// </summary>
  150. /// <param name="databaseName">Name of the database.</param>
  151. /// <param name="username">The username.</param>
  152. /// <param name="password">The password.</param>
  153. /// <returns>A default credential.</returns>
  154. public static MongoCredential CreateCredential(string databaseName, string username, SecureString password)
  155. {
  156. return FromComponents(null,
  157. databaseName,
  158. username,
  159. new PasswordEvidence(password));
  160. }
  161. /// <summary>
  162. /// Creates a GSSAPI credential.
  163. /// </summary>
  164. /// <param name="username">The username.</param>
  165. /// <returns>A credential for GSSAPI.</returns>
  166. /// <remarks>This overload is used primarily on linux.</remarks>
  167. public static MongoCredential CreateGssapiCredential(string username)
  168. {
  169. return FromComponents("GSSAPI",
  170. "$external",
  171. username,
  172. new ExternalEvidence());
  173. }
  174. /// <summary>
  175. /// Creates a GSSAPI credential.
  176. /// </summary>
  177. /// <param name="username">The username.</param>
  178. /// <param name="password">The password.</param>
  179. /// <returns>A credential for GSSAPI.</returns>
  180. public static MongoCredential CreateGssapiCredential(string username, string password)
  181. {
  182. return FromComponents("GSSAPI",
  183. "$external",
  184. username,
  185. new PasswordEvidence(password));
  186. }
  187. /// <summary>
  188. /// Creates a GSSAPI credential.
  189. /// </summary>
  190. /// <param name="username">The username.</param>
  191. /// <param name="password">The password.</param>
  192. /// <returns>A credential for GSSAPI.</returns>
  193. public static MongoCredential CreateGssapiCredential(string username, SecureString password)
  194. {
  195. return FromComponents("GSSAPI",
  196. "$external",
  197. username,
  198. new PasswordEvidence(password));
  199. }
  200. /// <summary>
  201. /// Creates a credential used with MONGODB-CR.
  202. /// </summary>
  203. /// <param name="databaseName">Name of the database.</param>
  204. /// <param name="username">The username.</param>
  205. /// <param name="password">The password.</param>
  206. /// <returns>A credential for MONGODB-CR.</returns>
  207. public static MongoCredential CreateMongoCRCredential(string databaseName, string username, string password)
  208. {
  209. return FromComponents("MONGODB-CR",
  210. databaseName,
  211. username,
  212. new PasswordEvidence(password));
  213. }
  214. /// <summary>
  215. /// Creates a credential used with MONGODB-CR.
  216. /// </summary>
  217. /// <param name="databaseName">Name of the database.</param>
  218. /// <param name="username">The username.</param>
  219. /// <param name="password">The password.</param>
  220. /// <returns>A credential for MONGODB-CR.</returns>
  221. public static MongoCredential CreateMongoCRCredential(string databaseName, string username, SecureString password)
  222. {
  223. return FromComponents("MONGODB-CR",
  224. databaseName,
  225. username,
  226. new PasswordEvidence(password));
  227. }
  228. /// <summary>
  229. /// Creates a credential used with MONGODB-CR.
  230. /// </summary>
  231. /// <param name="username">The username.</param>
  232. /// <returns>A credential for MONGODB-X509.</returns>
  233. public static MongoCredential CreateMongoX509Credential(string username)
  234. {
  235. return FromComponents("MONGODB-X509",
  236. "$external",
  237. username,
  238. new ExternalEvidence());
  239. }
  240. /// <summary>
  241. /// Creates a PLAIN credential.
  242. /// </summary>
  243. /// <param name="databaseName">Name of the database.</param>
  244. /// <param name="username">The username.</param>
  245. /// <param name="password">The password.</param>
  246. /// <returns>A credential for PLAIN.</returns>
  247. public static MongoCredential CreatePlainCredential(string databaseName, string username, string password)
  248. {
  249. return FromComponents("PLAIN",
  250. databaseName,
  251. username,
  252. new PasswordEvidence(password));
  253. }
  254. /// <summary>
  255. /// Creates a PLAIN credential.
  256. /// </summary>
  257. /// <param name="databaseName">Name of the database.</param>
  258. /// <param name="username">The username.</param>
  259. /// <param name="password">The password.</param>
  260. /// <returns>A credential for PLAIN.</returns>
  261. public static MongoCredential CreatePlainCredential(string databaseName, string username, SecureString password)
  262. {
  263. return FromComponents("PLAIN",
  264. databaseName,
  265. username,
  266. new PasswordEvidence(password));
  267. }
  268. // public methods
  269. /// <summary>
  270. /// Gets the mechanism property.
  271. /// </summary>
  272. /// <typeparam name="T">The type of the mechanism property.</typeparam>
  273. /// <param name="key">The key.</param>
  274. /// <param name="defaultValue">The default value.</param>
  275. /// <returns>The mechanism property if one was set; otherwise the default value.</returns>
  276. public T GetMechanismProperty<T>(string key, T defaultValue)
  277. {
  278. object value;
  279. if (_mechanismProperties.TryGetValue(key, out value))
  280. {
  281. return (T)value;
  282. }
  283. return defaultValue;
  284. }
  285. /// <summary>
  286. /// Compares this MongoCredential to another MongoCredential.
  287. /// </summary>
  288. /// <param name="rhs">The other credential.</param>
  289. /// <returns>True if the two credentials are equal.</returns>
  290. public bool Equals(MongoCredential rhs)
  291. {
  292. if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; }
  293. return _identity == rhs._identity &&
  294. _evidence == rhs._evidence &&
  295. _mechanism == rhs._mechanism &&
  296. _mechanismProperties.OrderBy(x => x.Key).SequenceEqual(rhs._mechanismProperties.OrderBy(x => x.Key));
  297. }
  298. /// <summary>
  299. /// Compares this MongoCredential to another MongoCredential.
  300. /// </summary>
  301. /// <param name="obj">The other credential.</param>
  302. /// <returns>True if the two credentials are equal.</returns>
  303. public override bool Equals(object obj)
  304. {
  305. return Equals(obj as MongoCredential); // works even if obj is null or of a different type
  306. }
  307. /// <summary>
  308. /// Gets the hashcode for the credential.
  309. /// </summary>
  310. /// <returns>The hashcode.</returns>
  311. public override int GetHashCode()
  312. {
  313. // see Effective Java by Joshua Bloch
  314. return new Hasher()
  315. .Hash(_identity)
  316. .Hash(_evidence)
  317. .Hash(_mechanism)
  318. .HashStructElements(_mechanismProperties)
  319. .GetHashCode();
  320. }
  321. /// <summary>
  322. /// Returns a string representation of the credential.
  323. /// </summary>
  324. /// <returns>A string representation of the credential.</returns>
  325. public override string ToString()
  326. {
  327. return string.Format("{0}@{1}", _identity.Username, _identity.Source);
  328. }
  329. /// <summary>
  330. /// Creates a new MongoCredential with the specified mechanism property.
  331. /// </summary>
  332. /// <param name="key">The key.</param>
  333. /// <param name="value">The value.</param>
  334. /// <returns>A new MongoCredential with the specified mechanism property.</returns>
  335. public MongoCredential WithMechanismProperty(string key, object value)
  336. {
  337. var copy = new MongoCredential(_mechanism, _identity, _evidence);
  338. foreach (var pair in _mechanismProperties)
  339. {
  340. copy._mechanismProperties.Add(pair.Key, pair.Value);
  341. }
  342. copy._mechanismProperties[key] = value; // overwrite if it's already set
  343. return copy;
  344. }
  345. // internal methods
  346. internal IAuthenticator ToAuthenticator()
  347. {
  348. var passwordEvidence = _evidence as PasswordEvidence;
  349. if (passwordEvidence != null)
  350. {
  351. var insecurePassword = MongoUtils.ToInsecureString(passwordEvidence.SecurePassword);
  352. var credential = new UsernamePasswordCredential(
  353. _identity.Source,
  354. _identity.Username,
  355. insecurePassword);
  356. if (_mechanism == null)
  357. {
  358. return new DefaultAuthenticator(credential);
  359. }
  360. else if (_mechanism == MongoDBCRAuthenticator.MechanismName)
  361. {
  362. return new MongoDBCRAuthenticator(credential);
  363. }
  364. else if (_mechanism == ScramSha1Authenticator.MechanismName)
  365. {
  366. return new ScramSha1Authenticator(credential);
  367. }
  368. else if (_mechanism == PlainAuthenticator.MechanismName)
  369. {
  370. return new PlainAuthenticator(credential);
  371. }
  372. else if (_mechanism == GssapiAuthenticator.MechanismName)
  373. {
  374. return new GssapiAuthenticator(
  375. credential,
  376. _mechanismProperties.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString())));
  377. }
  378. }
  379. else if (_identity.Source == "$external" && _evidence is ExternalEvidence)
  380. {
  381. if (_mechanism == MongoDBX509Authenticator.MechanismName)
  382. {
  383. return new MongoDBX509Authenticator(_identity.Username);
  384. }
  385. else if (_mechanism == GssapiAuthenticator.MechanismName)
  386. {
  387. return new GssapiAuthenticator(
  388. _identity.Username,
  389. _mechanismProperties.Select(x => new KeyValuePair<string, string>(x.Key, x.Value.ToString())));
  390. }
  391. }
  392. throw new NotSupportedException("Unable to create an authenticator.");
  393. }
  394. // internal static methods
  395. internal static MongoCredential FromComponents(string mechanism, string source, string username, string password)
  396. {
  397. var evidence = password == null ? (MongoIdentityEvidence)new ExternalEvidence() : new PasswordEvidence(password);
  398. return FromComponents(mechanism, source, username, evidence);
  399. }
  400. // private methods
  401. private void ValidatePassword(string password)
  402. {
  403. if (password == null)
  404. {
  405. throw new ArgumentNullException("password");
  406. }
  407. if (password.Any(c => (int)c >= 128))
  408. {
  409. throw new ArgumentException("Password must contain only ASCII characters.");
  410. }
  411. }
  412. // private static methods
  413. private static MongoCredential FromComponents(string mechanism, string source, string username, MongoIdentityEvidence evidence)
  414. {
  415. var defaultedMechanism = (mechanism ?? "DEFAULT").Trim().ToUpperInvariant();
  416. switch (defaultedMechanism)
  417. {
  418. case "DEFAULT":
  419. case "MONGODB-CR":
  420. case "SCRAM-SHA-1":
  421. // it is allowed for a password to be an empty string, but not a username
  422. source = source ?? "admin";
  423. if (evidence == null || !(evidence is PasswordEvidence))
  424. {
  425. var message = string.Format("A {0} credential must have a password.", defaultedMechanism);
  426. throw new ArgumentException(message);
  427. }
  428. return new MongoCredential(
  429. mechanism,
  430. new MongoInternalIdentity(source, username),
  431. evidence);
  432. case "MONGODB-X509":
  433. // always $external for X509.
  434. source = "$external";
  435. if (evidence == null || !(evidence is ExternalEvidence))
  436. {
  437. throw new ArgumentException("A MONGODB-X509 does not support a password.");
  438. }
  439. return new MongoCredential(
  440. mechanism,
  441. new MongoX509Identity(username),
  442. evidence);
  443. case "GSSAPI":
  444. // always $external for GSSAPI.
  445. source = "$external";
  446. return new MongoCredential(
  447. "GSSAPI",
  448. new MongoExternalIdentity(source, username),
  449. evidence);
  450. case "PLAIN":
  451. source = source ?? "admin";
  452. if (evidence == null || !(evidence is PasswordEvidence))
  453. {
  454. throw new ArgumentException("A PLAIN credential must have a password.");
  455. }
  456. MongoIdentity identity;
  457. if (source == "$external")
  458. {
  459. identity = new MongoExternalIdentity(source, username);
  460. }
  461. else
  462. {
  463. identity = new MongoInternalIdentity(source, username);
  464. }
  465. return new MongoCredential(
  466. mechanism,
  467. identity,
  468. evidence);
  469. default:
  470. throw new NotSupportedException(string.Format("Unsupported MongoAuthenticationMechanism {0}.", mechanism));
  471. }
  472. }
  473. }
  474. }