Login Return Developer Guide - edmozley/freeitsm GitHub Wiki
Back to your page after signing in - Developer Guide
(5.8.0, #407, contributed by @cloudcogsio)
When a session ends while a page is open - an idle timeout, a sign-out in another tab, a server restart - the next click lands on the sign-in page. Signing in now goes back to the page that was asked for, however the sign-in finishes: password, trusted device, MFA, single sign-on, or the forced password change. Opening the sign-in page yourself still goes to your landing page.
This page is how it works and what to keep in mind when you touch sign-in. The merge review, with the open-redirect tests, is Back to your page after sign-in - review.
Files
| File | What it holds |
|---|---|
includes/login_return.php |
The hook (loginReturnInstallHook()), the sanitiser (loginReturnSanitize()), loginReturnRemember() / loginReturnPeek() / loginReturnTake(), the refused folders and aliases |
includes/functions.php |
Installs the hook, before the gates that redirect |
auth/login.php |
Keeps ?return= in the session; uses it when already signed in, after a password or trusted-device sign-in, and across a cancelled MFA step |
auth/force_password_change.php |
After the new password: loginReturnPeek() ?? index.php |
api/myaccount/verify_login_otp.php |
The MFA finish: loginReturnTake() |
api/auth/oidc_callback.php |
The single sign-on finish: loginReturnTake() |
tests/login-return-target.php |
The sanitiser against every known redirect trick, at a subfolder and at the web root (47 checks) |
1. One hook instead of a hundred edits
Around a hundred pages and gates redirect to auth/login.php on their own - module headers, requireModuleAccess(), the active-analyst gate. Rather than change each of them, includes/functions.php (which every page loads) installs a header callback before those gates run:
// includes/functions.php
require_once __DIR__ . '/login_return.php';
loginReturnInstallHook();
The callback runs just before PHP sends the headers. If the response is a bare redirect to the sign-in page, it adds where the person was going:
// includes/login_return.php - inside loginReturnInstallHook()
header_register_callback(function () use ($here) {
foreach (headers_list() as $h) {
if (stripos($h, 'Location:') !== 0) {
continue;
}
$location = trim(substr($h, 9));
// Only the bare sign-in page, absolute or relative ('../auth/login.php').
// One that already carries a query (an error, a cancel) is left alone.
if (preg_match('#(^|/)auth/login\.php$#', $location)) {
header('Location: ' . $location . '?return=' . rawurlencode($here));
}
return;
}
});
The hook is only installed when it means something:
- GET requests only, and not from the command line.
- Not for JSON callers (
X-Requested-With: XMLHttpRequestorAccept: application/json) - they get a 401, not a page. - Not when the running script is under
auth/,api/,setup/orself-service/- judged bySCRIPT_NAME(the file actually running), not the URL, because.htaccessserves sign-in and sign-out pages at root aliases too. - Not for the landing page itself - that is where a sign-in goes anyway, so its sign-in link stays plain.
- Not when the current address fails
loginReturnSanitize().
2. Kept in the session, used once
// auth/login.php
if (($_SERVER['REQUEST_METHOD'] ?? '') === 'GET') {
if (isset($_GET['return'])) {
loginReturnRemember(is_string($_GET['return']) ? $_GET['return'] : null);
} elseif (($_SERVER['QUERY_STRING'] ?? '') === '' && $sso_error === null
&& !isset($_SESSION['mfa_pending_analyst_id'])) {
loginReturnRemember(null);
}
}
The target lives in $_SESSION['login_return_to'], so it survives the POST, the MFA step and a single sign-on round trip. Opening the sign-in page plainly forgets an old one - but not when single sign-on has just bounced back with an error, or an MFA step is pending, because that is the same sign-in still under way. Cancelling MFA starts the sign-in again with the same ?return= (loginReturnPeek()).
Every finish ends with header('Location: ' . loginReturnTake()):
function loginReturnTake(): string
{
$target = loginReturnPeek();
unset($_SESSION[LOGIN_RETURN_SESSION_KEY]);
$landing = (defined('BASE_URL') ? BASE_URL : '/') . 'index.php';
if (isset($_COOKIE['freeitsm_report_return'])) {
return $landing;
}
return $target ?? $landing;
}
It is read and forgotten, so a later, ordinary sign-in starts at the landing page. A report download link opened while signed out leaves its own cookie that index.php acts on; that wins, so the download is not left to fire on some later visit.
3. 🔴 The open redirect, and the sanitiser
The target comes from the address bar, so anybody can send a sign-in link with any return. If FreeITSM followed it blindly, a phishing email could use a real FreeITSM sign-in page to send someone to a look-alike site straight after they signed in. Every read goes through one function, on the way in and on the way out:
function loginReturnSanitize($target, ?string $base = null): ?string
{
if (!is_string($target) || $target === '' || strlen($target) > 2048) {
return null;
}
// Control characters (header injection) and backslashes (browsers read "/\host" as "//host").
if (preg_match('/[\x00-\x1F\x7F\\\\]/', $target)) {
return null;
}
$base = $base ?? (defined('BASE_URL') ? BASE_URL : '/');
if ($target[0] !== '/' || str_starts_with($target, '//') || !str_starts_with($target, $base)) {
return null;
}
$parts = parse_url($target);
if ($parts === false || isset($parts['scheme']) || isset($parts['host']) || !isset($parts['path'])) {
return null;
}
$path = rawurldecode($parts['path']);
if (preg_match('#(^|/)\.\.?(/|$)#', $path) || str_contains($path, '\\') || str_starts_with($path, '//')) {
return null;
}
// Case-insensitive: on a case-insensitive filesystem /AUTH/login.php is the same file.
$rel = strtolower(substr($path, strlen($base)));
foreach (LOGIN_RETURN_REFUSED_FOLDERS as $folder) {
if (str_starts_with($rel, $folder)) {
return null;
}
}
if (in_array(rtrim($rel, '/'), LOGIN_RETURN_REFUSED_ALIASES, true)) {
return null;
}
return $target;
}
In words: only a path on this install (it starts with BASE_URL), never a scheme, host or leading //, never a backslash or control character, never a . or .. segment (checked after percent-decoding), and never a page under auth/, api/, setup/ or self-service/.
LOGIN_RETURN_REFUSED_ALIASES lists the root aliases .htaccess rewrites into auth/ (login, logout, analyst_logout.php, forgot-password...). Without it, a return of /analyst_logout.php would sign the person out again straight after every sign-in.
The riskiest case is an install at the web root, where BASE_URL is just / and "starts with the base" proves nothing - which is why the //, backslash and scheme checks exist on their own. The test runs every trick at both.
With Keep me signed in (5.12.0)
Keep me signed in signs a returning browser back in at the end of includes/functions.php - before the page checks the session, so before it would redirect here. The two do not meet: with a kept sign-in nobody reaches the sign-in page to need returning; without one, this works exactly as before.
Traps
- TRAP: PHP keeps ONE header callback per request. A second
header_register_callback()anywhere replaces this one silently, and the return address quietly stops working. Nothing else registers one; anything that ever needs to must chain to this one. - A new way to finish signing in must call
loginReturnTake(), or that route lands on the landing page - safe, just not helpful. - A new folder of pages nobody should be sent back to (JSON, setup, another sign-in) belongs in
LOGIN_RETURN_REFUSED_FOLDERS; a new root alias for a sign-in or sign-out page belongs inLOGIN_RETURN_REFUSED_ALIASES. - Redirect to
auth/login.php, not a root alias. A page that sent signed-out visitors to../login.phpgot no return address (contracts/equipment-report.phpdid, and was fixed in the merge). The hook only recognises the real path.
Testing
php tests/login-return-target.php
It feeds the sanitiser the known tricks - https://evil.com, //evil.com, /\evil.com, /%2F%2Fevil.com, /%2e/%2e/evil, raw tabs and null bytes, /AUTH/login.php, /Analyst_Logout.php - at a subfolder and at the web root, and checks the harmless ones (/https://evil.com, /@evil.com, which are paths on this site) are accepted. Over real HTTP: signed out, open a deep page; the sign-in URL carries ?return=; sign in and you are back on it; sign in plainly and you land on index.php.
Related: Code traps · CSRF protection - Developer Guide · Single sign-on