Skip to content

A free open source IT asset/license management system

Harden internal URL redirect safety

sniped30b73d9c8dc
diff --git a/app/Helpers/Helper.php b/app/Helpers/Helper.php
index 7ee4a30482..ea62380400 100644
--- a/app/Helpers/Helper.php
+++ b/app/Helpers/Helper.php
@@ -1769,10 +1769,10 @@ class Helper
$checkedInFrom = session('checkedInFrom');
$other_redirect = session('other_redirect');
- // Same-origin gate: redirect()->intended() performs no host
- // validation, and url.intended can be written from the SAML
- // RelayState POST parameter (SamlController), which an
- // attacker-controlled IdP could set to an off-site URL.
+ // Defense-in-depth: url.intended can be written by any writer
+ // in the app (SamlController::acs sanitizes its RelayState
+ // input up-front, but future writers may not), and Laravel's
+ // redirect()->intended() performs no host validation on read.
$backUrl = self::sameOriginUrl(session()->pull('url.intended', 'home')) ?? route('home');
// return to previous page
diff --git a/app/Http/Controllers/Accessories/AccessoriesController.php b/app/Http/Controllers/Accessories/AccessoriesController.php
index 004ebbf053..e0e7e8e931 100755
--- a/app/Http/Controllers/Accessories/AccessoriesController.php
+++ b/app/Http/Controllers/Accessories/AccessoriesController.php
@@ -117,7 +117,9 @@ class AccessoriesController extends Controller
public function edit(Accessory $accessory): View|RedirectResponse
{
$this->authorize('update', $accessory);
- session()->put('url.intended', url()->previous());
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
return view('accessories.edit')->with('item', $accessory)->with('category_type', 'accessory');
}
diff --git a/app/Http/Controllers/Assets/AssetsController.php b/app/Http/Controllers/Assets/AssetsController.php
index b51bd07ac2..6e6e8766e1 100755
--- a/app/Http/Controllers/Assets/AssetsController.php
+++ b/app/Http/Controllers/Assets/AssetsController.php
@@ -315,7 +315,9 @@ class AssetsController extends Controller
public function edit(Asset $asset): View|RedirectResponse
{
$this->authorize($asset);
- session()->put('url.intended', url()->previous());
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
return view('hardware/edit')
->with('item', $asset)
diff --git a/app/Http/Controllers/Assets/BulkAssetsController.php b/app/Http/Controllers/Assets/BulkAssetsController.php
index 6d71217f90..7c2e2289b3 100644
--- a/app/Http/Controllers/Assets/BulkAssetsController.php
+++ b/app/Http/Controllers/Assets/BulkAssetsController.php
@@ -96,9 +96,15 @@ class BulkAssetsController extends Controller
return redirect()->route('maintenances.create');
}
- // Figure out where we need to send the user after the update is complete, and store that in the session
- $bulk_back_url = request()->headers->get('referer');
- session(['bulk_back_url' => $bulk_back_url]);
+ // Stash where to redirect after update/destroy. Referer is user-
+ // controllable, so run it through the same-origin gate so a
+ // hostile referrer can't turn the later redirect($bulk_back_url)
+ // into an open-redirect. If the referrer fails validation the
+ // reader falls back to route('hardware.index') via the same
+ // helper coalescing pattern.
+ if ($safeReferer = Helper::sameOriginUrl(request()->headers->get('referer'))) {
+ session(['bulk_back_url' => $safeReferer]);
+ }
$allowed_columns = [
'id',
@@ -247,9 +253,11 @@ class BulkAssetsController extends Controller
$has_errors = 0;
$error_array = [];
- // Get the back url from the session and then destroy the session
-
- $bulk_back_url = $request->session()->pull('bulk_back_url', url()->previous());
+ // Pull the stashed-and-vetted back URL from edit(). If the
+ // session slot is empty (direct POST, session lost, etc.) fall
+ // back to the plain index rather than url()->previous(), which
+ // is Referer-derived and would need its own sanitize step.
+ $bulk_back_url = Helper::sameOriginUrl($request->session()->pull('bulk_back_url')) ?? route('hardware.index');
$custom_field_columns = CustomField::all()->pluck('db_column')->toArray();
@@ -601,11 +609,10 @@ class BulkAssetsController extends Controller
{
$this->authorize('delete', Asset::class);
- $bulk_back_url = route('hardware.index');
-
- if ($request->session()->has('bulk_back_url')) {
- $bulk_back_url = $request->session()->pull('bulk_back_url');
- }
+ // Same pattern as update(): pull the vetted URL from edit()'s
+ // stash, fall through to the plain index if it's missing or was
+ // somehow poisoned upstream of the sanitize step.
+ $bulk_back_url = Helper::sameOriginUrl($request->session()->pull('bulk_back_url')) ?? route('hardware.index');
$assetIds = $request->input('ids');
if (empty($assetIds)) {
diff --git a/app/Http/Controllers/Auth/LoginController.php b/app/Http/Controllers/Auth/LoginController.php
index 9dcbff5c70..39fc2c3e25 100644
--- a/app/Http/Controllers/Auth/LoginController.php
+++ b/app/Http/Controllers/Auth/LoginController.php
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Auth;
+use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Models\Ldap;
use App\Models\SamlNonce;
@@ -56,7 +57,17 @@ class LoginController extends Controller
{
parent::__construct();
$this->middleware('guest', ['except' => ['logout', 'postTwoFactorAuth', 'getTwoFactorAuth', 'getTwoFactorEnroll']]);
- Session::put('backUrl', \URL::previous());
+
+ // backUrl feeds redirectTo(), which Laravel hands to the
+ // post-login Redirector without host validation. URL::previous()
+ // is Referer-derived and login endpoints are often the loosest
+ // on CSRF, so sanitize before storing. If the referrer isn't
+ // safe we leave backUrl unset and redirectTo() falls back to
+ // $this->redirectTo.
+ if ($safeReferer = Helper::sameOriginUrl(\URL::previous())) {
+ Session::put('backUrl', $safeReferer);
+ }
+
$this->saml = $saml;
}
@@ -525,6 +536,6 @@ class LoginController extends Controller
public function redirectTo()
{
- return Session::get('backUrl') ? Session::get('backUrl') : $this->redirectTo;
+ return Helper::sameOriginUrl(Session::get('backUrl')) ?? $this->redirectTo;
}
}
diff --git a/app/Http/Controllers/Auth/SamlController.php b/app/Http/Controllers/Auth/SamlController.php
index 1188a12d09..ccc24a5c42 100644
--- a/app/Http/Controllers/Auth/SamlController.php
+++ b/app/Http/Controllers/Auth/SamlController.php
@@ -2,6 +2,7 @@
namespace App\Http\Controllers\Auth;
+use App\Helpers\Helper;
use App\Http\Controllers\Controller;
use App\Services\Saml;
use Illuminate\Http\RedirectResponse;
@@ -93,10 +94,23 @@ class SamlController extends Controller
*/
public function acs(Request $request)
{
+ // RelayState is attacker-controllable via a hostile IdP or a
+ // crafted SAML POST binding. Sanitize before storing so any
+ // downstream consumer that skips Helper::getRedirectOption
+ // (LoginController::authenticated, RedirectIfAuthenticated,
+ // DashboardController, etc. all call redirect()->intended()
+ // directly, which does no host validation) can't be steered
+ // off-site. sameOriginUrl() also strips CR/LF and rejects
+ // non-http(s) schemes. Runs before getAuth() so the sanitize
+ // step is unconditional even if SAML happens to be disabled at
+ // request time.
+ if ($relayState = Helper::sameOriginUrl($request->post('RelayState'))) {
+ session()->put('url.intended', $relayState);
+ }
+
$saml = $this->saml;
$auth = $saml->getAuth();
$saml_exception = false;
- session()->put('url.intended', str_replace(["\r", "\n"], '', $request->post('RelayState')));
try {
$auth->processResponse();
} catch (\Exception $e) {
diff --git a/app/Http/Controllers/Components/ComponentsController.php b/app/Http/Controllers/Components/ComponentsController.php
index f88a9d58db..e99a94a4ac 100644
--- a/app/Http/Controllers/Components/ComponentsController.php
+++ b/app/Http/Controllers/Components/ComponentsController.php
@@ -125,7 +125,9 @@ class ComponentsController extends Controller
{
$this->authorize('update', $component);
- session()->put('url.intended', url()->previous());
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
return view('components/edit')
->with('item', $component)
diff --git a/app/Http/Controllers/Consumables/ConsumablesController.php b/app/Http/Controllers/Consumables/ConsumablesController.php
index 2db53464d9..813fc79f8b 100644
--- a/app/Http/Controllers/Consumables/ConsumablesController.php
+++ b/app/Http/Controllers/Consumables/ConsumablesController.php
@@ -134,7 +134,9 @@ class ConsumablesController extends Controller
public function edit(Consumable $consumable): View|RedirectResponse
{
$this->authorize($consumable);
- session()->put('url.intended', url()->previous());
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
return view('consumables/edit')
->with('item', $consumable)
diff --git a/app/Http/Controllers/Licenses/LicensesController.php b/app/Http/Controllers/Licenses/LicensesController.php
index 68ba1c2357..080a3b94d6 100755
--- a/app/Http/Controllers/Licenses/LicensesController.php
+++ b/app/Http/Controllers/Licenses/LicensesController.php
@@ -143,7 +143,9 @@ class LicensesController extends Controller
{
$this->authorize('update', $license);
- session()->put('url.intended', url()->previous());
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
$maintained_list = [
'' => 'Maintained',
'1' => 'Yes',
diff --git a/app/Http/Controllers/MaintenancesController.php b/app/Http/Controllers/MaintenancesController.php
index 1b44f03cf1..ae36dd3bbb 100644
--- a/app/Http/Controllers/MaintenancesController.php
+++ b/app/Http/Controllers/MaintenancesController.php
@@ -156,8 +156,11 @@ class MaintenancesController extends Controller
// Capture the referring page (filtered index, asset-detail tab)
// server-side so update() can restore the caller's context via
// redirect()->intended() without trusting a hidden form field.
- // Host-validated on read in update() below.
- session()->put('url.intended', url()->previous());
+ // Same-origin gated on write; also host-validated on read in
+ // update() below.
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
return view('maintenances/edit')
->with('selected_assets', $maintenance->asset->pluck('id')->toArray())
diff --git a/app/Http/Controllers/Users/UsersController.php b/app/Http/Controllers/Users/UsersController.php
index 2deecf4ec8..1568d483a7 100755
--- a/app/Http/Controllers/Users/UsersController.php
+++ b/app/Http/Controllers/Users/UsersController.php
@@ -218,7 +218,9 @@ class UsersController extends Controller
{
$this->authorize('update', $user);
- session()->put('url.intended', url()->previous());
+ if ($safeReferer = Helper::sameOriginUrl(url()->previous())) {
+ session()->put('url.intended', $safeReferer);
+ }
$user = User::with(['assets', 'assets.model', 'consumables', 'accessories', 'licenses', 'userloc'])->withTrashed()->find($user->id);
if ($user) {
diff --git a/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php b/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php
index 33d436aded..b4c082c051 100644
--- a/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php
+++ b/tests/Feature/Assets/Ui/BulkDeleteAssetsTest.php
@@ -196,4 +196,36 @@ class BulkDeleteAssetsTest extends TestCase
$expectedMessage = trans_choice('admin/hardware/message.delete.assigned_to_error', 1, ['asset_tag' => $asset->asset_tag]);
$this->assertEquals($expectedMessage, $errorMessage);
}
+
+ public function test_bulk_delete_redirects_to_stashed_same_origin_url()
+ {
+ $user = User::factory()->viewAssets()->deleteAssets()->create();
+ $asset = Asset::factory()->create();
+ $originUrl = route('hardware.index').'?status_type=Deployed';
+
+ $this->actingAs($user)
+ ->withSession(['bulk_back_url' => $originUrl])
+ ->post('/hardware/bulkdelete', [
+ 'ids' => [$asset->id],
+ 'bulk_actions' => 'delete',
+ ])
+ ->assertRedirect($originUrl);
+ }
+
+ public function test_bulk_delete_ignores_poisoned_stashed_url()
+ {
+ // Defense-in-depth: even if BulkAssetsController::edit()'s
+ // write-side gate were bypassed, the read here must still keep
+ // the redirect on-domain.
+ $user = User::factory()->viewAssets()->deleteAssets()->create();
+ $asset = Asset::factory()->create();
+
+ $this->actingAs($user)
+ ->withSession(['bulk_back_url' => 'https://evil.example.com/steal-session'])
+ ->post('/hardware/bulkdelete', [
+ 'ids' => [$asset->id],
+ 'bulk_actions' => 'delete',
+ ])
+ ->assertRedirect(route('hardware.index'));
+ }
}
diff --git a/tests/Feature/Assets/Ui/BulkEditAssetsTest.php b/tests/Feature/Assets/Ui/BulkEditAssetsTest.php
index 73ec810be1..032131b207 100644
--- a/tests/Feature/Assets/Ui/BulkEditAssetsTest.php
+++ b/tests/Feature/Assets/Ui/BulkEditAssetsTest.php
@@ -327,4 +327,78 @@ class BulkEditAssetsTest extends TestCase
$this->assertEquals('Original Encrypted Text', Crypt::decrypt($asset->{$encrypted->db_column}));
});
}
+
+ public function test_same_origin_referer_is_stored_as_bulk_back_url()
+ {
+ $user = User::factory()->viewAssets()->editAssets()->create();
+ $assets = Asset::factory()->count(2)->create();
+ $originUrl = route('hardware.index').'?status_type=Deployed';
+
+ $this->actingAs($user)
+ ->from($originUrl)
+ ->post('/hardware/bulkedit', [
+ 'ids' => $assets->pluck('id')->toArray(),
+ 'bulk_actions' => 'edit',
+ 'sort' => 'id',
+ 'order' => 'asc',
+ ])
+ ->assertSessionHas('bulk_back_url', $originUrl);
+ }
+
+ public function test_offsite_referer_is_not_stored_as_bulk_back_url()
+ {
+ $user = User::factory()->viewAssets()->editAssets()->create();
+ $assets = Asset::factory()->count(2)->create();
+
+ $this->actingAs($user)
+ ->from('https://evil.example.com/phish')
+ ->post('/hardware/bulkedit', [
+ 'ids' => $assets->pluck('id')->toArray(),
+ 'bulk_actions' => 'edit',
+ 'sort' => 'id',
+ 'order' => 'asc',
+ ])
+ ->assertSessionMissing('bulk_back_url');
+ }
+
+ public function test_bulk_update_redirects_to_stashed_same_origin_url()
+ {
+ $user = User::factory()->superuser()->create();
+ $asset = Asset::factory()->create();
+ $originUrl = route('hardware.index').'?status_type=Deployed';
+
+ $this->actingAs($user)
+ ->withSession(['bulk_back_url' => $originUrl])
+ ->post('/hardware/bulksave', [
+ 'ids' => [$asset->id => '1'],
+ ])
+ ->assertRedirect($originUrl);
+ }
+
+ public function test_bulk_update_falls_back_to_hardware_index_when_stashed_url_is_missing()
+ {
+ $user = User::factory()->superuser()->create();
+ $asset = Asset::factory()->create();
+
+ $this->actingAs($user)
+ ->post('/hardware/bulksave', [
+ 'ids' => [$asset->id => '1'],
+ ])
+ ->assertRedirect(route('hardware.index'));
+ }
+
+ public function test_bulk_update_ignores_poisoned_stashed_url()
+ {
+ // If the write-side gate were ever bypassed, the read-side
+ // helper coalescing must still keep the redirect on-domain.
+ $user = User::factory()->superuser()->create();
+ $asset = Asset::factory()->create();
+
+ $this->actingAs($user)
+ ->withSession(['bulk_back_url' => 'https://evil.example.com/steal-session'])
+ ->post('/hardware/bulksave', [
+ 'ids' => [$asset->id => '1'],
+ ])
+ ->assertRedirect(route('hardware.index'));
+ }
}
diff --git a/tests/Feature/Authentication/LoginBackUrlSanitizationTest.php b/tests/Feature/Authentication/LoginBackUrlSanitizationTest.php
new file mode 100644
index 0000000000..919d2e86f7
--- /dev/null
+++ b/tests/Feature/Authentication/LoginBackUrlSanitizationTest.php
@@ -0,0 +1,91 @@
+<?php
+
+namespace Tests\Feature\Authentication;
+
+use App\Http\Controllers\Auth\LoginController;
+use App\Models\User;
+use Illuminate\Support\Facades\Session;
+use Tests\TestCase;
+
+/**
+ * LoginController::__construct() stashes the current Referer as session
+ * key 'backUrl'. redirectTo() then feeds that value straight into
+ * Laravel's post-login Redirector, which does no host validation. Login
+ * endpoints are often the loosest on CSRF, so a hostile Referer could
+ * turn the post-auth landing page into an off-site phishing hand-off
+ * unless we sanitize at write time. redirectTo() also re-sanitizes on
+ * read as defense-in-depth against any future writer that skips the
+ * gate.
+ */
+class LoginBackUrlSanitizationTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ // CheckForSetup middleware bounces /login to /setup without a
+ // user in the DB. Create one so the constructor actually runs.
+ User::factory()->create();
+ }
+
+ public function test_same_origin_referer_is_stashed_as_backurl_on_login_form_visit()
+ {
+ $safeReferer = config('app.url').'/hardware?status_type=Deployed';
+
+ $this->from($safeReferer)
+ ->get(route('login'))
+ ->assertSessionHas('backUrl', $safeReferer);
+ }
+
+ public function test_offsite_referer_is_not_stashed_as_backurl_on_login_form_visit()
+ {
+ $this->from('https://evil.example.com/phish')
+ ->get(route('login'))
+ ->assertSessionMissing('backUrl');
+ }
+
+ public function test_javascript_scheme_referer_is_not_stashed()
+ {
+ // URL::previous() falls back to the previous URL or, absent
+ // that, session()['_previous']['url']. Seed it directly so we
+ // can test what happens if a javascript: URL somehow reaches
+ // URL::previous().
+ $this->withSession(['_previous' => ['url' => 'javascript:alert(1)']])
+ ->get(route('login'))
+ ->assertSessionMissing('backUrl');
+ }
+
+ public function test_redirect_to_returns_stashed_same_origin_url()
+ {
+ // Construct first — the constructor writes its own backUrl from
+ // URL::previous(). Then override the session slot with the
+ // scenario we're actually asserting on.
+ $controller = app(LoginController::class);
+
+ $safeReferer = config('app.url').'/hardware?status_type=Deployed';
+ Session::put('backUrl', $safeReferer);
+
+ $this->assertSame($safeReferer, $controller->redirectTo());
+ }
+
+ public function test_redirect_to_falls_back_when_backurl_is_missing()
+ {
+ $controller = app(LoginController::class);
+
+ Session::forget('backUrl');
+
+ // Default is $this->redirectTo = '/' (see LoginController).
+ $this->assertSame('/', $controller->redirectTo());
+ }
+
+ public function test_redirect_to_ignores_poisoned_backurl()
+ {
+ // Defense-in-depth: if a future writer skips the write-side
+ // gate, the read here still keeps the redirect on-domain.
+ $controller = app(LoginController::class);
+
+ Session::put('backUrl', 'https://evil.example.com/steal-session');
+
+ $this->assertSame('/', $controller->redirectTo());
+ }
+}
diff --git a/tests/Feature/Authentication/SamlRelayStateSanitizationTest.php b/tests/Feature/Authentication/SamlRelayStateSanitizationTest.php
new file mode 100644
index 0000000000..dc38d02fc1
--- /dev/null
+++ b/tests/Feature/Authentication/SamlRelayStateSanitizationTest.php
@@ -0,0 +1,98 @@
+<?php
+
+namespace Tests\Feature\Authentication;
+
+use App\Models\User;
+use Tests\TestCase;
+
+/**
+ * SamlController::acs() writes the RelayState POST parameter into
+ * session()['url.intended']. RelayState is attacker-controllable via a
+ * hostile IdP or a crafted SAML POST binding, and several post-auth
+ * redirect sites (LoginController::authenticated, RedirectIfAuthenticated,
+ * DashboardController) call redirect()->intended() directly, bypassing
+ * Helper::getRedirectOption's host-validation guard. So RelayState must
+ * be sanitized at write time.
+ *
+ * The sanitize step runs before Saml::getAuth(), so these tests exercise
+ * it even without a fully configured IdP — the endpoint still 500s on
+ * the missing SAML config after the write, which is fine for what we're
+ * asserting on.
+ */
+class SamlRelayStateSanitizationTest extends TestCase
+{
+ protected function setUp(): void
+ {
+ parent::setUp();
+
+ // CheckForSetup middleware redirects to /setup when there are no
+ // users. Creating one lets acs actually run.
+ User::factory()->create();
+ }
+
+ public function test_offsite_relaystate_is_not_written_to_intended_url()
+ {
+ session()->forget('url.intended');
+
+ $this->post(route('saml.acs'), [
+ 'RelayState' => 'https://evil.example.com/steal-session',
+ 'SAMLResponse' => 'invalid',
+ ]);
+
+ $this->assertNull(session('url.intended'), 'Off-site RelayState must not become url.intended');
+ }
+
+ public function test_javascript_scheme_relaystate_is_not_written_to_intended_url()
+ {
+ session()->forget('url.intended');
+
+ $this->post(route('saml.acs'), [
+ 'RelayState' => 'javascript:alert(document.cookie)',
+ 'SAMLResponse' => 'invalid',
+ ]);
+
+ $this->assertNull(session('url.intended'));
+ }
+
+ public function test_scheme_relative_offsite_relaystate_is_not_written_to_intended_url()
+ {
+ session()->forget('url.intended');
+
+ $this->post(route('saml.acs'), [
+ 'RelayState' => '//evil.example.com/steal-session',
+ 'SAMLResponse' => 'invalid',
+ ]);
+
+ $this->assertNull(session('url.intended'));
+ }
+
+ public function test_same_origin_relaystate_is_preserved()
+ {
+ $safeRelay = config('app.url').'/hardware?status=1';
+
+ $this->post(route('saml.acs'), [
+ 'RelayState' => $safeRelay,
+ 'SAMLResponse' => 'invalid',
+ ]);
+
+ $this->assertSame($safeRelay, session('url.intended'));
+ }
+
+ public function test_crlf_in_relaystate_is_stripped()
+ {
+ $poisoned = config('app.url')."/hardware\r\nSet-Cookie: attacker=1";
+
+ $this->post(route('saml.acs'), [
+ 'RelayState' => $poisoned,
+ 'SAMLResponse' => 'invalid',
+ ]);
+
+ // CR/LF stripped so this can't split the HTTP response into a
+ // header-injection primitive. Remaining text is harmless once
+ // the line breaks are gone.
+ $stored = session('url.intended');
+ $this->assertNotNull($stored);
+ $this->assertStringNotContainsString("\r", $stored);
+ $this->assertStringNotContainsString("\n", $stored);
+ }
+}