AuthenticationManager.js 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510
  1. const Settings = require('@overleaf/settings')
  2. const { User } = require('../../models/User')
  3. const { db, ObjectId } = require('../../infrastructure/mongodb')
  4. const bcrypt = require('bcrypt')
  5. const EmailHelper = require('../Helpers/EmailHelper')
  6. const {
  7. InvalidEmailError,
  8. InvalidPasswordError,
  9. ParallelLoginError,
  10. PasswordMustBeDifferentError,
  11. PasswordReusedError,
  12. } = require('./AuthenticationErrors')
  13. const util = require('util')
  14. const HaveIBeenPwned = require('./HaveIBeenPwned')
  15. const UserAuditLogHandler = require('../User/UserAuditLogHandler')
  16. const logger = require('@overleaf/logger')
  17. const DiffHelper = require('../Helpers/DiffHelper')
  18. const Metrics = require('@overleaf/metrics')
  19. const BCRYPT_ROUNDS = Settings.security.bcryptRounds || 12
  20. const BCRYPT_MINOR_VERSION = Settings.security.bcryptMinorVersion || 'a'
  21. const MAX_SIMILARITY = 0.7
  22. function _exceedsMaximumLengthRatio(password, maxSimilarity, value) {
  23. const passwordLength = password.length
  24. const lengthBoundSimilarity = (maxSimilarity / 2) * passwordLength
  25. const valueLength = value.length
  26. return (
  27. passwordLength >= 10 * valueLength && valueLength < lengthBoundSimilarity
  28. )
  29. }
  30. const _checkWriteResult = function (result, callback) {
  31. // for MongoDB
  32. if (result && result.modifiedCount === 1) {
  33. callback(null, true)
  34. } else {
  35. callback(null, false)
  36. }
  37. }
  38. function _validatePasswordNotTooLong(password) {
  39. // bcrypt has a hard limit of 72 characters.
  40. if (password.length > 72) {
  41. return new InvalidPasswordError({
  42. message: 'password is too long',
  43. info: { code: 'too_long' },
  44. })
  45. }
  46. return null
  47. }
  48. function _metricsForSuccessfulPasswordMatch(password) {
  49. const validationResult = AuthenticationManager.validatePassword(password)
  50. const status =
  51. validationResult === null ? 'success' : validationResult?.info?.code
  52. Metrics.inc('check-password', { status })
  53. return null
  54. }
  55. const AuthenticationManager = {
  56. _checkUserPassword(query, password, callback) {
  57. HaveIBeenPwned.checkPasswordForReuse(password, (err, isPasswordReused) => {
  58. if (err) {
  59. logger.err({ err }, 'cannot check password for re-use')
  60. }
  61. if (isPasswordReused) return callback(new PasswordReusedError())
  62. AuthenticationManager._checkUserPasswordWithOutHIBPCheck(
  63. query,
  64. password,
  65. callback
  66. )
  67. })
  68. },
  69. _checkUserPasswordWithOutHIBPCheck(query, password, callback) {
  70. // Using Mongoose for legacy reasons here. The returned User instance
  71. // gets serialized into the session and there may be subtle differences
  72. // between the user returned by Mongoose vs mongodb (such as default values)
  73. User.findOne(query, (error, user) => {
  74. if (error) {
  75. return callback(error)
  76. }
  77. if (!user || !user.hashedPassword) {
  78. return callback(null, null, null)
  79. }
  80. let rounds = 0
  81. try {
  82. rounds = bcrypt.getRounds(user.hashedPassword)
  83. } catch (err) {
  84. let prefix, suffix, length
  85. if (typeof user.hashedPassword === 'string') {
  86. length = user.hashedPassword.length
  87. if (user.hashedPassword.length > 50) {
  88. // A full bcrypt hash is 60 characters long.
  89. prefix = user.hashedPassword.slice(0, '$2a$12$x'.length)
  90. suffix = user.hashedPassword.slice(-4)
  91. } else if (user.hashedPassword.length > 20) {
  92. prefix = user.hashedPassword.slice(0, 4)
  93. suffix = user.hashedPassword.slice(-4)
  94. } else {
  95. prefix = user.hashedPassword.slice(0, 4)
  96. }
  97. }
  98. logger.warn(
  99. {
  100. err,
  101. userId: user._id,
  102. hashedPassword: {
  103. type: typeof user.hashedPassword,
  104. length,
  105. prefix,
  106. suffix,
  107. },
  108. },
  109. 'unexpected user.hashedPassword value'
  110. )
  111. }
  112. Metrics.inc('bcrypt', 1, {
  113. method: 'compare',
  114. path: rounds,
  115. })
  116. bcrypt.compare(password, user.hashedPassword, function (error, match) {
  117. if (error) {
  118. return callback(error)
  119. }
  120. if (match) {
  121. _metricsForSuccessfulPasswordMatch(password)
  122. }
  123. callback(null, user, match)
  124. })
  125. })
  126. },
  127. authenticate(query, password, auditLog, callback) {
  128. if (typeof callback === 'undefined') {
  129. callback = auditLog
  130. auditLog = null
  131. }
  132. AuthenticationManager._checkUserPassword(
  133. query,
  134. password,
  135. (error, user, match) => {
  136. if (error) {
  137. return callback(error)
  138. }
  139. if (!user) {
  140. return callback(null, null)
  141. }
  142. const update = { $inc: { loginEpoch: 1 } }
  143. if (!match) {
  144. update.$set = { lastFailedLogin: new Date() }
  145. }
  146. User.updateOne(
  147. { _id: user._id, loginEpoch: user.loginEpoch },
  148. update,
  149. {},
  150. (err, result) => {
  151. if (err) {
  152. return callback(err)
  153. }
  154. if (result.modifiedCount !== 1) {
  155. return callback(new ParallelLoginError())
  156. }
  157. if (!match) {
  158. if (!auditLog) {
  159. return callback(null, null)
  160. } else {
  161. return UserAuditLogHandler.addEntry(
  162. user._id,
  163. 'failed-password-match',
  164. user._id,
  165. auditLog.ipAddress,
  166. auditLog.info,
  167. err => {
  168. if (err) {
  169. logger.error(
  170. { userId: user._id, err, info: auditLog.info },
  171. 'Error while adding AuditLog entry for failed-password-match'
  172. )
  173. }
  174. callback(null, null)
  175. }
  176. )
  177. }
  178. }
  179. AuthenticationManager.checkRounds(
  180. user,
  181. user.hashedPassword,
  182. password,
  183. function (err) {
  184. if (err) {
  185. return callback(err)
  186. }
  187. callback(null, user)
  188. }
  189. )
  190. }
  191. )
  192. }
  193. )
  194. },
  195. validateEmail(email) {
  196. const parsed = EmailHelper.parseEmail(email)
  197. if (!parsed) {
  198. return new InvalidEmailError({ message: 'email not valid' })
  199. }
  200. return null
  201. },
  202. // validates a password based on a similar set of rules previously used by `passfield.js` on the frontend
  203. // note that `passfield.js` enforced more rules than this, but these are the most commonly set.
  204. // returns null on success, or an error object.
  205. validatePassword(password, email) {
  206. if (password == null) {
  207. return new InvalidPasswordError({
  208. message: 'password not set',
  209. info: { code: 'not_set' },
  210. })
  211. }
  212. Metrics.inc('try-validate-password')
  213. let allowAnyChars, min, max
  214. if (Settings.passwordStrengthOptions) {
  215. allowAnyChars = Settings.passwordStrengthOptions.allowAnyChars === true
  216. if (Settings.passwordStrengthOptions.length) {
  217. min = Settings.passwordStrengthOptions.length.min
  218. max = Settings.passwordStrengthOptions.length.max
  219. }
  220. }
  221. allowAnyChars = !!allowAnyChars
  222. min = min || 8
  223. max = max || 72
  224. // we don't support passwords > 72 characters in length, because bcrypt truncates them
  225. if (max > 72) {
  226. max = 72
  227. }
  228. if (password.length < min) {
  229. return new InvalidPasswordError({
  230. message: 'password is too short',
  231. info: { code: 'too_short' },
  232. })
  233. }
  234. if (password.length > max) {
  235. return new InvalidPasswordError({
  236. message: 'password is too long',
  237. info: { code: 'too_long' },
  238. })
  239. }
  240. const passwordLengthError = _validatePasswordNotTooLong(password)
  241. if (passwordLengthError) {
  242. return passwordLengthError
  243. }
  244. if (
  245. !allowAnyChars &&
  246. !AuthenticationManager._passwordCharactersAreValid(password)
  247. ) {
  248. return new InvalidPasswordError({
  249. message: 'password contains an invalid character',
  250. info: { code: 'invalid_character' },
  251. })
  252. }
  253. if (typeof email === 'string' && email !== '') {
  254. const startOfEmail = email.split('@')[0]
  255. if (
  256. password.includes(email) ||
  257. password.includes(startOfEmail) ||
  258. email.includes(password)
  259. ) {
  260. return new InvalidPasswordError({
  261. message: 'password contains part of email address',
  262. info: { code: 'contains_email' },
  263. })
  264. }
  265. try {
  266. const passwordTooSimilarError =
  267. AuthenticationManager._validatePasswordNotTooSimilar(password, email)
  268. if (passwordTooSimilarError) {
  269. Metrics.inc('password-too-similar-to-email')
  270. return new InvalidPasswordError({
  271. message: 'password is too similar to email address',
  272. info: { code: 'too_similar' },
  273. })
  274. }
  275. } catch (error) {
  276. logger.error(
  277. { error },
  278. 'error while checking password similarity to email'
  279. )
  280. }
  281. // TODO: remove this check once the password-too-similar checks are active?
  282. }
  283. return null
  284. },
  285. setUserPassword(user, password, callback) {
  286. AuthenticationManager.setUserPasswordInV2(user, password, callback)
  287. },
  288. checkRounds(user, hashedPassword, password, callback) {
  289. // Temporarily disable this function, TODO: re-enable this
  290. if (Settings.security.disableBcryptRoundsUpgrades) {
  291. Metrics.inc('bcrypt_check_rounds', 1, { status: 'disabled' })
  292. return callback()
  293. }
  294. // check current number of rounds and rehash if necessary
  295. const currentRounds = bcrypt.getRounds(hashedPassword)
  296. if (currentRounds < BCRYPT_ROUNDS) {
  297. Metrics.inc('bcrypt_check_rounds', 1, { status: 'upgrade' })
  298. AuthenticationManager._setUserPasswordInMongo(user, password, callback)
  299. } else {
  300. Metrics.inc('bcrypt_check_rounds', 1, { status: 'success' })
  301. callback()
  302. }
  303. },
  304. hashPassword(password, callback) {
  305. // Double-check the size to avoid truncating in bcrypt.
  306. const error = _validatePasswordNotTooLong(password)
  307. if (error) {
  308. return callback(error)
  309. }
  310. bcrypt.genSalt(BCRYPT_ROUNDS, BCRYPT_MINOR_VERSION, function (error, salt) {
  311. if (error) {
  312. return callback(error)
  313. }
  314. Metrics.inc('bcrypt', 1, {
  315. method: 'hash',
  316. path: BCRYPT_ROUNDS,
  317. })
  318. bcrypt.hash(password, salt, callback)
  319. })
  320. },
  321. setUserPasswordInV2(user, password, callback) {
  322. if (!user || !user.email || !user._id) {
  323. return callback(new Error('invalid user object'))
  324. }
  325. const validationError = this.validatePassword(password, user.email)
  326. if (validationError) {
  327. return callback(validationError)
  328. }
  329. // check if we can log in with this password. In which case we should reject it,
  330. // because it is the same as the existing password.
  331. AuthenticationManager._checkUserPasswordWithOutHIBPCheck(
  332. { _id: user._id },
  333. password,
  334. (err, _user, match) => {
  335. if (err) {
  336. return callback(err)
  337. }
  338. if (match) {
  339. return callback(new PasswordMustBeDifferentError())
  340. }
  341. HaveIBeenPwned.checkPasswordForReuse(
  342. password,
  343. (error, isPasswordReused) => {
  344. if (error) {
  345. logger.err({ error }, 'cannot check password for re-use')
  346. }
  347. if (!error && isPasswordReused) {
  348. return callback(new PasswordReusedError())
  349. }
  350. // password is strong enough or the validation with the service did not happen
  351. this._setUserPasswordInMongo(user, password, callback)
  352. }
  353. )
  354. }
  355. )
  356. },
  357. _setUserPasswordInMongo(user, password, callback) {
  358. this.hashPassword(password, function (error, hash) {
  359. if (error) {
  360. return callback(error)
  361. }
  362. db.users.updateOne(
  363. { _id: new ObjectId(user._id.toString()) },
  364. {
  365. $set: {
  366. hashedPassword: hash,
  367. },
  368. $unset: {
  369. password: true,
  370. },
  371. },
  372. function (updateError, result) {
  373. if (updateError) {
  374. return callback(updateError)
  375. }
  376. _checkWriteResult(result, callback)
  377. }
  378. )
  379. })
  380. },
  381. _passwordCharactersAreValid(password) {
  382. let digits, letters, lettersUp, symbols
  383. if (
  384. Settings.passwordStrengthOptions &&
  385. Settings.passwordStrengthOptions.chars
  386. ) {
  387. digits = Settings.passwordStrengthOptions.chars.digits
  388. letters = Settings.passwordStrengthOptions.chars.letters
  389. lettersUp = Settings.passwordStrengthOptions.chars.letters_up
  390. symbols = Settings.passwordStrengthOptions.chars.symbols
  391. }
  392. digits = digits || '1234567890'
  393. letters = letters || 'abcdefghijklmnopqrstuvwxyz'
  394. lettersUp = lettersUp || 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
  395. symbols = symbols || '@#$%^&*()-_=+[]{};:<>/?!£€.,'
  396. for (let charIndex = 0; charIndex <= password.length - 1; charIndex++) {
  397. if (
  398. digits.indexOf(password[charIndex]) === -1 &&
  399. letters.indexOf(password[charIndex]) === -1 &&
  400. lettersUp.indexOf(password[charIndex]) === -1 &&
  401. symbols.indexOf(password[charIndex]) === -1
  402. ) {
  403. return false
  404. }
  405. }
  406. return true
  407. },
  408. /**
  409. * Check if the password is similar to (parts of) the email address.
  410. * For now, this merely sends a metric when the password and
  411. * email address are deemed to be too similar to each other.
  412. * Later we will reject passwords that fail this check.
  413. *
  414. * This logic was borrowed from the django project:
  415. * https://github.com/django/django/blob/fa3afc5d86f1f040922cca2029d6a34301597a70/django/contrib/auth/password_validation.py#L159-L214
  416. */
  417. _validatePasswordNotTooSimilar(password, email) {
  418. password = password.toLowerCase()
  419. email = email.toLowerCase()
  420. const stringsToCheck = [email]
  421. .concat(email.split(/\W+/))
  422. .concat(email.split(/@/))
  423. for (const emailPart of stringsToCheck) {
  424. if (!_exceedsMaximumLengthRatio(password, MAX_SIMILARITY, emailPart)) {
  425. const similarity = DiffHelper.stringSimilarity(password, emailPart)
  426. if (similarity > MAX_SIMILARITY) {
  427. logger.warn(
  428. { email, emailPart, similarity, maxSimilarity: MAX_SIMILARITY },
  429. 'Password too similar to email'
  430. )
  431. return new Error('password is too similar to email')
  432. }
  433. }
  434. }
  435. },
  436. getMessageForInvalidPasswordError(error, req) {
  437. const errorCode = error?.info?.code
  438. const message = {
  439. type: 'error',
  440. }
  441. switch (errorCode) {
  442. case 'not_set':
  443. message.key = 'password-not-set'
  444. message.text = req.i18n.translate('invalid_password_not_set')
  445. break
  446. case 'invalid_character':
  447. message.key = 'password-invalid-character'
  448. message.text = req.i18n.translate('invalid_password_invalid_character')
  449. break
  450. case 'contains_email':
  451. message.key = 'password-contains-email'
  452. message.text = req.i18n.translate('invalid_password_contains_email')
  453. break
  454. case 'too_similar':
  455. message.key = 'password-too-similar'
  456. message.text = req.i18n.translate('invalid_password_too_similar')
  457. break
  458. case 'too_short':
  459. message.key = 'password-too-short'
  460. message.text = req.i18n.translate('invalid_password_too_short', {
  461. minLength: Settings.passwordStrengthOptions?.length?.min || 8,
  462. })
  463. break
  464. case 'too_long':
  465. message.key = 'password-too-long'
  466. message.text = req.i18n.translate('invalid_password_too_long', {
  467. maxLength: Settings.passwordStrengthOptions?.length?.max || 72,
  468. })
  469. break
  470. default:
  471. logger.error({ err: error }, 'Unknown password validation error code')
  472. message.text = req.i18n.translate('invalid_password')
  473. break
  474. }
  475. return message
  476. },
  477. }
  478. AuthenticationManager.promises = {
  479. authenticate: util.promisify(AuthenticationManager.authenticate),
  480. hashPassword: util.promisify(AuthenticationManager.hashPassword),
  481. setUserPassword: util.promisify(AuthenticationManager.setUserPassword),
  482. }
  483. module.exports = AuthenticationManager