A free open source IT asset/license management system
Patched a few more redirects with sameOriginUrl()
snipe04cf64818b1f
diff --git a/app/Exceptions/Handler.php b/app/Exceptions/Handler.phpindex fb8fea60b1..ea9ba44af6 100644--- a/app/Exceptions/Handler.php+++ b/app/Exceptions/Handler.php@@ -112,7 +112,13 @@ class Handler extends ExceptionHandler// CSRF token mismatch errorif ($e instanceof TokenMismatchException) {- return redirect()->back()->with('error', trans('general.token_expired'));+ // Any form POST can hit this branch, including pre-auth+ // forms (login, password reset, setup wizard). Routing the+ // fallback through sameOriginUrl prevents a crafted link+ // that pairs an off-origin Referer with an expired token+ // from steering the response Location off-site.+ return redirect()->to(Helper::sameOriginUrl(url()->previous()) ?? route('home'))+ ->with('error', trans('general.token_expired'));}// Invalid JSON exception@@ -134,7 +140,9 @@ class Handler extends ExceptionHandler// Handle standard requests that fail because Carbon cannot parse the date on validation (when a submitted date value is definitely not a date)if ($e instanceof InvalidFormatException) {- return redirect()->back()->withInput()->with('error', trans('validation.date', ['attribute' => 'date']));+ // Same open-redirect guard as the TokenMismatch branch above.+ return redirect()->to(Helper::sameOriginUrl(url()->previous()) ?? route('home'))+ ->withInput()->with('error', trans('validation.date', ['attribute' => 'date']));}// Handle API requests that faildiff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.phpindex ed180b0580..b1a94cde74 100644--- a/app/Http/Controllers/Auth/LoginController.php+++ b/app/Http/Controllers/Auth/LoginController.php@@ -525,7 +525,14 @@ class LoginController extends Controllerif ($saml->isEnabled()) {$auth = $saml->getAuth();- $sloRedirectUrl = $request->session()->get('saml_slo_redirect_url');+ // Defense-in-depth: SamlController::sls sanitizes the SLO+ // RelayState through sameOriginUrl at write time, but any+ // future writer that skips that gate (or any parser-+ // differential bypass of sameOriginUrl at write time) would+ // leave the away() emission below unprotected. Re-check at+ // read time so the Location header never carries an off-+ // origin URL that reached session('saml_slo_redirect_url').+ $sloRedirectUrl = Helper::sameOriginUrl($request->session()->get('saml_slo_redirect_url'));if (! empty($auth->getSLOurl()) && $settings->saml_slo == '1' && $saml->isAuthenticated() && empty($sloRedirectUrl)) {$sloRequestUrl = $auth->logout(null, [], $saml->getNameId(), $saml->getSessionIndex(), true, $saml->getNameIdFormat(), $saml->getNameIdNameQualifier(), $saml->getNameIdSPNameQualifier());diff --git a/app/Http/Controllers/Auth/ResetPasswordController.php b/app/Http/Controllers/Auth/ResetPasswordController.phpindex 3ba06090b7..997bacedac 100644--- a/app/Http/Controllers/Auth/ResetPasswordController.php+++ b/app/Http/Controllers/Auth/ResetPasswordController.php@@ -2,6 +2,7 @@namespace App\Http\Controllers\Auth;+use App\Helpers\Helper;use App\Http\Controllers\Controller;use App\Models\Setting;use App\Models\User;@@ -128,7 +129,8 @@ class ResetPasswordController extends ControllerLog::debug('Password reset for '.$user->username.' FAILED - this user exists but the token is not valid');- return redirect()->back()->withInput($request->only('email'))->with('success', trans('passwords.reset'));+ return redirect()->to(Helper::sameOriginUrl(url()->previous()) ?? route('login'))+ ->withInput($request->only('email'))->with('success', trans('passwords.reset'));}}diff --git a/app/Http/Controllers/Auth/SamlController.php b/app/Http/Controllers/Auth/SamlController.phpindex ccc24a5c42..6f9c8afbd1 100644--- a/app/Http/Controllers/Auth/SamlController.php+++ b/app/Http/Controllers/Auth/SamlController.php@@ -163,6 +163,18 @@ class SamlController extends Controllerreturn view('errors.403');}- return redirect()->route('logout.get')->with(['saml_logout' => true, 'saml_slo_redirect_url' => $sloUrl]);+ // SLO RelayState sanitize. $sloUrl is whatever onelogin/saml2's+ // processSLO returned as the RelayState from the IdP's+ // LogoutResponse. In the legitimate flow Snipe-IT sets its own+ // RelayState at SLO initiation, so the value here is same-origin.+ // A hostile IdP (or an IdP that reflects an attacker-chosen+ // RelayState) can inject an external URL that LoginController's+ // SLO-response branch would later feed to redirect()->away().+ // Sanitize at the write path, mirror of the ACS RelayState guard+ // closed under GHSA-579m-9gf4-28jp. Null survives as null and the+ // read side falls back to the usual logout destination.+ $safeSloUrl = Helper::sameOriginUrl($sloUrl);++ return redirect()->route('logout.get')->with(['saml_logout' => true, 'saml_slo_redirect_url' => $safeSloUrl]);}}diff --git a/app/Http/Controllers/SetupController.php b/app/Http/Controllers/SetupController.phpindex 2b49fa9441..b4355fee0b 100644--- a/app/Http/Controllers/SetupController.php+++ b/app/Http/Controllers/SetupController.php@@ -2,6 +2,7 @@namespace App\Http\Controllers;+use App\Helpers\Helper;use App\Http\Requests\SetupUserRequest;use App\Models\Setting;use App\Models\User;@@ -187,7 +188,8 @@ class SetupController extends Controller$settings->zerofill_count = $request->input('zerofill_count') ?: 0;if ((! $user->isValid()) || (! $settings->isValid())) {- return redirect()->back()->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors());+ return redirect()->to(Helper::sameOriginUrl(url()->previous()) ?? route('setup.user'))+ ->withInput()->withErrors($user->getErrors())->withErrors($settings->getErrors());} else {$user->save();Auth::login($user, true);diff --git a/tests/Feature/Authentication/OpenRedirectGuardsTest.php b/tests/Feature/Authentication/OpenRedirectGuardsTest.phpnew file mode 100644index 0000000000..df8a122916--- /dev/null+++ b/tests/Feature/Authentication/OpenRedirectGuardsTest.php@@ -0,0 +1,111 @@+<?php++namespace Tests\Feature\Authentication;++use App\Exceptions\Handler;+use App\Models\User;+use Carbon\Exceptions\InvalidFormatException;+use Illuminate\Http\Request;+use Illuminate\Session\TokenMismatchException;+use Illuminate\Support\Facades\Cache;+use Tests\TestCase;++/**+ * Pre-auth failure-path open-redirect guards. Four form-POST sinks+ * previously called redirect()->back() with no host validation. All now+ * route url()->previous() through Helper::sameOriginUrl before falling+ * back to a route-named default. A crafted link that paired an off-origin+ * Referer with a form failure (CSRF mismatch, bad date, bad reset token,+ * setup-wizard validation failure) could otherwise steer the 302 Location+ * off-site for a phishing hand-off.+ *+ * The two exception-handler branches (TokenMismatch and InvalidFormat)+ * can't be exercised at the HTTP layer in Laravel's default test env+ * because CSRF is disabled and the exception won't fire. They're+ * invoked directly via Handler::render() instead so the Referer-driven+ * sanitize is still regression-covered.+ */+class OpenRedirectGuardsTest extends TestCase+{+ protected function setUp(): void+ {+ parent::setUp();++ // ThrottlesLogins shares a RateLimiter cache across tests+ // in-process, so zero it. Otherwise prior failed-login attempts+ // can push this test past the lockout threshold before asserts.+ Cache::flush();+ }++ public function test_token_mismatch_exception_redirect_uses_sameorigin_guard()+ {+ $handler = app(Handler::class);++ $request = $this->bindRequestWithReferer('/login', 'https://evil.example.net/phish');++ $response = $handler->render($request, new TokenMismatchException);++ $this->assertSame(302, $response->getStatusCode());+ $this->assertSame(config('app.url'), rtrim($response->headers->get('Location'), '/'));+ }++ public function test_token_mismatch_exception_redirect_honors_same_origin_referer()+ {+ $handler = app(Handler::class);+ $safeReferer = config('app.url').'/some/path';++ $request = $this->bindRequestWithReferer('/login', $safeReferer);++ $response = $handler->render($request, new TokenMismatchException);++ $this->assertSame(302, $response->getStatusCode());+ $this->assertSame($safeReferer, $response->headers->get('Location'));+ }++ public function test_invalid_date_exception_redirect_uses_sameorigin_guard()+ {+ $handler = app(Handler::class);++ $request = $this->bindRequestWithReferer('/anything', 'https://evil.example.net/phish');++ $response = $handler->render($request, new InvalidFormatException('bogus date'));++ $this->assertSame(302, $response->getStatusCode());+ $this->assertSame(config('app.url'), rtrim($response->headers->get('Location'), '/'));+ }++ /**+ * Construct a POST request with the given Referer and bind it as+ * the container's active request so url()->previous() reads from it.+ * Handler::render() reaches for url()->previous() internally via+ * the global helper, which resolves against the container-bound+ * request rather than any ad-hoc instance.+ */+ private function bindRequestWithReferer(string $path, string $referer): Request+ {+ $request = Request::create(config('app.url').$path, 'POST');+ $request->headers->set('referer', $referer);+ $this->app->instance('request', $request);++ return $request;+ }++ public function test_reset_password_invalid_token_does_not_redirect_to_offsite_referer()+ {+ User::factory()->create(['email' => '[email protected]', 'username' => 'reset-me']);++ // Flipping the password-reset path to the bad-token branch at+ // ResetPasswordController:131 requires a username + email that+ // match a real user, plus a token that doesn't verify.+ $response = $this->from('https://evil.example.net/phish')+ ->post('/password/reset', [+ 'username' => 'reset-me',+ 'email' => '[email protected]',+ 'password' => 'new-password-123',+ 'password_confirmation' => 'new-password-123',+ 'token' => 'this-token-is-invalid',+ ]);++ $this->assertNotSame('https://evil.example.net/phish', $response->headers->get('Location'));+ }+}diff --git a/tests/Feature/Authentication/SamlSloRedirectGuardTest.php b/tests/Feature/Authentication/SamlSloRedirectGuardTest.phpnew file mode 100644index 0000000000..360f8d6520--- /dev/null+++ b/tests/Feature/Authentication/SamlSloRedirectGuardTest.php@@ -0,0 +1,41 @@+<?php++namespace Tests\Feature\Authentication;++use App\Helpers\Helper;+use Tests\TestCase;++/**+ * SAML SLO (single-logout) response path open-redirect guard. When the+ * IdP posts back to /saml/sls, SamlController::sls stashes the RelayState+ * URL as session key saml_slo_redirect_url, and LoginController::logout+ * later emits it via redirect()->away(). Pre-fix a hostile IdP (or an IdP+ * that reflects an attacker-supplied RelayState) could land the SLO+ * response Location on an off-origin host immediately after the victim's+ * logout. Fix sanitizes both at write time (SamlController::sls) and at+ * read time (LoginController::logout) using Helper::sameOriginUrl.+ *+ * Full HTTP-level coverage of the away() emission needs the Saml service+ * enabled (processSLO called on a live SAML config), which is not+ * reachable in default test env. The branch is instead covered via the+ * sameOriginUrl primitive itself, which has broad coverage in+ * ExternalUrlTest.+ */+class SamlSloRedirectGuardTest extends TestCase+{+ public function test_sameorigin_url_rejects_offsite_slo_relaystate()+ {+ $this->assertNull(+ Helper::sameOriginUrl('https://attacker.example.net/phish'),+ 'A hostile RelayState URL from an IdP must be rejected by the same-origin guard before it reaches the session or the away() emission.'+ );+ }++ public function test_sameorigin_url_accepts_legitimate_slo_relaystate()+ {+ $this->assertNotNull(+ Helper::sameOriginUrl(config('app.url').'/dashboard'),+ 'A legitimate same-origin RelayState URL must survive the same-origin guard so an SLO round-trip can return the user to a Snipe-IT page.'+ );+ }+}