FormAuth.php 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  1. <?php
  2. declare(strict_types=1);
  3. class FreshRSS_FormAuth {
  4. public const MIN_PASSWORD_LENGTH = 7; // Only to be enforced when setting new passwords.
  5. public const MAX_PASSWORD_LENGTH = 72; // Bcrypt limits password lengths to 72 bytes.
  6. /**
  7. * @param array{enforceMinLength?: bool} $options
  8. */
  9. public static function passwordRequirementsMet(#[\SensitiveParameter] string $passwordPlain, array $options = []): bool {
  10. $enforceMinLength = ($options['enforceMinLength'] ?? true) === true;
  11. if (strlen($passwordPlain) > self::MAX_PASSWORD_LENGTH) {
  12. return false;
  13. }
  14. if ($enforceMinLength && strlen($passwordPlain) < self::MIN_PASSWORD_LENGTH) {
  15. return false;
  16. }
  17. if (trim($passwordPlain) === '') {
  18. return false;
  19. }
  20. return true;
  21. }
  22. public static function checkCredentials(string $username, #[\SensitiveParameter] string $hash, #[\SensitiveParameter] string $passwordPlain): bool {
  23. if (!FreshRSS_user_Controller::checkUsername($username) || !ctype_graph($hash)) {
  24. Minz_Log::debug("Invalid credential parameters: user={$username}");
  25. return false;
  26. }
  27. // Expecting bcrypt format, see: https://en.wikipedia.org/wiki/Bcrypt#Description
  28. // FreshRSS has not historically used any other algorithm for password hash generation,
  29. // so no upgrades are required.
  30. if (!preg_match('/^\$2[aby]\$(0[4-9]|10)\$[.\/0-9A-Za-z]{53}$/', $hash)) {
  31. Minz_Log::debug("Invalid hash format: user={$username}");
  32. return false;
  33. }
  34. $byteLen = strlen($passwordPlain);
  35. $utf8Prefix = mb_check_encoding($passwordPlain, 'UTF-8')
  36. ? mb_strcut($passwordPlain, 0, self::MAX_PASSWORD_LENGTH, 'UTF-8')
  37. : '';
  38. $cutOffUtf8Character = $byteLen > self::MAX_PASSWORD_LENGTH &&
  39. strlen($utf8Prefix) < self::MAX_PASSWORD_LENGTH &&
  40. mb_strlen($passwordPlain, 'UTF-8') === mb_strlen($utf8Prefix, 'UTF-8') + 1;
  41. // Only reject logging in with a password longer than 72 bytes if the limit does not
  42. // cut off a valid UTF-8 character, since this may be an existing bcrypt password.
  43. if (!$cutOffUtf8Character && $byteLen > self::MAX_PASSWORD_LENGTH) {
  44. Minz_Log::warning("Exceeded maximum allowed password length during authentication: user={$username}");
  45. return false;
  46. }
  47. // https://www.php.net/manual/function.password-verify.php
  48. if (password_verify($passwordPlain, $hash)) {
  49. if (trim($passwordPlain) === '') {
  50. Minz_Log::warning("Refusing authentication with empty zero-length password: user={$username}");
  51. return false;
  52. }
  53. return true;
  54. }
  55. return false;
  56. }
  57. /**
  58. * @return array{username: string, password: string}
  59. */
  60. public static function getAutofilledFields(bool $raw = false): array {
  61. $username = Minz_ExtensionManager::callHook(Minz_HookType::AutofillField, 'username');
  62. $password = Minz_ExtensionManager::callHook(Minz_HookType::AutofillField, 'password');
  63. $fields = [
  64. 'username' => is_string($username) ? $username : '',
  65. 'password' => is_string($password) ? $password : '',
  66. ];
  67. if (!$raw) {
  68. foreach ($fields as $k => $v) {
  69. $fields[$k] = htmlspecialchars($v, ENT_COMPAT, 'UTF-8');
  70. }
  71. }
  72. return $fields;
  73. }
  74. /** @return list<string> */
  75. public static function getCredentialsFromCookie(): array {
  76. $token = Minz_Session::getLongTermCookie('FreshRSS_login');
  77. if (!ctype_alnum($token)) {
  78. return [];
  79. }
  80. $token_file = DATA_PATH . '/tokens/' . $token . '.txt';
  81. $mtime = @filemtime($token_file) ?: 0;
  82. $limits = FreshRSS_Context::systemConf()->limits;
  83. $cookie_duration = empty($limits['cookie_duration']) ? FreshRSS_Auth::DEFAULT_COOKIE_DURATION : $limits['cookie_duration'];
  84. if ($mtime + $cookie_duration < time()) {
  85. // Token has expired (> cookie_duration) or does not exist.
  86. @unlink($token_file);
  87. return [];
  88. }
  89. $credentials = @file_get_contents($token_file);
  90. if ($credentials !== false && self::renewCookie($token) != false) {
  91. return explode("\t", $credentials, 2);
  92. }
  93. return [];
  94. }
  95. private static function renewCookie(string $token): string|false {
  96. $token_file = DATA_PATH . '/tokens/' . $token . '.txt';
  97. if (touch($token_file)) {
  98. $limits = FreshRSS_Context::systemConf()->limits;
  99. $cookie_duration = empty($limits['cookie_duration']) ? FreshRSS_Auth::DEFAULT_COOKIE_DURATION : $limits['cookie_duration'];
  100. $expire = time() + $cookie_duration;
  101. Minz_Session::setLongTermCookie('FreshRSS_login', $token, $expire);
  102. return $token;
  103. }
  104. return false;
  105. }
  106. public static function makeCookie(string $username, #[\SensitiveParameter] string $password_hash): string|false {
  107. do {
  108. $token = hash('sha256', FreshRSS_Context::systemConf()->salt . $username . random_bytes(32));
  109. $token_file = DATA_PATH . '/tokens/' . $token . '.txt';
  110. } while (file_exists($token_file));
  111. if (@file_put_contents($token_file, $username . "\t" . $password_hash) === false) {
  112. return false;
  113. }
  114. return self::renewCookie($token);
  115. }
  116. public static function deleteCookie(): void {
  117. $token = Minz_Session::getLongTermCookie('FreshRSS_login');
  118. if (ctype_alnum($token)) {
  119. Minz_Session::deleteLongTermCookie('FreshRSS_login');
  120. @unlink(DATA_PATH . '/tokens/' . $token . '.txt');
  121. }
  122. if (rand(0, 10) === 1) {
  123. self::purgeTokens();
  124. }
  125. }
  126. public static function purgeTokens(): void {
  127. $limits = FreshRSS_Context::systemConf()->limits;
  128. $cookie_duration = empty($limits['cookie_duration']) ? FreshRSS_Auth::DEFAULT_COOKIE_DURATION : $limits['cookie_duration'];
  129. $oldest = time() - $cookie_duration;
  130. foreach (new DirectoryIterator(DATA_PATH . '/tokens/') as $file_info) {
  131. $extension = $file_info->getExtension();
  132. if ($extension === 'txt' && $file_info->getMTime() < $oldest) {
  133. @unlink($file_info->getPathname());
  134. }
  135. }
  136. }
  137. }