AuthenticationManager.mjs 15 KB

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