scram.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ScramSHA256 = exports.ScramSHA1 = void 0;
  4. const crypto = require("crypto");
  5. const util_1 = require("util");
  6. const bson_1 = require("../../bson");
  7. const deps_1 = require("../../deps");
  8. const error_1 = require("../../error");
  9. const utils_1 = require("../../utils");
  10. const auth_provider_1 = require("./auth_provider");
  11. const providers_1 = require("./providers");
  12. class ScramSHA extends auth_provider_1.AuthProvider {
  13. constructor(cryptoMethod) {
  14. super();
  15. this.cryptoMethod = cryptoMethod || 'sha1';
  16. this.randomBytesAsync = (0, util_1.promisify)(crypto.randomBytes);
  17. }
  18. async prepare(handshakeDoc, authContext) {
  19. const cryptoMethod = this.cryptoMethod;
  20. const credentials = authContext.credentials;
  21. if (!credentials) {
  22. throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.');
  23. }
  24. if (cryptoMethod === 'sha256' &&
  25. ('kModuleError' in deps_1.saslprep || typeof deps_1.saslprep !== 'function')) {
  26. (0, utils_1.emitWarning)('Warning: no saslprep library specified. Passwords will not be sanitized');
  27. }
  28. const nonce = await this.randomBytesAsync(24);
  29. // store the nonce for later use
  30. authContext.nonce = nonce;
  31. const request = {
  32. ...handshakeDoc,
  33. speculativeAuthenticate: {
  34. ...makeFirstMessage(cryptoMethod, credentials, nonce),
  35. db: credentials.source
  36. }
  37. };
  38. return request;
  39. }
  40. async auth(authContext) {
  41. const { reauthenticating, response } = authContext;
  42. if (response?.speculativeAuthenticate && !reauthenticating) {
  43. return continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext);
  44. }
  45. return executeScram(this.cryptoMethod, authContext);
  46. }
  47. }
  48. function cleanUsername(username) {
  49. return username.replace('=', '=3D').replace(',', '=2C');
  50. }
  51. function clientFirstMessageBare(username, nonce) {
  52. // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.
  53. // Since the username is not sasl-prep-d, we need to do this here.
  54. return Buffer.concat([
  55. Buffer.from('n=', 'utf8'),
  56. Buffer.from(username, 'utf8'),
  57. Buffer.from(',r=', 'utf8'),
  58. Buffer.from(nonce.toString('base64'), 'utf8')
  59. ]);
  60. }
  61. function makeFirstMessage(cryptoMethod, credentials, nonce) {
  62. const username = cleanUsername(credentials.username);
  63. const mechanism = cryptoMethod === 'sha1' ? providers_1.AuthMechanism.MONGODB_SCRAM_SHA1 : providers_1.AuthMechanism.MONGODB_SCRAM_SHA256;
  64. // NOTE: This is done b/c Javascript uses UTF-16, but the server is hashing in UTF-8.
  65. // Since the username is not sasl-prep-d, we need to do this here.
  66. return {
  67. saslStart: 1,
  68. mechanism,
  69. payload: new bson_1.Binary(Buffer.concat([Buffer.from('n,,', 'utf8'), clientFirstMessageBare(username, nonce)])),
  70. autoAuthorize: 1,
  71. options: { skipEmptyExchange: true }
  72. };
  73. }
  74. async function executeScram(cryptoMethod, authContext) {
  75. const { connection, credentials } = authContext;
  76. if (!credentials) {
  77. throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.');
  78. }
  79. if (!authContext.nonce) {
  80. throw new error_1.MongoInvalidArgumentError('AuthContext must contain a valid nonce property');
  81. }
  82. const nonce = authContext.nonce;
  83. const db = credentials.source;
  84. const saslStartCmd = makeFirstMessage(cryptoMethod, credentials, nonce);
  85. const response = await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, undefined);
  86. await continueScramConversation(cryptoMethod, response, authContext);
  87. }
  88. async function continueScramConversation(cryptoMethod, response, authContext) {
  89. const connection = authContext.connection;
  90. const credentials = authContext.credentials;
  91. if (!credentials) {
  92. throw new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.');
  93. }
  94. if (!authContext.nonce) {
  95. throw new error_1.MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce');
  96. }
  97. const nonce = authContext.nonce;
  98. const db = credentials.source;
  99. const username = cleanUsername(credentials.username);
  100. const password = credentials.password;
  101. let processedPassword;
  102. if (cryptoMethod === 'sha256') {
  103. processedPassword =
  104. 'kModuleError' in deps_1.saslprep || typeof deps_1.saslprep !== 'function' ? password : (0, deps_1.saslprep)(password);
  105. }
  106. else {
  107. processedPassword = passwordDigest(username, password);
  108. }
  109. const payload = Buffer.isBuffer(response.payload)
  110. ? new bson_1.Binary(response.payload)
  111. : response.payload;
  112. const dict = parsePayload(payload.value());
  113. const iterations = parseInt(dict.i, 10);
  114. if (iterations && iterations < 4096) {
  115. // TODO(NODE-3483)
  116. throw new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`);
  117. }
  118. const salt = dict.s;
  119. const rnonce = dict.r;
  120. if (rnonce.startsWith('nonce')) {
  121. // TODO(NODE-3483)
  122. throw new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`);
  123. }
  124. // Set up start of proof
  125. const withoutProof = `c=biws,r=${rnonce}`;
  126. const saltedPassword = HI(processedPassword, Buffer.from(salt, 'base64'), iterations, cryptoMethod);
  127. const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key');
  128. const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key');
  129. const storedKey = H(cryptoMethod, clientKey);
  130. const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join(',');
  131. const clientSignature = HMAC(cryptoMethod, storedKey, authMessage);
  132. const clientProof = `p=${xor(clientKey, clientSignature)}`;
  133. const clientFinal = [withoutProof, clientProof].join(',');
  134. const serverSignature = HMAC(cryptoMethod, serverKey, authMessage);
  135. const saslContinueCmd = {
  136. saslContinue: 1,
  137. conversationId: response.conversationId,
  138. payload: new bson_1.Binary(Buffer.from(clientFinal))
  139. };
  140. const r = await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined);
  141. const parsedResponse = parsePayload(r.payload.value());
  142. if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) {
  143. throw new error_1.MongoRuntimeError('Server returned an invalid signature');
  144. }
  145. if (r.done !== false) {
  146. // If the server sends r.done === true we can save one RTT
  147. return;
  148. }
  149. const retrySaslContinueCmd = {
  150. saslContinue: 1,
  151. conversationId: r.conversationId,
  152. payload: Buffer.alloc(0)
  153. };
  154. await connection.commandAsync((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, undefined);
  155. }
  156. function parsePayload(payload) {
  157. const dict = {};
  158. const parts = payload.split(',');
  159. for (let i = 0; i < parts.length; i++) {
  160. const valueParts = parts[i].split('=');
  161. dict[valueParts[0]] = valueParts[1];
  162. }
  163. return dict;
  164. }
  165. function passwordDigest(username, password) {
  166. if (typeof username !== 'string') {
  167. throw new error_1.MongoInvalidArgumentError('Username must be a string');
  168. }
  169. if (typeof password !== 'string') {
  170. throw new error_1.MongoInvalidArgumentError('Password must be a string');
  171. }
  172. if (password.length === 0) {
  173. throw new error_1.MongoInvalidArgumentError('Password cannot be empty');
  174. }
  175. let md5;
  176. try {
  177. md5 = crypto.createHash('md5');
  178. }
  179. catch (err) {
  180. if (crypto.getFips()) {
  181. // This error is (slightly) more helpful than what comes from OpenSSL directly, e.g.
  182. // 'Error: error:060800C8:digital envelope routines:EVP_DigestInit_ex:disabled for FIPS'
  183. throw new Error('Auth mechanism SCRAM-SHA-1 is not supported in FIPS mode');
  184. }
  185. throw err;
  186. }
  187. md5.update(`${username}:mongo:${password}`, 'utf8');
  188. return md5.digest('hex');
  189. }
  190. // XOR two buffers
  191. function xor(a, b) {
  192. if (!Buffer.isBuffer(a)) {
  193. a = Buffer.from(a);
  194. }
  195. if (!Buffer.isBuffer(b)) {
  196. b = Buffer.from(b);
  197. }
  198. const length = Math.max(a.length, b.length);
  199. const res = [];
  200. for (let i = 0; i < length; i += 1) {
  201. res.push(a[i] ^ b[i]);
  202. }
  203. return Buffer.from(res).toString('base64');
  204. }
  205. function H(method, text) {
  206. return crypto.createHash(method).update(text).digest();
  207. }
  208. function HMAC(method, key, text) {
  209. return crypto.createHmac(method, key).update(text).digest();
  210. }
  211. let _hiCache = {};
  212. let _hiCacheCount = 0;
  213. function _hiCachePurge() {
  214. _hiCache = {};
  215. _hiCacheCount = 0;
  216. }
  217. const hiLengthMap = {
  218. sha256: 32,
  219. sha1: 20
  220. };
  221. function HI(data, salt, iterations, cryptoMethod) {
  222. // omit the work if already generated
  223. const key = [data, salt.toString('base64'), iterations].join('_');
  224. if (_hiCache[key] != null) {
  225. return _hiCache[key];
  226. }
  227. // generate the salt
  228. const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod);
  229. // cache a copy to speed up the next lookup, but prevent unbounded cache growth
  230. if (_hiCacheCount >= 200) {
  231. _hiCachePurge();
  232. }
  233. _hiCache[key] = saltedData;
  234. _hiCacheCount += 1;
  235. return saltedData;
  236. }
  237. function compareDigest(lhs, rhs) {
  238. if (lhs.length !== rhs.length) {
  239. return false;
  240. }
  241. if (typeof crypto.timingSafeEqual === 'function') {
  242. return crypto.timingSafeEqual(lhs, rhs);
  243. }
  244. let result = 0;
  245. for (let i = 0; i < lhs.length; i++) {
  246. result |= lhs[i] ^ rhs[i];
  247. }
  248. return result === 0;
  249. }
  250. class ScramSHA1 extends ScramSHA {
  251. constructor() {
  252. super('sha1');
  253. }
  254. }
  255. exports.ScramSHA1 = ScramSHA1;
  256. class ScramSHA256 extends ScramSHA {
  257. constructor() {
  258. super('sha256');
  259. }
  260. }
  261. exports.ScramSHA256 = ScramSHA256;
  262. //# sourceMappingURL=scram.js.map