AuthenticationManager.js 15 KB

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