Web application security · 4 MIN READ
Open redirects: accept a single-slash path or an allow-listed host, not any URL that parses
Validate redirect targets so only same-site paths and allow-listed https URLs pass, including the //host, backslash and userinfo tricks that browsers and net/url read differently.
Login, logout and OAuth flows often carry a next or return_to parameter. If the server redirects to whatever it contains, an attacker can send a link that starts on your trusted domain and ends on a lookalike login page, and in OAuth flows a redirect can leak codes or tokens. The obvious fix, allow only relative paths, is harder than it looks: browsers parse URLs by the WHATWG URL Standard, Go's net/url follows RFC 3986, and every difference between them is a bypass.
security · A MAP OF THE IDEA
- Reject backslash, controls
- Parse the target
- Path or allow-listed host
- Fall back to fixed page
Useful when
- Only two target shapes exist, so the policy fits in a short table.
- Rejected input is never echoed into the Location header.
Watch out
- net/url and browsers disagree on backslashes, tabs and userinfo.
- http.Redirect cleans relative paths but passes //host targets through.
Implementation & operation cost: A small validator and a host allow-list; keeping return paths server-side costs one session field.
Why starting with / is not the same as staying on this site
A target of //evil.example/login starts with a slash, yet browsers read it as a scheme-relative URL that changes the host. Browsers also treat a backslash like a forward slash in http and https URLs, so /\evil.example becomes //evil.example on its way to the address bar, and they delete tab and newline characters anywhere in a URL, so a slash, a tab and another slash collapse into the same thing. Absolute URLs bring their own tricks: in https://docs.example.com@evil.example the first part is userinfo and the host is evil.example, and https://docs.example.com.evil.example/ passes any check that only compares a prefix. None of these needs a bug in your router, only validation that inspects a string instead of the destination a browser will compute.
A decision table for redirect targets
redirectTarget accepts exactly two shapes: a relative reference that begins with a single slash, or an https URL whose host is on an explicit allow-list. Everything else is rejected with a reason. The table compares it with a common first attempt that allows anything beginning with / or with the docs prefix, and the last two lines run the validator inside a login handler through httptest.
package main
import (
"errors"
"fmt"
"net/http"
"net/http/httptest"
"net/url"
"strings"
)
// allowedHosts lists the only absolute destinations; compare exact hostnames.
var allowedHosts = map[string]bool{"docs.example.com": true}
func redirectTarget(raw string) (string, error) {
if raw == "" {
return "", errors.New("empty")
}
// Browsers treat \ like / and strip tabs and newlines; Go's parser does not.
if strings.ContainsFunc(raw, func(r rune) bool { return r == '\\' || r < 0x20 || r == 0x7f }) {
return "", errors.New("backslash or control character")
}
u, err := url.Parse(raw)
if err != nil {
return "", errors.New("unparseable")
}
if u.Scheme == "" && u.Host == "" && u.User == nil {
if !strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "//") {
return "", errors.New("relative target must start with exactly one /")
}
return u.String(), nil
}
// u.Host includes any port, so "docs.example.com:8443" is not allowed either.
if !allowedHosts[u.Host] {
return "", fmt.Errorf("host %q not allowed", u.Host)
}
if u.Scheme != "https" || u.User != nil {
return "", errors.New("only https URLs without userinfo")
}
return u.String(), nil
}
// naiveTarget is a common first attempt: a local path or "our" docs prefix.
func naiveTarget(raw string) bool {
return strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "https://docs.example.com")
}
func main() {
inputs := []string{
"/settings?tab=keys",
"https://docs.example.com/guide",
"http://docs.example.com/guide",
"//evil.example/login",
`/\evil.example`,
"/\t/evil.example",
"https://docs.example.com@evil.example/",
"https://docs.example.com.evil.example/",
"https:evil.example",
"javascript:alert(1)",
"settings",
}
for _, in := range inputs {
naive := "reject"
if naiveTarget(in) {
naive = "allow"
}
if target, err := redirectTarget(in); err != nil {
fmt.Printf("%-42q naive=%-6s safe=reject (%v)\n", in, naive, err)
} else {
fmt.Printf("%-42q naive=%-6s safe=allow %s\n", in, naive, target)
}
}
// The handler falls back to a fixed page instead of echoing bad input.
h := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
target, err := redirectTarget(r.URL.Query().Get("next"))
if err != nil {
target = "/"
}
http.Redirect(w, r, target, http.StatusSeeOther)
})
for _, next := range []string{"/settings", "//evil.example"} {
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest("POST", "/login?next="+url.QueryEscape(next), nil))
fmt.Printf("POST /login next=%s -> %d Location: %s\n", next, rec.Code, rec.Header().Get("Location"))
}
}Backslashes and control characters are rejected before parsing, because net/url either keeps them as path bytes or refuses them while a browser silently rewrites them. url.Parse then decides the shape: no scheme, no host and no userinfo means a relative reference, which must start with one slash and not two. For absolute URLs, u.Host, which includes any port, must equal an allow-list entry, so the userinfo and suffix tricks reveal their real hosts. https:evil.example parses with an empty host and an opaque part, and javascript: URLs have no host either, so both fail. The handler never echoes a rejected value: it falls back to / and answers 303 See Other so the browser follows with GET after the login POST.
What url.Parse does and does not tell you
url.Parse is a parser, not a validator. It accepts almost any string: settings parses as a relative path, javascript:alert(1) as a scheme with an opaque part, and a leading space simply becomes part of the path. It lowercases the scheme but not the host, so normalize the host with strings.ToLower if DOCS.example.com should match. Never allow-list by string suffix, because badexample.com ends with example.com; if subdomains are allowed, require the host to equal example.com or end with .example.com. http.Redirect, and Gin's c.Redirect, which calls it, turn a relative target into an absolute path and clean it, but they pass //evil.example and /\evil.example through unchanged, so they are not validators either. Validate first and redirect to the value you validated.
Better still: do not accept URLs at all
The safest redirect parameter is not a URL. Store the intended destination server-side, for example in the session before sending the user to log in, and carry nothing or an opaque key in the query string. When a client must name a destination, let it choose from names that map to URLs in configuration. OAuth makes this mandatory for redirect_uri: the OAuth 2.0 security best current practice requires authorization servers to compare it with pre-registered values by exact string match, and your own post-login return path deserves the same standard. If linking to external sites is a product feature, show an interstitial page that displays the destination instead of redirecting silently.
Test with a browser's eyes
Build the test table from transformations browsers actually apply: //host, backslashes, tabs and newlines inside the slashes or scheme, userinfo, suffix lookalikes, uppercase hosts, ports, the https:host form, javascript: and data: schemes, and percent-encoded slashes if any later component decodes them. Assert both the decision and the exact Location header. Run the same inputs through every place that redirects, including logout and error pages, because one unvalidated handler is enough. Log rejected values: repeated rejections are often the first visible sign that someone is testing phishing links against your login page.
TAKE THIS WITH YOU
Accept a redirect target only if it is a path starting with exactly one slash or an https URL whose exact host is allow-listed; reject backslashes and control characters first and fall back to a fixed page.
Check your understanding
A login handler redirects to next only if it starts with "/". Why is next=//evil.example still dangerous?
Go to the source
Progress stays in this browser. No account needed.