PasswordEvidence.cs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  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.Linq;
  17. using System.Runtime.InteropServices;
  18. using System.Security;
  19. using System.Security.Cryptography;
  20. using MongoDB.Bson;
  21. using MongoDB.Bson.IO;
  22. using MongoDB.Driver.Core.Misc;
  23. using MongoDB.Shared;
  24. namespace MongoDB.Driver
  25. {
  26. /// <summary>
  27. /// Evidence of a MongoIdentity via a shared secret.
  28. /// </summary>
  29. public sealed class PasswordEvidence : MongoIdentityEvidence
  30. {
  31. // private fields
  32. private readonly SecureString _securePassword;
  33. // constructors
  34. /// <summary>
  35. /// Initializes a new instance of the <see cref="PasswordEvidence" /> class.
  36. /// Less secure when used in conjunction with SCRAM-SHA-256, due to the need to store the password in a managed
  37. /// string in order to SaslPrep it.
  38. /// See <a href="https://github.com/mongodb/specifications/blob/master/source/auth/auth.rst#scram-sha-256">Driver Authentication: SCRAM-SHA-256</a>
  39. /// for additional details.
  40. /// </summary>
  41. /// <param name="password">The password.</param>
  42. public PasswordEvidence(SecureString password)
  43. {
  44. Ensure.IsNotNull(password, nameof(password));
  45. _securePassword = password.Copy();
  46. _securePassword.MakeReadOnly();
  47. }
  48. /// <summary>
  49. /// Initializes a new instance of the <see cref="PasswordEvidence" /> class.
  50. /// </summary>
  51. /// <param name="password">The password.</param>
  52. public PasswordEvidence(string password)
  53. {
  54. Ensure.IsNotNull(password, nameof(password));
  55. _securePassword = CreateSecureString(password);
  56. }
  57. // public properties
  58. /// <summary>
  59. /// Gets the password.
  60. /// </summary>
  61. public SecureString SecurePassword
  62. {
  63. get { return _securePassword; }
  64. }
  65. // public methods
  66. /// <summary>
  67. /// Determines whether the specified <see cref="System.Object" /> is equal to this instance.
  68. /// </summary>
  69. /// <param name="rhs">The <see cref="System.Object" /> to compare with this instance.</param>
  70. /// <returns>
  71. /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; otherwise, <c>false</c>.
  72. /// </returns>
  73. public override bool Equals(object rhs)
  74. {
  75. if (object.ReferenceEquals(rhs, null) || GetType() != rhs.GetType()) { return false; }
  76. using (var lhsDecryptedPassword = new DecryptedSecureString(_securePassword))
  77. using (var rhsDecryptedPassword = new DecryptedSecureString(((PasswordEvidence)rhs)._securePassword))
  78. {
  79. return lhsDecryptedPassword.GetChars().SequenceEqual(rhsDecryptedPassword.GetChars());
  80. }
  81. }
  82. /// <summary>
  83. /// Returns a hash code for this instance.
  84. /// </summary>
  85. /// <returns>
  86. /// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
  87. /// </returns>
  88. public override int GetHashCode()
  89. {
  90. using (var decryptedPassword = new DecryptedSecureString(_securePassword))
  91. {
  92. return new Hasher().HashStructElements(decryptedPassword.GetChars()).GetHashCode();
  93. }
  94. }
  95. // internal methods
  96. /// <summary>
  97. /// Computes the MONGODB-CR password digest.
  98. /// </summary>
  99. /// <param name="username">The username.</param>
  100. /// <returns>The MONGODB-CR password digest.</returns>
  101. [Obsolete("MONGODB-CR was replaced by SCRAM-SHA-1 in MongoDB 3.0, and is now deprecated.")]
  102. internal string ComputeMongoCRPasswordDigest(string username)
  103. {
  104. using (var md5 = MD5.Create())
  105. using (var decryptedPassword = new DecryptedSecureString(_securePassword))
  106. {
  107. var encoding = Utf8Encodings.Strict;
  108. var prefixBytes = encoding.GetBytes(username + ":mongo:");
  109. var hash = ComputeHash(md5, prefixBytes, decryptedPassword.GetUtf8Bytes());
  110. return BsonUtils.ToHexString(hash);
  111. }
  112. }
  113. // private static methods
  114. private static SecureString CreateSecureString(string value)
  115. {
  116. var secureString = new SecureString();
  117. foreach (var c in value)
  118. {
  119. secureString.AppendChar(c);
  120. }
  121. secureString.MakeReadOnly();
  122. return secureString;
  123. }
  124. private static byte[] ComputeHash(HashAlgorithm algorithm, byte[] prefixBytes, byte[] passwordBytes)
  125. {
  126. var buffer = new byte[prefixBytes.Length + passwordBytes.Length];
  127. var bufferHandle = GCHandle.Alloc(buffer, GCHandleType.Pinned);
  128. try
  129. {
  130. Buffer.BlockCopy(prefixBytes, 0, buffer, 0, prefixBytes.Length);
  131. Buffer.BlockCopy(passwordBytes, 0, buffer, prefixBytes.Length, passwordBytes.Length);
  132. return algorithm.ComputeHash(buffer);
  133. }
  134. finally
  135. {
  136. Array.Clear(buffer, 0, buffer.Length);
  137. bufferHandle.Free();
  138. }
  139. }
  140. }
  141. }