From abc1898daebae33405688618caffa01cece3b850 Mon Sep 17 00:00:00 2001 From: grm Date: Fri, 18 Sep 2026 13:48:50 +0300 Subject: Security: Refuse form posts a browser marks as coming from another origin Every blog is a subdomain of the root domain, which makes a blog page "same-site" to the dashboard: SameSite=Lax sends the session cookie with a form a blog's custom HTML submits to example.com. The HMAC token already stops those, but the login form had nothing (login CSRF), and a second, independent check costs one header lookup. A POST whose Sec-Fetch-Site is cross-site or same-site is now refused in guardPOST and on login; old browsers without the header keep working under the token alone. Co-Authored-By: Claude Opus 5 Claude-Session: https://claude.ai/code/session_01Sd8UPWrvyYCLj97JexNw3A --- internal/web/server.go | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) (limited to 'internal/web/server.go') diff --git a/internal/web/server.go b/internal/web/server.go index f768ebd..5a6ac4e 100644 --- a/internal/web/server.go +++ b/internal/web/server.go @@ -214,6 +214,10 @@ func (s *Server) guardPOST(w http.ResponseWriter, r *http.Request, limit int64) if r.Method != http.MethodPost { return true } + if crossSiteForm(r) { + s.fail(w, r, http.StatusForbidden, s.tr(r, "Form expired or invalid. Go back, reload the page and try again.")) + return false + } u := currentUser(r) // Cap the request body before any form parsing (uploads included). r.Body = http.MaxBytesReader(w, r.Body, limit+1<<20) @@ -233,6 +237,19 @@ func (s *Server) guardPOST(w http.ResponseWriter, r *http.Request, limit int64) return true } +// crossSiteForm says a browser sent the POST from another origin. Blogs are +// subdomains of the root domain, so a blog page is "same-site" to the +// dashboard and SameSite=Lax would send the cookie along; only the dashboard +// itself ("same-origin") or a typed address ("none") may post. Browsers too +// old to send the header pass, and the CSRF token still covers them. +func crossSiteForm(r *http.Request) bool { + switch r.Header.Get("Sec-Fetch-Site") { + case "cross-site", "same-site": + return true + } + return false +} + // requireAuth is for management pages outside a blog (dashboard, password, // admin): logged in, small forms only. func (s *Server) requireAuth(next http.HandlerFunc) http.HandlerFunc { -- cgit v1.2.3