package router import ( "net" "net/http" "net/netip" "net/url" "strings" ) // AdminGuard keeps a browser from being used against the admin listener. // // The listener has no login: reaching it is meant to mean holding the machine, // so it binds to loopback and an operator reaches it over an ssh tunnel. But a // browser on that operator's machine reaches it too, from any page it has // open. A page could POST a model whose profile runs as root on every node, // or — by pointing its own domain at 127.0.0.1 — read pprof's heap, which // holds API keys in the clear. Three checks close that without touching what // ctl and curl do: // // - Host must be an address or localhost. A page that rebinds its own name // to 127.0.0.1 still sends that name. // - A request carrying Origin or Sec-Fetch-Site from another site is // refused. Browsers send them; ctl and curl do not. // - Anything but GET and HEAD must be application/json. A page can send a // form or text/plain anywhere without asking; JSON across origins needs a // preflight this listener never grants. func AdminGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !addressHost(r.Host) { http.Error(w, "the admin listener answers to an address or localhost, not a name", http.StatusMisdirectedRequest) return } if crossSite(r) { http.Error(w, "cross-site request refused", http.StatusForbidden) return } if r.Method != http.MethodGet && r.Method != http.MethodHead { ct := r.Header.Get("Content-Type") if mt, _, _ := strings.Cut(ct, ";"); strings.TrimSpace(strings.ToLower(mt)) != "application/json" { http.Error(w, "a change to the admin API must be sent as application/json", http.StatusUnsupportedMediaType) return } } next.ServeHTTP(w, r) }) } func addressHost(hostport string) bool { host := hostport if h, _, err := net.SplitHostPort(hostport); err == nil { host = h } host = strings.Trim(host, "[]") if strings.EqualFold(host, "localhost") { return true } _, err := netip.ParseAddr(host) return err == nil } func crossSite(r *http.Request) bool { switch r.Header.Get("Sec-Fetch-Site") { case "", "same-origin", "none": default: return true } if o := r.Header.Get("Origin"); o != "" { u, err := url.Parse(o) if err != nil || !strings.EqualFold(u.Host, r.Host) { return true } } return false }