// Package httpsec holds the HTTP hardening every Yetano/Yak/Yamase web // UI shares: security headers, the Host gate against DNS rebinding, // open-redirect-safe "next" targets and the cookie scope for a UI served // under a base path. It only builds on net/http; cross-origin protection // stays the standard library's http.CrossOriginProtection. package httpsec import ( "net" "net/http" "net/url" "strings" ) // DefaultCSP allows the UI's own scripts, styles and images (plus data: // images, e.g. the template's favicon) and nothing else: no plugins, no // rewriting, no framing, forms only to the UI itself. const DefaultCSP = "default-src 'self'; img-src 'self' data:; object-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'self'" // HeaderOptions configures Headers. The zero value is the default set. type HeaderOptions struct { // CSP replaces DefaultCSP, e.g. for a UI that still needs inline // scripts or a WebSocket to another origin. CSP string // TLS adds Strict-Transport-Security. Set it only when the UI itself // serves HTTPS (or is only ever reached through an HTTPS proxy): // browsers remember it for a year. TLS bool // CacheablePrefixes are path prefixes (as the handler sees them) whose // responses may be cached, e.g. "/static/", "/webui-static/"; // everything else gets Cache-Control: no-store, so pages with // session data never land in a shared or back-button cache. CacheablePrefixes []string } // Headers sets the security headers on every response of next. Put it // outermost, so even a 421 from the Host gate or a 403 from cross-origin // protection carries them. func Headers(next http.Handler, opts HeaderOptions) http.Handler { csp := opts.CSP if csp == "" { csp = DefaultCSP } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { h := w.Header() h.Set("Content-Security-Policy", csp) h.Set("X-Content-Type-Options", "nosniff") h.Set("X-Frame-Options", "DENY") h.Set("Referrer-Policy", "same-origin") h.Set("Cross-Origin-Opener-Policy", "same-origin") if opts.TLS { h.Set("Strict-Transport-Security", "max-age=31536000") } cacheable := false for _, p := range opts.CacheablePrefixes { if strings.HasPrefix(r.URL.Path, p) { cacheable = true break } } if !cacheable { h.Set("Cache-Control", "no-store") } next.ServeHTTP(w, r) }) } // GateActive is the family's rule for when the Host gate runs: always // when the UI has no login (anyone who can make a browser send requests // to it could otherwise drive it through a rebound DNS name), and also // with a login once hosts are configured explicitly. A UI behind a // domain with a login keeps working without extra configuration. func GateActive(loginOn bool, allowed []string) bool { return !loginOn || len(allowed) > 0 } // HostAllowed reports whether a request's Host header names this UI: an // IP address, localhost or a *.localhost name, or one of allowed // (compared case-insensitively, a trailing dot ignored). A port is // ignored. An empty Host is rejected -- every browser sends one, so only // a hand-made request lacks it. func HostAllowed(host string, allowed []string) bool { if h, _, err := net.SplitHostPort(host); err == nil { host = h } host = strings.TrimSuffix(strings.ToLower(strings.Trim(host, "[]")), ".") if host == "" { return false } if net.ParseIP(host) != nil || host == "localhost" || strings.HasSuffix(host, ".localhost") { return true } for _, a := range allowed { if strings.TrimSuffix(strings.ToLower(a), ".") == host { return true } } return false } // HostOf returns the host of a public URL (e.g. a configured external // address), for adding it to the allowed list; "" if there is none. func HostOf(publicURL string) string { u, err := url.Parse(publicURL) if err != nil { return "" } return u.Hostname() } // Gate answers 421 Misdirected Request for a Host HostAllowed rejects, // naming setting (the configuration key that lists allowed hosts, e.g. // "settings.webUI.allowedHosts") so the operator knows what to change. func Gate(next http.Handler, allowed []string, setting string) http.Handler { msg := "unknown host" if setting != "" { msg += " (see " + setting + ")" } return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if !HostAllowed(r.Host, allowed) { http.Error(w, msg, http.StatusMisdirectedRequest) return } next.ServeHTTP(w, r) }) } // SafeNext returns next if it is a local target inside the UI at // basePath ("" for a UI at the root) -- a path, optionally with query, // that cannot leave the host: no scheme, host or user, no "//" or "/\" // start, no backslash or control character -- and none of the // basePath-relative paths in exclude (e.g. "/login", "/logout", so a // login never returns to itself). Otherwise it returns basePath + "/". func SafeNext(next, basePath string, exclude ...string) string { fallback := basePath + "/" if next == "" || !strings.HasPrefix(next, "/") || strings.HasPrefix(next, "//") { return fallback } for _, c := range next { if c < 0x20 || c == 0x7f || c == '\\' { return fallback } } u, err := url.Parse(next) if err != nil || u.Scheme != "" || u.Host != "" || u.User != nil || u.Opaque != "" { return fallback } rel := u.Path if basePath != "" { if rel != basePath && !strings.HasPrefix(rel, basePath+"/") { return fallback } rel = strings.TrimPrefix(rel, basePath) } for _, x := range exclude { if rel == x { return fallback } } return next } // CookiePath is the Path for cookies of a UI at basePath: basePath + "/" // ("/" at the root), so two UIs on one host keep separate sessions and // "/app" never matches "/application". (A "__Host-" cookie needs Path // "/" and therefore a UI at the root.) func CookiePath(basePath string) string { return strings.TrimSuffix(basePath, "/") + "/" } // SecureCookies reports whether cookies for r should carry Secure: when // the request came over TLS, or the UI's public URL is https (it then // sits behind a TLS-terminating proxy). func SecureCookies(r *http.Request, publicURL string) bool { return r.TLS != nil || strings.HasPrefix(strings.ToLower(publicURL), "https://") }