TExcelTAD

Open Redirects and URL Parsing

After login, most sites send you back where you were: /login?next=/orders/42. If the server redirects to whatever next says, then https://shop.lab.test/login?next=https://evil.example/ is a link that starts on the real shop, passes its sign-in page, and ends on the attacker's look-alike, which then asks for the password "again". That is an open redirect (CWE-601). On its own it is a phishing aid, usually rated low or medium. Chained, it is worse: OAuth flaws showed it turning a loose redirect_uri check into a stolen authorization code, and it can bypass SSRF allow-lists that trust the site's own host. The interesting part is the fix, because "is this URL on my site?" turns out to be a question that naive string checks answer wrongly.

Definitions

  • Open redirect: an endpoint that redirects (HTTP 3xx Location, a <meta refresh>, location.href = … in JavaScript) to a destination taken from the request without validation.
  • Relative reference: /orders/42 (path-absolute), orders/42 (path-relative), ?tab=2, #top. Scheme-relative (network-path) reference: //evil.example/x, which inherits the scheme but changes the host.
  • WHATWG URL parsing (browsers): treats \ like / in special schemes (http, https), strips raw tabs and newlines, and reads https:evil.example as a relative path on an https page but as the host evil.example on an http page. Server-side parsers often disagree, which is the gap attackers use.

Naive checks against the browser's parser

The function whereDoesItGo asks the same URL parser browsers use (Node's URL follows the WHATWG standard) where a redirect would really land, starting from the shop's login page. Three validators then judge each candidate.

js · try it yourself
const BASE = 'https://shop.lab.test/login';
const whereDoesItGo = (next) => new URL(next, BASE).href;

const naive = {
  'startsWith("/")': (n) => n.startsWith('/'),
  'includes(host)': (n) => n.includes('shop.lab.test'),
  'no "//" prefix': (n) => n.startsWith('/') && !n.startsWith('//'),
};

function safeNext(next) {
  // Resolve with the browser's rules, then require the same origin; fall back to the home page.
  try {
    const u = new URL(next, BASE);
    if (u.origin !== 'https://shop.lab.test') return '/';
    return u.pathname + u.search + u.hash;          // send a path, never the full URL we were given
  } catch {
    return '/';
  }
}

const candidates = ['/orders/42', '//evil.example/login', '/\\evil.example/login', 'https://evil.example/',
  'https://shop.lab.test.evil.example/', '/%09/evil.example', 'https:evil.example', '/orders?x=1#top'];
for (const c of candidates) {
  const verdicts = Object.entries(naive).map(([name, f]) => (f(c) ? 'pass' : '-').padEnd(6)).join(' ');
  console.log(JSON.stringify(c).padEnd(40), '->', whereDoesItGo(c).padEnd(40), verdicts, ' safe:', safeNext(c));
}
"/orders/42"                             -> https://shop.lab.test/orders/42          pass   -      pass    safe: /orders/42
"//evil.example/login"                   -> https://evil.example/login               pass   -      -       safe: /
"/\\evil.example/login"                  -> https://evil.example/login               pass   -      pass    safe: /
"https://evil.example/"                  -> https://evil.example/                    -      -      -       safe: /
"https://shop.lab.test.evil.example/"    -> https://shop.lab.test.evil.example/      -      pass   -       safe: /
"/%09/evil.example"                      -> https://shop.lab.test/%09/evil.example   pass   -      pass    safe: /%09/evil.example
"https:evil.example"                     -> https://shop.lab.test/evil.example       -      -      -       safe: /evil.example
"/orders?x=1#top"                        -> https://shop.lab.test/orders?x=1#top     pass   -      pass    safe: /orders?x=1#top

Each naive check passed at least one destination on evil.example: startsWith("/") passes //evil.example, the "no //" refinement passes /\evil.example, which the browser normalises to //evil.example, and includes(host) passes any domain that merely contains the shop's name. The safe version resolves the value with the same parser the browser will use, compares the origin, and redirects to the path it computed rather than echoing the input. Server code in other languages should do the same with a WHATWG-compliant parser, or avoid parsing altogether.

The best fix: don't take URLs at all

A redirect target can often be an identifier instead of a URL: ?next=orders mapped on the server to /orders, or a key into a server-side session (session["return_to"] saved before showing the login form). The Python version of that pattern:

python · try it yourself
RETURN_TARGETS = {"orders": "/orders", "cart": "/cart", "settings": "/account/settings"}

def after_login(next_key):
    return "302 Location: " + RETURN_TARGETS.get(next_key, "/")

for key in ["orders", "settings", "https://evil.example/", "//evil.example", None]:
    print(f"{key!r:26} -> {after_login(key)}")
'orders'                   -> 302 Location: /orders
'settings'                 -> 302 Location: /account/settings
'https://evil.example/'    -> 302 Location: /
'//evil.example'           -> 302 Location: /
None                       -> 302 Location: /

Nothing the attacker sends can become a URL, so there is nothing to parse wrongly.

How open redirects are detected

  • Testing (in scope): find parameters that look like destinations (next, return, returnTo, redirect, url, continue, dest, goto, RelayState, OAuth redirect_uri) and JavaScript that assigns location from URL data; try the candidate list above and watch the Location header or where the browser ends up.
  • Code review: redirect(request.args["next"]), res.redirect(req.query.url), header("Location: " . $_GET[...]), location.href = params.get(...); validation by startsWith, includes, or regular expressions instead of origin comparison.
  • Logs: redirect parameters containing //, \, %09, %2f%2f, @, or external host names; spikes in a redirect endpoint's traffic from e-mail referrers (phishing campaigns using your domain).

How it is fixed

  1. Use identifiers or a server-side stored return path, not URLs.
  2. If a URL is needed, resolve it with a WHATWG parser and require the same origin (or an allow-list of origins), then redirect to the normalised path.
  3. For unavoidable external redirects, show an interstitial ("You are leaving shop.lab.test for …") and sign the destination with an HMAC so only links your site generated work.
  4. Keep OAuth redirect_uri exact-match, so an open redirect can't become a code leak.

Pitfalls

  • Decoding twice: %252f%252f becomes %2f%2f after one decode and // after the second; validate the same string you redirect to.
  • Different parsers in different layers (a proxy, the framework, the browser).
  • javascript: in client-side redirects: location.href = next with next = "javascript:…" is XSS, not just a redirect (DOM XSS).

Practice

1. Why does safeNext return u.pathname + u.search + u.hash instead of next?

So the redirect uses the value that was checked, normalised by the parser, and always a path on the shop. Echoing the original string would let any remaining parser disagreement between the check and the browser slip through.

2. An open redirect exists on shop.lab.test, and the shop's OAuth client registered https://shop.lab.test/ as a prefix-matched redirect URI. Describe the chain.

The attacker sends the victim an authorization link with redirect_uri=https://shop.lab.test/go?to=https://evil.example/. The AS accepts it (prefix match), the victim signs in, the AS sends the code to the shop's open redirect, which forwards the browser, with the code in the URL, to the attacker. Exact redirect URIs and PKCE break the chain at two points.

Test yourself

Where does //evil.example/login lead from https://shop.lab.test/login?

  1. https://shop.lab.test//evil.example/login
  2. https://evil.example/login
  3. Nowhere
  4. An error

Why did /\evil.example pass a check for 'starts with / but not //'?

  1. Backslashes are ignored
  2. Browsers treat \ like / in http(s) URLs, so it becomes //evil.example after the check
  3. It is a relative path
  4. It is encoded

What is the most robust fix for post-login redirects?

  1. A regex on the URL
  2. Map short identifiers (or a stored return path) to fixed paths on the server
  3. Block the word http
  4. Use 301 instead of 302