scram.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.ScramSHA256 = exports.ScramSHA1 = void 0;
  4. const crypto = require("crypto");
  5. const bson_1 = require("../../bson");
  6. const deps_1 = require("../../deps");
  7. const error_1 = require("../../error");
  8. const utils_1 = require("../../utils");
  9. const auth_provider_1 = require("./auth_provider");
  10. const providers_1 = require("./providers");
  11. class ScramSHA extends auth_provider_1.AuthProvider {
  12. constructor(cryptoMethod) {
  13. super();
  14. this.cryptoMethod = cryptoMethod || 'sha1';
  15. }
  16. prepare(handshakeDoc, authContext, callback) {
  17. const cryptoMethod = this.cryptoMethod;
  18. const credentials = authContext.credentials;
  19. if (!credentials) {
  20. return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'));
  21. }
  22. if (cryptoMethod === 'sha256' && deps_1.saslprep == null) {
  23. (0, utils_1.emitWarning)('Warning: no saslprep library specified. Passwords will not be sanitized');
  24. }
  25. crypto.randomBytes(24, (err, nonce) => {
  26. if (err) {
  27. return callback(err);
  28. }
  29. // store the nonce for later use
  30. Object.assign(authContext, { nonce });
  31. const request = Object.assign({}, handshakeDoc, {
  32. speculativeAuthenticate: Object.assign(makeFirstMessage(cryptoMethod, credentials, nonce), {
  33. db: credentials.source
  34. })
  35. });
  36. callback(undefined, request);
  37. });
  38. }
  39. auth(authContext, callback) {
  40. const response = authContext.response;
  41. if (response && response.speculativeAuthenticate) {
  42. continueScramConversation(this.cryptoMethod, response.speculativeAuthenticate, authContext, callback);
  43. return;
  44. }
  45. executeScram(this.cryptoMethod, authContext, callback);
  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. function executeScram(cryptoMethod, authContext, callback) {
  75. const { connection, credentials } = authContext;
  76. if (!credentials) {
  77. return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'));
  78. }
  79. if (!authContext.nonce) {
  80. return callback(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. connection.command((0, utils_1.ns)(`${db}.$cmd`), saslStartCmd, undefined, (_err, result) => {
  86. const err = resolveError(_err, result);
  87. if (err) {
  88. return callback(err);
  89. }
  90. continueScramConversation(cryptoMethod, result, authContext, callback);
  91. });
  92. }
  93. function continueScramConversation(cryptoMethod, response, authContext, callback) {
  94. const connection = authContext.connection;
  95. const credentials = authContext.credentials;
  96. if (!credentials) {
  97. return callback(new error_1.MongoMissingCredentialsError('AuthContext must provide credentials.'));
  98. }
  99. if (!authContext.nonce) {
  100. return callback(new error_1.MongoInvalidArgumentError('Unable to continue SCRAM without valid nonce'));
  101. }
  102. const nonce = authContext.nonce;
  103. const db = credentials.source;
  104. const username = cleanUsername(credentials.username);
  105. const password = credentials.password;
  106. let processedPassword;
  107. if (cryptoMethod === 'sha256') {
  108. processedPassword = 'kModuleError' in deps_1.saslprep ? password : (0, deps_1.saslprep)(password);
  109. }
  110. else {
  111. try {
  112. processedPassword = passwordDigest(username, password);
  113. }
  114. catch (e) {
  115. return callback(e);
  116. }
  117. }
  118. const payload = Buffer.isBuffer(response.payload)
  119. ? new bson_1.Binary(response.payload)
  120. : response.payload;
  121. const dict = parsePayload(payload.value());
  122. const iterations = parseInt(dict.i, 10);
  123. if (iterations && iterations < 4096) {
  124. callback(
  125. // TODO(NODE-3483)
  126. new error_1.MongoRuntimeError(`Server returned an invalid iteration count ${iterations}`), false);
  127. return;
  128. }
  129. const salt = dict.s;
  130. const rnonce = dict.r;
  131. if (rnonce.startsWith('nonce')) {
  132. // TODO(NODE-3483)
  133. callback(new error_1.MongoRuntimeError(`Server returned an invalid nonce: ${rnonce}`), false);
  134. return;
  135. }
  136. // Set up start of proof
  137. const withoutProof = `c=biws,r=${rnonce}`;
  138. const saltedPassword = HI(processedPassword, Buffer.from(salt, 'base64'), iterations, cryptoMethod);
  139. const clientKey = HMAC(cryptoMethod, saltedPassword, 'Client Key');
  140. const serverKey = HMAC(cryptoMethod, saltedPassword, 'Server Key');
  141. const storedKey = H(cryptoMethod, clientKey);
  142. const authMessage = [clientFirstMessageBare(username, nonce), payload.value(), withoutProof].join(',');
  143. const clientSignature = HMAC(cryptoMethod, storedKey, authMessage);
  144. const clientProof = `p=${xor(clientKey, clientSignature)}`;
  145. const clientFinal = [withoutProof, clientProof].join(',');
  146. const serverSignature = HMAC(cryptoMethod, serverKey, authMessage);
  147. const saslContinueCmd = {
  148. saslContinue: 1,
  149. conversationId: response.conversationId,
  150. payload: new bson_1.Binary(Buffer.from(clientFinal))
  151. };
  152. connection.command((0, utils_1.ns)(`${db}.$cmd`), saslContinueCmd, undefined, (_err, r) => {
  153. const err = resolveError(_err, r);
  154. if (err) {
  155. return callback(err);
  156. }
  157. const parsedResponse = parsePayload(r.payload.value());
  158. if (!compareDigest(Buffer.from(parsedResponse.v, 'base64'), serverSignature)) {
  159. callback(new error_1.MongoRuntimeError('Server returned an invalid signature'));
  160. return;
  161. }
  162. if (!r || r.done !== false) {
  163. return callback(err, r);
  164. }
  165. const retrySaslContinueCmd = {
  166. saslContinue: 1,
  167. conversationId: r.conversationId,
  168. payload: Buffer.alloc(0)
  169. };
  170. connection.command((0, utils_1.ns)(`${db}.$cmd`), retrySaslContinueCmd, undefined, callback);
  171. });
  172. }
  173. function parsePayload(payload) {
  174. const dict = {};
  175. const parts = payload.split(',');
  176. for (let i = 0; i < parts.length; i++) {
  177. const valueParts = parts[i].split('=');
  178. dict[valueParts[0]] = valueParts[1];
  179. }
  180. return dict;
  181. }
  182. function passwordDigest(username, password) {
  183. if (typeof username !== 'string') {
  184. throw new error_1.MongoInvalidArgumentError('Username must be a string');
  185. }
  186. if (typeof password !== 'string') {
  187. throw new error_1.MongoInvalidArgumentError('Password must be a string');
  188. }
  189. if (password.length === 0) {
  190. throw new error_1.MongoInvalidArgumentError('Password cannot be empty');
  191. }
  192. const md5 = crypto.createHash('md5');
  193. md5.update(`${username}:mongo:${password}`, 'utf8');
  194. return md5.digest('hex');
  195. }
  196. // XOR two buffers
  197. function xor(a, b) {
  198. if (!Buffer.isBuffer(a)) {
  199. a = Buffer.from(a);
  200. }
  201. if (!Buffer.isBuffer(b)) {
  202. b = Buffer.from(b);
  203. }
  204. const length = Math.max(a.length, b.length);
  205. const res = [];
  206. for (let i = 0; i < length; i += 1) {
  207. res.push(a[i] ^ b[i]);
  208. }
  209. return Buffer.from(res).toString('base64');
  210. }
  211. function H(method, text) {
  212. return crypto.createHash(method).update(text).digest();
  213. }
  214. function HMAC(method, key, text) {
  215. return crypto.createHmac(method, key).update(text).digest();
  216. }
  217. let _hiCache = {};
  218. let _hiCacheCount = 0;
  219. function _hiCachePurge() {
  220. _hiCache = {};
  221. _hiCacheCount = 0;
  222. }
  223. const hiLengthMap = {
  224. sha256: 32,
  225. sha1: 20
  226. };
  227. function HI(data, salt, iterations, cryptoMethod) {
  228. // omit the work if already generated
  229. const key = [data, salt.toString('base64'), iterations].join('_');
  230. if (_hiCache[key] != null) {
  231. return _hiCache[key];
  232. }
  233. // generate the salt
  234. const saltedData = crypto.pbkdf2Sync(data, salt, iterations, hiLengthMap[cryptoMethod], cryptoMethod);
  235. // cache a copy to speed up the next lookup, but prevent unbounded cache growth
  236. if (_hiCacheCount >= 200) {
  237. _hiCachePurge();
  238. }
  239. _hiCache[key] = saltedData;
  240. _hiCacheCount += 1;
  241. return saltedData;
  242. }
  243. function compareDigest(lhs, rhs) {
  244. if (lhs.length !== rhs.length) {
  245. return false;
  246. }
  247. if (typeof crypto.timingSafeEqual === 'function') {
  248. return crypto.timingSafeEqual(lhs, rhs);
  249. }
  250. let result = 0;
  251. for (let i = 0; i < lhs.length; i++) {
  252. result |= lhs[i] ^ rhs[i];
  253. }
  254. return result === 0;
  255. }
  256. function resolveError(err, result) {
  257. if (err)
  258. return err;
  259. if (result) {
  260. if (result.$err || result.errmsg)
  261. return new error_1.MongoServerError(result);
  262. }
  263. }
  264. class ScramSHA1 extends ScramSHA {
  265. constructor() {
  266. super('sha1');
  267. }
  268. }
  269. exports.ScramSHA1 = ScramSHA1;
  270. class ScramSHA256 extends ScramSHA {
  271. constructor() {
  272. super('sha256');
  273. }
  274. }
  275. exports.ScramSHA256 = ScramSHA256;
  276. //# sourceMappingURL=scram.js.map