scram.js 9.6 KB

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