authController.php 11 KB

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