Explorar el Código

Fix wrong status code on failed login (#9566)

Regression from https://github.com/FreshRSS/FreshRSS/pull/9358 (PR not present in current release, stopped sending 403 on failed logins).

This PR fixes the Minz bug mentioned in https://github.com/FreshRSS/FreshRSS/pull/9358#discussion_r4382254359 which occurred with `redirect: false` redirects.

But it also takes a different approach for redirecting, by using HTML instead of the `Location` header (to address one additional issue with a resubmit prompt appearing when refreshing the login page after a failed login).

403 is now returned during failed reauthentication as well.
Inverle hace 2 horas
padre
commit
06c0329de2

+ 30 - 13
app/Controllers/authController.php

@@ -90,6 +90,28 @@ class FreshRSS_auth_Controller extends FreshRSS_ActionController {
 		};
 	}
 
+	/**
+	 * Redirect back to the login form, while replying to the login request with an HTTP error status code (403, 500),
+	 * e.g. for fail2ban, which a normal HTTP redirection (3xx) cannot do.
+	 * The HTML redirection (POST->GET) also prevents browsers from offering to resubmit the password when reloading the page.
+	 */
+	private static function loginFailed(int $httpCode, string $notification): void {
+		$redirect = [
+			'c' => 'auth',
+			'a' => 'login',
+			'params' => ['original_request' => Minz_Request::paramString('original_request')],
+		];
+		if (Minz_Request::is('auth', 'reauth')) {
+			$redirect = [
+				'c' => 'auth',
+				'a' => 'reauth',
+				'params' => ['r' => Minz_Request::paramString('original_request')],
+			];
+		}
+		Minz_Request::setBadNotification($notification);
+		Minz_Request::forward($redirect, redirect: true, httpCode: $httpCode);
+	}
+
 	/**
 	 * This action handles form login page.
 	 *
@@ -120,9 +142,7 @@ class FreshRSS_auth_Controller extends FreshRSS_ActionController {
 
 			if (!Minz_Session::paramBoolean('sessionOk')) {
 				Minz_Log::warning("Invalid session during login for user={$username}, ip_address={$ip_address}");
-				header('HTTP/1.1 403 Forbidden');
-				Minz_Request::setBadNotification(_t('install.session.nok'));
-				Minz_Request::forward(['c' => 'auth', 'a' => 'login'], redirect: true);
+				self::loginFailed(403, _t('install.session.nok'));
 				return;
 			}
 
@@ -150,9 +170,7 @@ class FreshRSS_auth_Controller extends FreshRSS_ActionController {
 					Minz_Session::regenerateID('FreshRSS');
 				} catch (RuntimeException $e) {
 					Minz_Log::error("Session could not be regenerated during login for user={$username}, ip_address={$ip_address}: {$e->getMessage()}");
-					header('HTTP/1.1 500 Internal Server Error');
-					Minz_Request::setBadNotification(_t('install.session.nok'));
-					Minz_Request::forward(['c' => 'auth', 'a' => 'login'], redirect: true);
+					self::loginFailed(500, _t('install.session.nok'));
 					return;
 				}
 				// Set session parameters to give access to the user.
@@ -186,9 +204,7 @@ class FreshRSS_auth_Controller extends FreshRSS_ActionController {
 				);
 			} else {
 				Minz_Log::warning("Password mismatch for user={$username}, ip_address={$ip_address}");
-				header('HTTP/1.1 403 Forbidden');
-				Minz_Request::setBadNotification(_t('feedback.auth.login.invalid'));
-				Minz_Request::forward(['c' => 'auth', 'a' => 'login'], redirect: true);
+				self::loginFailed(403, _t('feedback.auth.login.invalid'));
 			}
 		} else {
 			Minz_Session::deleteLegacyCookie('FreshRSS');	// Delete legacy cookie (before 1.29.0)
@@ -213,18 +229,19 @@ class FreshRSS_auth_Controller extends FreshRSS_ActionController {
 			if (!FreshRSS_FormAuth::checkCredentials(
 				$username, FreshRSS_Context::userConf()->passwordHash, $passwordPlain
 			)) {
-				Minz_Request::setBadNotification(_t('feedback.auth.login.invalid'));
+				self::loginFailed(403, _t('feedback.auth.login.invalid'));
+				return;
 			} else {
 				try {
 					Minz_Session::regenerateID('FreshRSS');
 					Minz_Session::_param('lastReauth', time());
-					Minz_Request::forward($redirect, true);
+					Minz_Request::forward($redirect, redirect: true);
 					return;
 				} catch (RuntimeException $e) {
 					Minz_Log::error("Session could not be regenerated during reauthentication! {$e->getMessage()}");
 					Minz_Session::_param('lastReauth', 0);
-					header('HTTP/1.1 500 Internal Server Error');
-					Minz_Request::setBadNotification(_t('install.session.nok'));
+					self::loginFailed(500, _t('install.session.nok'));
+					return;
 				}
 			}
 		}

+ 1 - 1
app/views/auth/formLogin.phtml

@@ -20,7 +20,7 @@
 
 	<form method="post" action="<?= _url('auth', 'login') ?>">
 		<input type="hidden" name="_csrf" value="<?= FreshRSS_Auth::csrfToken() ?>" />
-		<input type="hidden" name="original_request" value="<?= Minz_Url::serialize(Minz_Request::originalRequest())?>" />
+		<input type="hidden" name="original_request" value="<?= Minz_Request::paramString('original_request') ?: Minz_Url::serialize(Minz_Request::originalRequest()) ?>" />
 
 		<div class="form-group">
 			<label for="username"><?= _t('gen.auth.username') ?></label>

+ 1 - 0
app/views/auth/reauth.phtml

@@ -8,6 +8,7 @@
 
 	<form method="post">
 		<input type="hidden" name="_csrf" value="<?= FreshRSS_Auth::csrfToken() ?>" />
+		<input type="hidden" name="original_request" value="<?= Minz_Request::paramString('r') ?>" />
 		<input type="hidden" id="username" value="<?= Minz_User::name() ?>" />
 		<div class="form-group">
 			<label for="passwordPlain"><?= _t('gen.auth.password') ?></label>

+ 7 - 6
lib/Minz/FrontController.php

@@ -41,12 +41,13 @@ class Minz_FrontController {
 
 			// Build the current request's URL and forward to it directly.
 			// If needed, a redirect is issued instead to correct the public relative path.
-			$url = Minz_Url::build();
-			$url['params'] = array_merge(
-				empty($url['params']) || !is_array($url['params']) ? [] : $url['params'],
-				array_filter($_POST, 'is_string', ARRAY_FILTER_USE_KEY)
-			);
-			Minz_Request::forward($url, redirect: Minz_Request::pathInfo() !== '');
+			// Only GET parameters are part of the URL, and hence of the original request or of a redirect.
+			Minz_Request::forward(Minz_Url::build(), redirect: Minz_Request::pathInfo() !== '');
+
+			// POST parameters (which may contain passwords) are added afterwards so that they never end up in a URL.
+			$post = array_filter($_POST, 'is_string', ARRAY_FILTER_USE_KEY);
+			unset($post['rid']);	// Request ID is only taken from GET
+			Minz_Request::_params(array_merge(Minz_Request::params(), $post));
 		} catch (Minz_Exception $e) {
 			Minz_Log::error($e->getMessage());
 			self::killApp($e->getMessage());

+ 36 - 2
lib/Minz/Request.php

@@ -518,9 +518,11 @@ class Minz_Request {
 	 * Restart a request
 	 * @param array{c?:string,a?:string,params?:array<string,mixed>} $url an array presentation of the URL to route to
 	 * @param bool $redirect If true, uses an HTTP redirection, and if false (default), performs an internal dispatcher redirection.
+	 * @param int $httpCode Only for a redirection: an HTTP error status code (4xx, 5xx) to send instead of a 3xx redirection.
+	 * 	Since browsers do not follow the `Location` header of such a response, an HTML redirection (with JS or `<meta http-equiv="refresh">`) is used instead.
 	 * @throws Minz_ConfigurationException
 	 */
-	public static function forward(array $url = [], bool $redirect = false): void {
+	public static function forward(array $url = [], bool $redirect = false, int $httpCode = 0): void {
 		if (empty(Minz_Request::originalRequest())) {
 			self::$originalRequest = $url;
 		}
@@ -529,7 +531,39 @@ class Minz_Request {
 		$url['params']['rid'] = self::requestId();
 
 		if ($redirect) {
-			header('Location: ' . Minz_Url::display($url, 'php', 'root'));
+			$location = Minz_Url::display($url, 'php', 'root'); // `/i/...`
+			if ($httpCode >= 400 && $httpCode <= 599) {
+				$nonce = bin2hex(random_bytes(16));
+
+				http_response_code($httpCode);
+				header('Content-Type: text/html; charset=UTF-8');
+				header("Content-Security-Policy: default-src 'none'; frame-ancestors 'none'; script-src 'nonce-$nonce'");
+				header('X-Content-Type-Options: nosniff');
+				$location = htmlspecialchars($location, ENT_QUOTES, 'UTF-8');
+
+				// JavaScript helps prevent the redirect page from flashing.
+				// See: https://developer.mozilla.org/en-US/docs/Web/HTML/Reference/Elements/script#blocking
+				echo <<<HTML
+				<!DOCTYPE html>
+				<html>
+				<head>
+					<meta charset="UTF-8">
+					<meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
+					<meta name="color-scheme" content="light dark">
+					<meta http-equiv="refresh" content="0; url=$location">
+					<script nonce="$nonce" blocking="render" data-target="$location">
+						location.replace(document.currentScript.dataset.target);
+					</script>
+					<title>$httpCode</title>
+				</head>
+				<body>
+					<p>Redirecting.</p>
+				</body>
+				</html>
+				HTML;
+			} else {
+				header('Location: ' . $location);
+			}
 			exit();
 		} else {
 			self::_controllerName($url['c']);