scram.js 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. "use strict";
  2. var f = require('util').format
  3. , crypto = require('crypto')
  4. , retrieveBSON = require('../connection/utils').retrieveBSON
  5. , Query = require('../connection/commands').Query
  6. , MongoError = require('../error');
  7. var BSON = retrieveBSON(),
  8. Binary = BSON.Binary;
  9. var AuthSession = function(db, username, password) {
  10. this.db = db;
  11. this.username = username;
  12. this.password = password;
  13. }
  14. AuthSession.prototype.equal = function(session) {
  15. return session.db == this.db
  16. && session.username == this.username
  17. && session.password == this.password;
  18. }
  19. var id = 0;
  20. /**
  21. * Creates a new ScramSHA1 authentication mechanism
  22. * @class
  23. * @return {ScramSHA1} A cursor instance
  24. */
  25. var ScramSHA1 = function(bson) {
  26. this.bson = bson;
  27. this.authStore = [];
  28. this.id = id++;
  29. }
  30. var parsePayload = function(payload) {
  31. var dict = {};
  32. var parts = payload.split(',');
  33. for(var i = 0; i < parts.length; i++) {
  34. var valueParts = parts[i].split('=');
  35. dict[valueParts[0]] = valueParts[1];
  36. }
  37. return dict;
  38. }
  39. var passwordDigest = function(username, password) {
  40. if(typeof username != 'string') throw new MongoError("username must be a string");
  41. if(typeof password != 'string') throw new MongoError("password must be a string");
  42. if(password.length == 0) throw new MongoError("password cannot be empty");
  43. // Use node md5 generator
  44. var md5 = crypto.createHash('md5');
  45. // Generate keys used for authentication
  46. md5.update(username + ":mongo:" + password, 'utf8');
  47. return md5.digest('hex');
  48. }
  49. // XOR two buffers
  50. var xor = function(a, b) {
  51. if (!Buffer.isBuffer(a)) a = new Buffer(a)
  52. if (!Buffer.isBuffer(b)) b = new Buffer(b)
  53. var res = []
  54. if (a.length > b.length) {
  55. for (var i = 0; i < b.length; i++) {
  56. res.push(a[i] ^ b[i])
  57. }
  58. } else {
  59. for (i = 0; i < a.length; i++) {
  60. res.push(a[i] ^ b[i])
  61. }
  62. }
  63. return new Buffer(res);
  64. }
  65. // Create a final digest
  66. var hi = function(data, salt, iterations) {
  67. // Create digest
  68. var digest = function(msg) {
  69. var hmac = crypto.createHmac('sha1', data);
  70. hmac.update(msg);
  71. return new Buffer(hmac.digest('base64'), 'base64');
  72. }
  73. // Create variables
  74. salt = Buffer.concat([salt, new Buffer('\x00\x00\x00\x01')])
  75. var ui = digest(salt);
  76. var u1 = ui;
  77. for(var i = 0; i < iterations - 1; i++) {
  78. u1 = digest(u1);
  79. ui = xor(ui, u1);
  80. }
  81. return ui;
  82. }
  83. /**
  84. * Authenticate
  85. * @method
  86. * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on
  87. * @param {[]Connections} connections Connections to authenticate using this authenticator
  88. * @param {string} db Name of the database
  89. * @param {string} username Username
  90. * @param {string} password Password
  91. * @param {authResultCallback} callback The callback to return the result from the authentication
  92. * @return {object}
  93. */
  94. ScramSHA1.prototype.auth = function(server, connections, db, username, password, callback) {
  95. var self = this;
  96. // Total connections
  97. var count = connections.length;
  98. if(count == 0) return callback(null, null);
  99. // Valid connections
  100. var numberOfValidConnections = 0;
  101. var errorObject = null;
  102. // Execute MongoCR
  103. var executeScram = function(connection) {
  104. // Clean up the user
  105. username = username.replace('=', "=3D").replace(',', '=2C');
  106. // Create a random nonce
  107. var nonce = crypto.randomBytes(24).toString('base64');
  108. // var nonce = 'MsQUY9iw0T9fx2MUEz6LZPwGuhVvWAhc'
  109. var firstBare = f("n=%s,r=%s", username, nonce);
  110. // Build command structure
  111. var cmd = {
  112. saslStart: 1
  113. , mechanism: 'SCRAM-SHA-1'
  114. , payload: new Binary(f("n,,%s", firstBare))
  115. , autoAuthorize: 1
  116. }
  117. // Handle the error
  118. var handleError = function(err, r) {
  119. if(err) {
  120. numberOfValidConnections = numberOfValidConnections - 1;
  121. errorObject = err; return false;
  122. } else if(r.result['$err']) {
  123. errorObject = r.result; return false;
  124. } else if(r.result['errmsg']) {
  125. errorObject = r.result; return false;
  126. } else {
  127. numberOfValidConnections = numberOfValidConnections + 1;
  128. }
  129. return true
  130. }
  131. // Finish up
  132. var finish = function(_count, _numberOfValidConnections) {
  133. if(_count == 0 && _numberOfValidConnections > 0) {
  134. // Store the auth details
  135. addAuthSession(self.authStore, new AuthSession(db, username, password));
  136. // Return correct authentication
  137. return callback(null, true);
  138. } else if(_count == 0) {
  139. if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram"));
  140. return callback(errorObject, false);
  141. }
  142. }
  143. var handleEnd = function(_err, _r) {
  144. // Handle any error
  145. handleError(_err, _r)
  146. // Adjust the number of connections
  147. count = count - 1;
  148. // Execute the finish
  149. finish(count, numberOfValidConnections);
  150. }
  151. // Write the commmand on the connection
  152. server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, {
  153. numberToSkip: 0, numberToReturn: 1
  154. }), function(err, r) {
  155. // Do we have an error, handle it
  156. if(handleError(err, r) == false) {
  157. count = count - 1;
  158. if(count == 0 && numberOfValidConnections > 0) {
  159. // Store the auth details
  160. addAuthSession(self.authStore, new AuthSession(db, username, password));
  161. // Return correct authentication
  162. return callback(null, true);
  163. } else if(count == 0) {
  164. if(errorObject == null) errorObject = new MongoError(f("failed to authenticate using scram"));
  165. return callback(errorObject, false);
  166. }
  167. return;
  168. }
  169. // Get the dictionary
  170. var dict = parsePayload(r.result.payload.value())
  171. // Unpack dictionary
  172. var iterations = parseInt(dict.i, 10);
  173. var salt = dict.s;
  174. var rnonce = dict.r;
  175. // Set up start of proof
  176. var withoutProof = f("c=biws,r=%s", rnonce);
  177. var passwordDig = passwordDigest(username, password);
  178. var saltedPassword = hi(passwordDig
  179. , new Buffer(salt, 'base64')
  180. , iterations);
  181. // Create the client key
  182. var hmac = crypto.createHmac('sha1', saltedPassword);
  183. hmac.update(new Buffer("Client Key"));
  184. var clientKey = new Buffer(hmac.digest('base64'), 'base64');
  185. // Create the stored key
  186. var hash = crypto.createHash('sha1');
  187. hash.update(clientKey);
  188. var storedKey = new Buffer(hash.digest('base64'), 'base64');
  189. // Create the authentication message
  190. var authMsg = [firstBare, r.result.payload.value().toString('base64'), withoutProof].join(',');
  191. // Create client signature
  192. hmac = crypto.createHmac('sha1', storedKey);
  193. hmac.update(new Buffer(authMsg));
  194. var clientSig = new Buffer(hmac.digest('base64'), 'base64');
  195. // Create client proof
  196. var clientProof = f("p=%s", new Buffer(xor(clientKey, clientSig)).toString('base64'));
  197. // Create client final
  198. var clientFinal = [withoutProof, clientProof].join(',');
  199. // Generate server key
  200. hmac = crypto.createHmac('sha1', saltedPassword);
  201. hmac.update(new Buffer('Server Key'))
  202. var serverKey = new Buffer(hmac.digest('base64'), 'base64');
  203. // Generate server signature
  204. hmac = crypto.createHmac('sha1', serverKey);
  205. hmac.update(new Buffer(authMsg))
  206. //
  207. // Create continue message
  208. var cmd = {
  209. saslContinue: 1
  210. , conversationId: r.result.conversationId
  211. , payload: new Binary(new Buffer(clientFinal))
  212. }
  213. //
  214. // Execute sasl continue
  215. // Write the commmand on the connection
  216. server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, {
  217. numberToSkip: 0, numberToReturn: 1
  218. }), function(err, r) {
  219. if(r && r.result.done == false) {
  220. var cmd = {
  221. saslContinue: 1
  222. , conversationId: r.result.conversationId
  223. , payload: new Buffer(0)
  224. }
  225. // Write the commmand on the connection
  226. server(connection, new Query(self.bson, f("%s.$cmd", db), cmd, {
  227. numberToSkip: 0, numberToReturn: 1
  228. }), function(err, r) {
  229. handleEnd(err, r);
  230. });
  231. } else {
  232. handleEnd(err, r);
  233. }
  234. });
  235. });
  236. }
  237. var _execute = function(_connection) {
  238. process.nextTick(function() {
  239. executeScram(_connection);
  240. });
  241. }
  242. // For each connection we need to authenticate
  243. while(connections.length > 0) {
  244. _execute(connections.shift());
  245. }
  246. }
  247. // Add to store only if it does not exist
  248. var addAuthSession = function(authStore, session) {
  249. var found = false;
  250. for(var i = 0; i < authStore.length; i++) {
  251. if(authStore[i].equal(session)) {
  252. found = true;
  253. break;
  254. }
  255. }
  256. if(!found) authStore.push(session);
  257. }
  258. /**
  259. * Remove authStore credentials
  260. * @method
  261. * @param {string} db Name of database we are removing authStore details about
  262. * @return {object}
  263. */
  264. ScramSHA1.prototype.logout = function(dbName) {
  265. this.authStore = this.authStore.filter(function(x) {
  266. return x.db != dbName;
  267. });
  268. }
  269. /**
  270. * Re authenticate pool
  271. * @method
  272. * @param {{Server}|{ReplSet}|{Mongos}} server Topology the authentication method is being called on
  273. * @param {[]Connections} connections Connections to authenticate using this authenticator
  274. * @param {authResultCallback} callback The callback to return the result from the authentication
  275. * @return {object}
  276. */
  277. ScramSHA1.prototype.reauthenticate = function(server, connections, callback) {
  278. var authStore = this.authStore.slice(0);
  279. var count = authStore.length;
  280. // No connections
  281. if(count == 0) return callback(null, null);
  282. // Iterate over all the auth details stored
  283. for(var i = 0; i < authStore.length; i++) {
  284. this.auth(server, connections, authStore[i].db, authStore[i].username, authStore[i].password, function(err) {
  285. count = count - 1;
  286. // Done re-authenticating
  287. if(count == 0) {
  288. callback(err, null);
  289. }
  290. });
  291. }
  292. }
  293. module.exports = ScramSHA1;