authController.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * This controller handles action about authentication.
  5. */
  6. class FreshRSS_auth_Controller extends FreshRSS_ActionController {
  7. /**
  8. * This action handles authentication management page.
  9. *
  10. * Parameters are:
  11. * - token (default: current token)
  12. * - anon_access (default: false)
  13. * - anon_refresh (default: false)
  14. * - auth_type (default: none)
  15. * - api_enabled (default: false)
  16. */
  17. public function indexAction(): void {
  18. if (!FreshRSS_Auth::hasAccess('admin')) {
  19. Minz_Error::error(403);
  20. }
  21. if (FreshRSS_Auth::requestReauth()) {
  22. return;
  23. }
  24. FreshRSS_View::prependTitle(_t('admin.auth.title') . ' · ');
  25. if (Minz_Request::isPost()) {
  26. $ok = true;
  27. $anon = Minz_Request::paramBoolean('anon_access');
  28. $anon_refresh = Minz_Request::paramBoolean('anon_refresh');
  29. $auth_type = Minz_Request::paramString('auth_type') ?: 'form';
  30. $api_enabled = Minz_Request::paramBoolean('api_enabled');
  31. if ($anon !== FreshRSS_Context::systemConf()->allow_anonymous ||
  32. $auth_type !== FreshRSS_Context::systemConf()->auth_type ||
  33. $anon_refresh !== FreshRSS_Context::systemConf()->allow_anonymous_refresh ||
  34. $api_enabled !== FreshRSS_Context::systemConf()->api_enabled) {
  35. if (in_array($auth_type, ['form', 'http_auth', 'none'], true)) {
  36. FreshRSS_Context::systemConf()->auth_type = $auth_type;
  37. } else {
  38. FreshRSS_Context::systemConf()->auth_type = 'form';
  39. }
  40. FreshRSS_Context::systemConf()->allow_anonymous = $anon;
  41. FreshRSS_Context::systemConf()->allow_anonymous_refresh = $anon_refresh;
  42. FreshRSS_Context::systemConf()->api_enabled = $api_enabled;
  43. $ok &= FreshRSS_Context::systemConf()->save();
  44. }
  45. invalidateHttpCache();
  46. if ($ok) {
  47. Minz_Request::good(
  48. _t('feedback.conf.updated'),
  49. [ 'c' => 'auth', 'a' => 'index' ],
  50. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  51. );
  52. } else {
  53. Minz_Request::bad(_t('feedback.conf.error'), [ 'c' => 'auth', 'a' => 'index' ]);
  54. }
  55. }
  56. }
  57. /**
  58. * This action handles the login page.
  59. *
  60. * It forwards to the correct login page (form) or main page if
  61. * the user is already connected.
  62. */
  63. public function loginAction(): void {
  64. if (FreshRSS_Auth::hasAccess()) {
  65. Minz_Request::forward(['c' => 'index', 'a' => 'index'], true);
  66. return;
  67. }
  68. $auth_type = FreshRSS_Context::systemConf()->auth_type;
  69. FreshRSS_Context::initUser(Minz_User::INTERNAL_USER, false);
  70. match ($auth_type) {
  71. 'form' => Minz_Request::forward(['c' => 'auth', 'a' => 'formLogin']),
  72. 'http_auth' => Minz_Error::error(403, [
  73. 'error' => [
  74. _t('feedback.access.denied'),
  75. ' [HTTP Remote-User=' . htmlspecialchars(FreshRSS_http_Util::httpAuthUser(onlyTrusted: false), ENT_NOQUOTES, 'UTF-8') .
  76. ' ; Remote IP address=' . Minz_Request::connectionRemoteAddress() . ']'
  77. ]
  78. ], false),
  79. 'none' => Minz_Error::error(404), // It should not happen!
  80. default => Minz_Error::error(404), // TODO load plugin instead
  81. };
  82. }
  83. /**
  84. * Redirect back to the login form, while replying to the login request with an HTTP error status code (403, 500),
  85. * e.g. for fail2ban, which a normal HTTP redirection (3xx) cannot do.
  86. * The HTML redirection (POST->GET) also prevents browsers from offering to resubmit the password when reloading the page.
  87. */
  88. private static function loginFailed(int $httpCode, string $notification): void {
  89. $redirect = [
  90. 'c' => 'auth',
  91. 'a' => 'login',
  92. 'params' => ['original_request' => Minz_Request::paramString('original_request')],
  93. ];
  94. if (Minz_Request::is('auth', 'reauth')) {
  95. $redirect = [
  96. 'c' => 'auth',
  97. 'a' => 'reauth',
  98. 'params' => ['r' => Minz_Request::paramString('original_request')],
  99. ];
  100. }
  101. Minz_Request::setBadNotification($notification);
  102. Minz_Request::forward($redirect, redirect: true, httpCode: $httpCode);
  103. }
  104. /**
  105. * This action handles form login page.
  106. *
  107. * If this action is reached through a POST request, username and password
  108. * are compared against the bcrypt password hash stored in the user configuration file
  109. * to authenticate the current user.
  110. *
  111. * Parameters are:
  112. * - username (default: '')
  113. * - passwordPlain (default: '')
  114. * - keep_logged_in (default: false)
  115. *
  116. * @throws Exception
  117. */
  118. public function formLoginAction(): void {
  119. if (FreshRSS_Auth::hasAccess()) {
  120. Minz_Request::forward(['c' => 'index', 'a' => 'index'], true);
  121. return;
  122. }
  123. invalidateHttpCache();
  124. FreshRSS_View::prependTitle(_t('gen.auth.login') . ' · ');
  125. $this->view->auth_autofills = FreshRSS_FormAuth::getAutofilledFields();
  126. $limits = FreshRSS_Context::systemConf()->limits;
  127. $this->view->cookie_days = (int)round($limits['cookie_duration'] / 86400, 1);
  128. if (Minz_Request::isPost()) {
  129. $username = Minz_Request::paramString('username');
  130. $passwordPlain = Minz_Request::paramString('passwordPlain', plaintext: true, trim: false);
  131. $ip_address = Minz_Request::connectionRemoteAddress();
  132. if (!Minz_Session::paramBoolean('sessionOk')) {
  133. Minz_Log::warning("Invalid session during login for user={$username}, ip_address={$ip_address}");
  134. self::loginFailed(403, _t('install.session.nok'));
  135. return;
  136. }
  137. usleep(random_int(100, 10000)); // Primitive mitigation of timing attacks, in μs
  138. FreshRSS_Context::initUser($username);
  139. if (!FreshRSS_Context::hasUserConf()) {
  140. self::loginFailed(403, _t('feedback.auth.login.invalid'));
  141. return;
  142. }
  143. if (!FreshRSS_Context::userConf()->enabled || FreshRSS_Context::userConf()->passwordHash == '') {
  144. usleep(random_int(100, 5000)); // Primitive mitigation of timing attacks, in μs
  145. self::loginFailed(403, _t('feedback.auth.login.invalid'));
  146. return;
  147. }
  148. $ok = FreshRSS_FormAuth::checkCredentials(
  149. $username, FreshRSS_Context::userConf()->passwordHash, $passwordPlain
  150. );
  151. if ($ok) {
  152. try {
  153. Minz_Session::regenerateID('FreshRSS');
  154. } catch (RuntimeException $e) {
  155. Minz_Log::error("Session could not be regenerated during login for user={$username}, ip_address={$ip_address}: {$e->getMessage()}");
  156. self::loginFailed(500, _t('install.session.nok'));
  157. return;
  158. }
  159. // Set session parameters to give access to the user.
  160. Minz_Session::_params([
  161. Minz_User::CURRENT_USER => $username,
  162. 'passwordHash' => FreshRSS_Context::userConf()->passwordHash,
  163. 'csrf' => false,
  164. ]);
  165. FreshRSS_Auth::giveAccess();
  166. // Set cookie parameter if needed.
  167. if (Minz_Request::paramBoolean('keep_logged_in')) {
  168. FreshRSS_FormAuth::makeCookie($username, FreshRSS_Context::userConf()->passwordHash);
  169. } else {
  170. FreshRSS_FormAuth::deleteCookie();
  171. }
  172. Minz_Translate::init(FreshRSS_Context::userConf()->language);
  173. FreshRSS_UserDAO::touch();
  174. // All is good, go back to the original request or the index.
  175. $url = Minz_Url::unserialize(Minz_Request::paramString('original_request'));
  176. if (empty($url)) {
  177. $url = [ 'c' => 'index', 'a' => 'index' ];
  178. }
  179. Minz_Request::good(
  180. _t('feedback.auth.login.success'),
  181. $url,
  182. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  183. );
  184. } else {
  185. Minz_Log::warning("Password mismatch for user={$username}, ip_address={$ip_address}");
  186. self::loginFailed(403, _t('feedback.auth.login.invalid'));
  187. return;
  188. }
  189. } else {
  190. Minz_Session::deleteLegacyCookie('FreshRSS'); // Delete legacy cookie (before 1.29.0)
  191. Minz_Session::_param('sessionOk', true); // To be checked in the POST login request.
  192. }
  193. }
  194. public function reauthAction(): void {
  195. if (!FreshRSS_Auth::hasAccess()) {
  196. Minz_Error::error(403);
  197. return;
  198. }
  199. /** @var array{c?: string, a?: string, params?: array<string, mixed>} $redirect */
  200. $redirect = Minz_Url::unserialize(Minz_Request::paramString('r'));
  201. if (!FreshRSS_Auth::needsReauth()) {
  202. Minz_Request::forward($redirect, true);
  203. return;
  204. }
  205. if (Minz_Request::isPost()) {
  206. $username = Minz_User::name() ?? '';
  207. $passwordPlain = Minz_Request::paramString('passwordPlain', plaintext: true, trim: false);
  208. if (!FreshRSS_FormAuth::checkCredentials(
  209. $username, FreshRSS_Context::userConf()->passwordHash, $passwordPlain
  210. )) {
  211. self::loginFailed(403, _t('feedback.auth.login.invalid'));
  212. return;
  213. } else {
  214. try {
  215. Minz_Session::regenerateID('FreshRSS');
  216. Minz_Session::_param('lastReauth', time());
  217. Minz_Request::forward($redirect, redirect: true);
  218. return;
  219. } catch (RuntimeException $e) {
  220. Minz_Log::error("Session could not be regenerated during reauthentication! {$e->getMessage()}");
  221. Minz_Session::_param('lastReauth', 0);
  222. self::loginFailed(500, _t('install.session.nok'));
  223. return;
  224. }
  225. }
  226. }
  227. FreshRSS_View::prependTitle(_t('gen.auth.reauth.title') . ' · ');
  228. $this->view->auth_autofills = FreshRSS_FormAuth::getAutofilledFields();
  229. }
  230. /**
  231. * This action removes all accesses of the current user.
  232. */
  233. public function logoutAction(): void {
  234. if (Minz_Request::isPost()) {
  235. invalidateHttpCache();
  236. FreshRSS_Auth::removeAccess();
  237. Minz_Session::_param('csrf', false);
  238. try {
  239. Minz_Session::regenerateID('FreshRSS');
  240. } catch (RuntimeException $e) {
  241. Minz_Log::error('Session could not be regenerated during logout! ' . $e->getMessage());
  242. }
  243. Minz_Request::good(
  244. _t('feedback.auth.logout.success'),
  245. [ 'c' => 'index', 'a' => 'index' ],
  246. showNotification: FreshRSS_Context::userConf()->good_notification_timeout > 0
  247. );
  248. } else {
  249. Minz_Error::error(403);
  250. }
  251. }
  252. /**
  253. * This action gives possibility to a user to create an account.
  254. *
  255. * The user is redirected to the home when logged in.
  256. *
  257. * A 403 is sent if max number of registrations is reached.
  258. */
  259. public function registerAction(): void {
  260. if (FreshRSS_Auth::hasAccess()) {
  261. Minz_Request::forward(['c' => 'index', 'a' => 'index'], true);
  262. }
  263. if (FreshRSS_user_Controller::max_registrations_reached()) {
  264. Minz_Error::error(403);
  265. }
  266. $this->view->show_tos_checkbox = file_exists(TOS_FILENAME);
  267. $this->view->show_email_field = FreshRSS_Context::systemConf()->force_email_validation;
  268. $this->view->preferred_language = Minz_Translate::getLanguage(null, Minz_Request::getPreferredLanguages(), FreshRSS_Context::systemConf()->language);
  269. $this->view->auth_autofills = FreshRSS_FormAuth::getAutofilledFields();
  270. FreshRSS_View::prependTitle(_t('gen.auth.registration.title') . ' · ');
  271. }
  272. public static function getLogoutUrl(): string {
  273. if (($_SERVER['AUTH_TYPE'] ?? '') === 'openid-connect') {
  274. $url_string = urlencode(Minz_Request::guessBaseUrl());
  275. return './oidc/?logout=' . $url_string . '/';
  276. # The trailing slash is necessary so that we don’t redirect to http://.
  277. # https://bz.apache.org/bugzilla/show_bug.cgi?id=61355#c13
  278. } else {
  279. return _url('auth', 'logout');
  280. }
  281. }
  282. }