Answer#
Many sites accept a ?next= parameter so the user returns to the page they wanted after login. If the value is used blindly, an attacker can send a link to your real login page that forwards the user to an attacker's page afterwards. That page can imitate yours, and the user has just seen your genuine domain.
Checks such as "starts with /" fail: browsers treat //evil.example as a link to another host, and some treat /\evil.example the same way. A reliable check lets the same URL parser that browsers follow (the url crate implements the WHATWG URL standard) resolve the value, then compares the origin.
use url::Url;
/// Accept only a target on our own site; anything else becomes "/".
fn safe_redirect(target: &str) -> String {
let base = Url::parse("https://app.example.test/").unwrap();
match base.join(target) {
// join resolves "//host", "/\host" and "https://host" the way a browser would
Ok(u) if u.origin() == base.origin() => {
format!("{}{}", u.path(), u.query().map(|q| format!("?{q}")).unwrap_or_default())
}
_ => "/".to_string(),
}
}
fn main() {
for t in ["/account?tab=2", "settings", "https://evil.test/login", "//evil.test", "/\\evil.test", "javascript:alert(1)"] {
println!("{t:28} -> {}", safe_redirect(t));
}
}/account?tab=2 -> /account?tab=2
settings -> /settings
https://evil.test/login -> /
//evil.test -> /
/\evil.test -> /
javascript:alert(1) -> /The program uses a made-up site name. Every address that leaves the site becomes /; relative paths are resolved and kept.
How to do it#
- Keep the base address of your own site in configuration.
jointhe user's value to it and compareorigin().- Redirect to the path and query of the result, not to the original string.
- If you must redirect to other sites (for example, partners), keep an allow-list of exact origins.
- Better still, avoid the parameter: store the wanted page in the server-side session.
Common mistakes#
- Using
starts_with("/")or checking that the string contains your domain somewhere (evil.test/?example.com). - Forgetting the scheme-based cases such as
javascript:addresses. - Redirecting to an unchecked value from the
Refererheader.
Related questions#
Is an open redirect really a vulnerability?#
It is rated low on its own, but it makes phishing links look genuine, and it can combine with other flaws. OWASP lists unvalidated redirects as something to prevent.
Should the next address be signed instead?#
A signed value works too, but the same-origin check is simpler and needs no key. Keeping the target in the server-side session needs neither.
Sources#
- OWASP Unvalidated Redirects and Forwards Cheat Sheet: https://cheatsheetseries.owasp.org/cheatsheets/Unvalidated_Redirects_and_Forwards_Cheat_Sheet.html
urldocumentation,Url::joinandUrl::origin: https://docs.rs/url/2.5.8/url/struct.Url.html- WHATWG URL Standard: https://url.spec.whatwg.org/