GUIDE · GO WEB SECURITY · 33 MIN READ
Go's built-in web defences in 2026: CrossOriginProtection, os.Root, body limits, timeouts and govulncheck
Go 1.27's built-in web defences, tested: CrossOriginProtection, os.Root, MaxBytesReader, server timeouts, html/template, crypto/rand and govulncheck.
Edition: · Practical guide. Added to the archive on the publication date above. Sources and worked examples below.

What this edition covers and tested
Go's standard library has become a capable first line of defence for web services. Go 1.24 added os.Root for directory-confined file access and crypto/rand.Text for secrets. Go 1.25 added http.CrossOriginProtection, a defence against cross-site request forgery that needs neither tokens nor cookies. Go 1.26 and 1.27 tightened parsing limits, TLS defaults and template escaping. Older pieces such as http.MaxBytesReader, the http.Server timeouts and html/template still do most of the daily work, but only where they are switched on. Several of them are opt-in, and the zero http.Server has no timeouts at all.
This is the 22 November 2026 edition, researched and first published on 3 December 2026. Every behaviour below was checked in an original lab built with Go 1.27.3 on darwin/arm64. It passed gofmt, go vet ./... and go test -race -count=3 ./... with 23 top-level tests. The tests show CrossOriginProtection rejecting a cross-site POST while allowing same-origin requests and safe methods, os.Root refusing ../ and three kinds of symlink escape that os.ReadFile follows, http.MaxBytesReader returning *http.MaxBytesError, html/template escaping one hostile string five different ways, tokens compared through crypto/subtle, and server timeouts closing a slowloris connection after exactly five virtual seconds under testing/synctest. Mutated copies of the lab confirmed that each test fails when its defence is removed. The lab was also scanned once with govulncheck, and its real output is shown below.
As of 3 December 2026, the Go release history lists Go 1.27.4, released on 10 November 2026, as the newest release. It includes security fixes to cgo, the go command, the compiler, the linker and net/http. The lab was tested with 1.27.3 as planned, govulncheck flagged exactly that gap, and the tests also pass on 1.27.4. Build production binaries with 1.27.4 or later.
The guide stays within the standard library and the Go toolchain. Authentication, authorization and TLS configuration need their own treatment; the Secure Go services course covers those alongside XSS, CSRF, sessions, path traversal and supply-chain checks.
CrossOriginProtection reads signals the browser already sends
Cross-site request forgery works because a browser attaches a site's cookies to requests that another site causes it to send. The classic defence is a secret token in every form. Go 1.25 added a different one to net/http: CrossOriginProtection rejects non-safe cross-origin browser requests using the browser's Fetch metadata. Its release note stresses that it needs no tokens or cookies.
The decision, as documented on the type and implemented in net/http, has four steps:
GET,HEADandOPTIONSare safe methods and always pass. The documentation states the condition this depends on: applications must not perform state-changing actions in response to them.- If
Sec-Fetch-Siteissame-originornone, the request passes. Browsers sendnonefor user-originated requests such as a typed URL or a bookmark. Every other value,same-siteincluded, is rejected unless an exemption applies. - Without
Sec-Fetch-Site, the host in theOriginheader is compared with the request'sHost. A match passes and a mismatch is rejected. - With neither header, the request is assumed to be same-origin or not from a browser, and it passes.
Wrapping a handler takes a few lines. The lab's helper also loads trusted origins and bypass patterns, which the next section covers:
// CrossOrigin wraps h in net/http's CrossOriginProtection (Go 1.25 and
// later). Browser requests with unsafe methods from another origin get 403.
//
// trusted lists exact origins, such as "https://admin.example.com", that may
// send such requests anyway. bypass lists ServeMux patterns, such as
// "POST /hooks/{provider}", for endpoints that authenticate every request in
// another way, for example with a signed payload. AddInsecureBypassPattern
// panics on a malformed pattern, so bypass should come from code, not input.
func CrossOrigin(h http.Handler, trusted, bypass []string) (http.Handler, error) {
cop := http.NewCrossOriginProtection()
for _, origin := range trusted {
if err := cop.AddTrustedOrigin(origin); err != nil {
return nil, err
}
}
for _, pattern := range bypass {
cop.AddInsecureBypassPattern(pattern)
}
return cop.Handler(h), nil
}The lab's table test sends fourteen requests through a mux wrapped this way. A cross-site POST and a cross-site DELETE get 403 with the body cross-origin request detected from Sec-Fetch-Site header. A same-origin POST, a POST marked none, and cross-site GET, HEAD and OPTIONS requests get 200. A POST from a sibling subdomain, which browsers mark same-site, is rejected: unlike SameSite cookies, this check treats blog.example.com and example.com as different. A POST with no Sec-Fetch-Site whose Origin names another host is rejected with the longer message cross-origin request detected, and/or browser is out of date: Sec-Fetch-Site is missing, and Origin does not match Host. The same request with a matching Origin passes, and so does a POST with neither header, which is what curl or a server-to-server client sends.
That last case is a design decision rather than a gap. A forged request needs a victim's browser to carry the victim's cookies, and a client that omits the browser headers is not a browser acting for somebody else. Requests from non-browser clients still need their own authentication; this check does not provide it. When a request is rejected, the default response is a plain-text 403. SetDenyHandler replaces it, for example with a JSON error, and Check returns the reason as an error if you want to log it.
Trusted origins and bypass patterns
CrossOriginProtection has two escape hatches, and both deserve a code review every time they change.
AddTrustedOrigin allows requests whose Origin header exactly equals the given value, for example a separate admin front end on another host. It validates its argument. The lab gets scheme is required for example.com, and path, query, and fragment are not allowed for both https://example.com/ and https://example.com/path. The trailing-slash case catches anyone who pastes a URL instead of an origin. A trusted origin passes even when Sec-Fetch-Site says cross-site.
AddInsecureBypassPattern takes a ServeMux pattern, such as POST /hooks/{provider}, and lets every matching request through. The name is deliberate. Use it for endpoints that authenticate each request in another way, such as webhooks with a signed payload, and never to silence a 403 from your own front end. It panics if a pattern is malformed or conflicts with one already registered, so patterns belong in code as constants.
Bypass matching received a security fix early on. In Go 1.25.0 a bypass pattern could exempt more requests than intended, and because the original path was forwarded, a different handler could then serve the request without protection. That was GO-2025-3955 (CVE-2025-47910), fixed in Go 1.25.1. The documentation now states that only requests matching a pattern directly are permitted, and that requests ServeMux would redirect after cleaning the path or adding a trailing slash are not. The lab pins both sides: a cross-site POST to /hooks/github passes, and a cross-site POST to /hooks/github/../../admin gets 403.
Three deployment conditions decide whether the check sees the headers it relies on:
- HTTPS everywhere. The OWASP CSRF cheat sheet notes that browsers send Fetch metadata only to potentially trustworthy URLs, which in practice means HTTPS and localhost. Over plain HTTP the check falls back to comparing
OriginwithHost. - HSTS.
Hostcarries no scheme, so the fallback cannot tell an HTTP page from an HTTPS one on the same host. The source comments say the code deliberately fails open there, because all modern browsers have sentSec-Fetch-Sitesince 2023, and name HTTP Strict Transport Security as the mitigation. - Proxies that pass headers through. OWASP warns that intermediaries may remove or modify
OriginandSec-*headers. Behind a reverse proxy, also check thatHostreaches Go as the browser sent it, or legitimate requests from older browsers will fail theOrigincomparison.

Where CSRF tokens and SameSite cookies still fit
CrossOriginProtection does not make the older defences wrong. It changes which one carries the weight.
The OWASP CSRF Prevention Cheat Sheet lists Go's type among the built-in defences to prefer, saying that from Go 1.25 developers can rely on it for a Fetch-Metadata-based defence in the standard library. The same document still asks for at least one defence-in-depth measure and is specific about what the SameSite cookie attribute does not cover. Two of its limitations matter here. First, Lax still sends the cookie on top-level navigations that use safe methods, so any state change reachable through a GET defeats it; MDN's definition of Lax describes the same exception. Second, SameSite is scoped to the registrable domain, not the origin. A cookie set by app.example.com accompanies requests started on any other example.com subdomain, which turns a compromised or taken-over subdomain into a foothold.
For a Go service that renders its own pages, the layers fit together like this:
CrossOriginProtectionaround the whole mux as the primary CSRF defence. Because it rejectssame-siterequests, it closes the sibling-subdomain gap that SameSite leaves open.- Session cookies with
SameSite=Lax, orStrictwhere people never need to arrive logged in from links on other sites, plus the__Host-prefix covered later, as defence in depth. - No state changes behind GET, HEAD or OPTIONS. Both defences assume it.
- Synchronizer tokens or signed double-submit cookies only where you must serve browsers that send neither
Sec-Fetch-SitenorOrigin, or where a framework already provides them. OWASP notes thatSec-Fetch-*headers have been supported in all major browsers since March 2023.
An API that never authenticates with cookies or other credentials the browser attaches by itself gives a forged request nothing to borrow. Wrapping it costs one line, though, and still protects it on the day someone adds cookie sessions.
Confine file access with os.Root
Path traversal is the oldest bug in file-handling code: a name such as ../../etc/passwd, joined to a base directory, opens something outside it. The usual guard is lexical. filepath.IsLocal, added in Go 1.20, rejects absolute names, empty names, names that climb out with .. and, on Windows, reserved names. Its documentation also says what it cannot see. It is a purely lexical operation and does not account for symbolic links.
The lab makes that limit concrete. Its test directory holds a legitimate file, a symlink to it, and three links that lead out: escape points to ../secret.txt, absolute points to the secret by absolute path, and outside points to a sibling directory. filepath.IsLocal accepts all three names, and os.ReadFile(filepath.Join(dir, name)) returns the secret through each of them. Whenever users can create files, and extracting an uploaded archive counts, a lexical check is not enough. The Go blog's post on traversal-resistant file APIs adds that resolving links first with filepath.EvalSymlinks and then opening the result is still exposed to time-of-check/time-of-use races, because an attacker can swap a path component between the check and the open.
Go 1.24 added os.Root. os.OpenRoot opens a directory, and methods on the returned Root take names relative to it and refuse any that refer to a location outside it, including through symlinks. On Unix it is built on the openat family of system calls and holds a descriptor for the directory, so names are resolved component by component instead of being checked as strings. The lab wraps it in a small type:
// Files stores and serves user files beneath one directory. Every access goes
// through an os.Root (Go 1.24 and later), so names containing "../" and
// symbolic links that lead outside the directory are refused by the lookup
// itself rather than by string checks on the name.
type Files struct {
root *os.Root
limit int64 // maximum bytes per uploaded file
}
// OpenFiles opens dir for storing files of at most limit bytes each.
func OpenFiles(dir string, limit int64) (*Files, error) {
root, err := os.OpenRoot(dir)
if err != nil {
return nil, err
}
return &Files{root: root, limit: limit}, nil
}
// Close releases the directory handle.
func (f *Files) Close() error { return f.root.Close() }
// Read returns the contents of name, a path relative to the directory.
func (f *Files) Read(name string) ([]byte, error) { return f.root.ReadFile(name) }
// Save writes data to name, creating parent directories inside the root.
func (f *Files) Save(name string, data []byte) error {
if dir := path.Dir(name); dir != "." {
if err := f.root.MkdirAll(dir, 0o750); err != nil {
return err
}
}
return f.root.WriteFile(name, data, 0o640)
}Every escape in the lab fails with a *fs.PathError whose text ends in path escapes from parent: ../secret.txt, escape, absolute, outside/key.txt, outside/ and the secret's absolute path. Writes are refused the same way. Save("outside/pwned.txt") fails with mkdirat outside: statat outside: path escapes from parent, and the test confirms that nothing appeared in the sibling directory and that the secret was not overwritten through the escape link. Links that stay inside, such as alias, work normally.
Names are resolved with the platform's own semantics rather than cleaned first. On macOS, sub/../hello.txt failed with no such file or directory because sub does not exist; the blog notes that Windows would open hello.txt in that case. For a single open there is os.OpenInRoot(dir, name), which opens the root, opens the file inside it and closes the root.
The Root documentation lists its limits. It does not prevent traversal of filesystem boundaries, Linux bind mounts, /proc special files or access to Unix device files. Symbolic links must not be absolute. On Unix, Root.Chmod, Root.Chown and Root.Chtimes can act on a link if a regular file is swapped for one during the call. With GOOS=js, it cannot ensure that operations stay inside the root. The blog's rule of thumb makes a good review prompt: code that calls filepath.Join to combine a fixed directory with an externally provided name should probably use os.Root instead.

Serve and store user files through the root
Root.FS returns an fs.FS with the same guarantees, and since Go 1.25 it also implements fs.ReadLinkFS. That makes the download side a single http.FileServerFS call. Go 1.25 also added the methods the upload side needs, among them MkdirAll, ReadFile, WriteFile, Rename, RemoveAll, Symlink and Link; the Go 1.24 type started with Open, Create, OpenFile, OpenRoot, Mkdir, Remove, Stat and Lstat. The 1.26 and 1.27 release notes add no further methods.
// Routes registers uploads at PUT /files/{name...} and downloads under
// GET /files/. Downloads use the root's fs.FS, which also refuses escapes.
func (f *Files) Routes(mux *http.ServeMux) {
mux.Handle("GET /files/", http.StripPrefix("/files/", http.FileServerFS(f.root.FS())))
mux.HandleFunc("PUT /files/{name...}", f.put)
}
func (f *Files) put(w http.ResponseWriter, r *http.Request) {
data, err := io.ReadAll(http.MaxBytesReader(w, r.Body, f.limit))
if err != nil {
http.Error(w, "file too large", http.StatusRequestEntityTooLarge)
return
}
// PathValue is already unescaped: "..%2Fx" arrives here as "../x".
if err := f.Save(r.PathValue("name"), data); err != nil {
http.Error(w, "cannot store file", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusCreated)
}The comment in put records a detail the lab checks. ServeMux cleans paths and redirects requests with .. segments, but its documentation also says that paths are unescaped segment by segment for matching, so %2F stays inside a segment. A request for /files/..%2Fpwned.txt therefore matches {name...} without any redirect, and r.PathValue("name") returns the decoded ../pwned.txt. Any handler that joins a path value onto a directory receives traversal strings this way. Here the root refuses the write, the handler answers 400, and the test confirms that no pwned.txt appeared outside the directory. An upload larger than the 1 KiB test limit gets 413 from the same MaxBytesReader pattern described in the next section.
On the download side, GET /files/escape through the root's file system returns 500. The escape error is neither fs.ErrNotExist nor fs.ErrPermission, which FileServer maps to 404 and 403, so it falls through to 500. The secret never appears in the body. If 500s in your logs are a problem, wrap the file system and translate the error to 404 yourself. The negative control is the documented weakness of http.Dir: http.FileServer(http.Dir(dir)) answers GET /escape with 200 and the secret. Its documentation warns that Dir follows symlinks out of the tree and serves files whose names start with a period, such as .git, and the os.DirFS documentation points to Root.FS for the same reason. Note that os.Root confines paths but does not hide dot-files either; in the lab, GET /files/.env returned 200. Keep secrets out of served directories.
os.Root has also been patched several times, which is a reason to stay on current point releases. The Go vulnerability database lists an escape to the parent directory through a name ending in ../ (fixed in 1.24.3), directory listings that returned FileInfo for files outside the root (1.25.8 and 1.26.1), a Root.Chmod race on Linux (1.25.9 and 1.26.2), a symlink followed outside the root when the name ends in / (1.25.12, 1.26.5 and 1.27.0-rc.2), and Windows junctions followed by Mkdir and MkdirAll (1.26.9 and 1.27.2). The lab's outside/ case is the trailing-slash one.
Cap request bodies with MaxBytesReader
A request body is a stream of whatever size the client chooses to send, and json.NewDecoder(r.Body).Decode or io.ReadAll(r.Body) will read until the client stops. http.MaxBytesReader wraps the body so that a read beyond the limit fails with a *http.MaxBytesError, whose Limit field carries the limit. Its documentation names the purpose, preventing clients from accidentally or maliciously sending a large request and wasting server resources, and adds that it tells the ResponseWriter to close the connection after the limit is reached, where it can.
// DecodeJSON decodes one JSON value from the request body into dst, reading
// at most limit bytes. It answers 413 when the body is too large and 400 when
// it is malformed, and reports whether the caller should continue.
func DecodeJSON(w http.ResponseWriter, r *http.Request, limit int64, dst any) bool {
dec := json.NewDecoder(http.MaxBytesReader(w, r.Body, limit))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
var tooBig *http.MaxBytesError
if errors.As(err, &tooBig) {
msg := fmt.Sprintf("request body exceeds %d bytes", tooBig.Limit)
http.Error(w, msg, http.StatusRequestEntityTooLarge)
return false
}
http.Error(w, "malformed JSON body", http.StatusBadRequest)
return false
}
return true
}Match the error with errors.As, not by its text. The message http: request body too large is kept stable for compatibility, but the type is the contract. In the lab, io.Copy from a 2,000-byte body limited to 1,000 bytes copied exactly 1,000 bytes and then returned the error with Limit set to 1000. Through DecodeJSON with a 1 KiB limit, a small object returned 200, a 2 KiB object returned 413 with request body exceeds 1024 bytes, and both a truncated object and an unknown field returned 400. Over a real HTTP/1 exchange on the in-memory test server, the 413 response also carried Connection: close, which the Go client reports as resp.Close, so the client cannot keep streaming the rest of its body on that connection.
A few related limits are easy to misremember:
Request.ParseFormcaps a URL-encoded body at 10 MB only if the body has not already been limited byMaxBytesReader. Set your own, smaller limit first.Request.ParseMultipartForm(maxMemory)limits how much of the file parts is held in memory. The remainder goes to temporary files on disk, somaxMemoryis not a limit on the request size.http.MaxBytesHandler(h, n)applies the same wrapper to every request a handler receives, which suits routes whose bodies share one limit.- A size limit bounds memory, not time. A client can send a small body very slowly; the server's
ReadTimeouthandles that.
Go 1.27.4 fixed a crash in exactly this area. When a MaxBytesReader limit was exceeded on an HTTP/1 server, the Connection: close header was set without synchronization, so a server whose handler read the body concurrently with writing response headers could crash with a runtime panic. That is GO-2026-6859 (CVE-2026-97054), fixed in 1.27.4 and 1.26.11. The lab reads the body before writing, so its tests pass on 1.27.3, but the fix is reason enough to upgrade. Validating what the bytes contain, such as rejecting trailing data after one JSON document, is covered in Go streaming I/O: EOF, byte limits and JSON boundaries.
Server timeouts against slowloris
A slowloris client opens connections and sends each request's headers a few bytes at a time, or never finishes them, so that every connection stays occupied. A Go server does not run out of threads the way a thread-per-connection server does, but each open connection still holds a goroutine, buffers and a file descriptor, and descriptors are a fixed budget.
http.ListenAndServe(addr, handler) builds &Server{Addr: addr, Handler: handler} and serves it. Every timeout on that server is zero, and zero means no timeout. The lab sets each limit explicitly:
// HardenServer sets explicit limits on srv. The zero http.Server, which is
// what http.ListenAndServe uses, has no timeouts at all.
func HardenServer(srv *http.Server) {
srv.ReadHeaderTimeout = 5 * time.Second // slow or unfinished headers
srv.ReadTimeout = 30 * time.Second // headers plus the whole body
srv.WriteTimeout = 30 * time.Second // from end of headers to end of response
srv.IdleTimeout = 2 * time.Minute // keep-alive wait for the next request
srv.MaxHeaderBytes = 64 << 10 // request line plus headers
}The fields interact, and their documentation is worth reading once:
- ReadHeaderTimeout bounds reading the request line and headers. If it is zero,
ReadTimeoutis used instead, and if both are zero there is no limit. After the headers arrive, the connection's read deadline is reset so that the handler can decide what is too slow for the body. - ReadTimeout bounds reading the entire request, body included. The documentation notes that it does not let handlers make per-request decisions and that most users will prefer
ReadHeaderTimeout; setting both is valid. A handler can move its own read deadline withhttp.NewResponseController(w).SetReadDeadline, although a deadline that has already passed cannot be extended. - WriteTimeout bounds writing the response and is reset whenever a new request's headers are read. Streaming responses, such as server-sent events, need a later or cleared deadline per request through
ResponseController.SetWriteDeadline. - IdleTimeout bounds the wait for the next request on a keep-alive connection, and falls back to
ReadTimeoutwhen zero. - MaxHeaderBytes bounds the request line plus headers. The default,
DefaultMaxHeaderBytes, is 1 MB. Go 1.27 addsMaxHeaderValueCount, whose default,DefaultMaxHeaderValueCount, is 500 header values.
The numbers in HardenServer are a starting point for a JSON API, not a rule; upload and streaming routes need their own budgets, set per request. http.TimeoutHandler complements the server limits by bounding a handler's running time and answering 503 when it expires, but it does not support the Flusher or Hijacker interfaces. How these limits interact with shutdown and Kubernetes grace periods is covered in Go graceful shutdown: HTTP, workers and Kubernetes.
Prove the timeouts in virtual time
Timeout tests used to mean real sleeps and generous margins. Go 1.27 adds httptest.NewTestServer, which by default serves over an in-memory network that its documentation describes as suitable for testing/synctest, and registers its own cleanup. Inside a synctest bubble, time advances only when every goroutine in the bubble is durably blocked, so a five-second timeout takes no real time and can be measured exactly. The test client's transport dials the same in-memory network, which lets a test open a raw connection and send bytes that no well-behaved client would:
// rawConn opens a client connection to ts over httptest's in-memory network
// (Go 1.27), so the test can send bytes that no well-behaved client would.
func rawConn(t *testing.T, ts *httptest.Server) net.Conn {
t.Helper()
tr := ts.Client().Transport.(*http.Transport)
conn, err := tr.DialContext(t.Context(), "tcp", "example.com:80")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { conn.Close() })
return conn
}
func okHandler(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok") }
// A slowloris client sends a request line and some headers, then never sends
// the blank line that ends them. Time inside the bubble is simulated, so the
// test waits five virtual seconds, not real ones.
func TestReadHeaderTimeoutClosesSlowloris(t *testing.T) {
synctest.Test(t, func(t *testing.T) {
ts := httptest.NewTestServer(t, http.HandlerFunc(okHandler))
websafe.HardenServer(ts.Config)
conn := rawConn(t, ts)
start := time.Now()
io.WriteString(conn, "GET / HTTP/1.1\r\nHost: example.com\r\nX-Slow: 1\r\n")
conn.SetReadDeadline(start.Add(time.Hour))
_, err := conn.Read(make([]byte, 1))
if err != io.EOF {
t.Fatalf("read = %v, want io.EOF from the server closing the connection", err)
}
if elapsed := time.Since(start); elapsed != 5*time.Second {
t.Fatalf("server closed after %v, want exactly ReadHeaderTimeout (5s)", elapsed)
}
})
}The test passes with the elapsed virtual time equal to 5 seconds, not approximately 5. Three companion tests use the same technique:
- The zero
http.Serveris the negative control. The same half-finished request stayed open until the test's own one-hour read deadline expired, with no reaction from the server. - A client that sent its headers promptly and then one body byte per second saw the handler's body read fail after exactly 30 virtual seconds with
i/o timeout. In a copy of the lab withoutReadTimeout, but still withReadHeaderTimeout, the handler read all 1,000 bytes over 16 minutes 39 virtual seconds and got no error at all: a header timeout does nothing for the body. - A request with 502 header lines, 501 of them
X-Many: 1plusHost, drew431 Request Header Fields Too Largefrom a server with default settings, which is the Go 1.27 value-count limit at work.
Removing only ReadHeaderTimeout from HardenServer made the slowloris test fail with server closed after 30s, the documented fallback to ReadTimeout. Because nothing waits on the wall clock, go test -count=20 over the whole lab finished in under half a second. That is the practical payoff: limits that are tested on every run stay set.
html/template escapes by context
html/template and text/template share one API, and that is the trap: changing an import is all it takes to turn escaping off. The html/template documentation describes its model. Template authors are trusted and the data passed to Execute is not, and each action is escaped for the context it appears in, whether that is HTML text, an attribute, a URL, JavaScript or CSS.
The lab renders one hostile name into five contexts:
// profileSource puts the same values into five contexts: element text, a
// quoted attribute, a URL attribute, a URL query and a script.
const profileSource = `<h1>{{.Name}}</h1>
<a href="{{.Website}}" title="{{.Name}}">site</a>
<a href="/search?q={{.Name}}">search</a>
<script>const name = {{.Name}};</script>
`
var profilePage = template.Must(template.New("profile").Parse(profileSource))
// RenderProfile writes the page with html/template, which escapes each value
// for the context it lands in.
func RenderProfile(w io.Writer, p Profile) error {
return profilePage.Execute(w, p)
}With Name set to </script><script>alert(1)</script>" onmouseover="alert(2) and Website set to javascript:alert(3), the test logged this HTML:
<h1></script><script>alert(1)</script>" onmouseover="alert(2)</h1>
<a href="#ZgotmplZ" title="</script><script>alert(1)</script>" onmouseover="alert(2)">site</a>
<a href="/search?q=%3c%2fscript%3e%3cscript%3ealert%281%29%3c%2fscript%3e%22%20onmouseover%3d%22alert%282%29">search</a>
<script>const name = "\u003c/script\u003e\u003cscript\u003ealert(1)\u003c/script\u003e\" onmouseover=\"alert(2)";</script>Each context got different treatment. In element text and in the title attribute the value became HTML entities, so neither the tag nor the quote can act. The javascript: URL in href became #ZgotmplZ, the marker the package substitutes for a value it will not allow in a URL attribute; the documentation explains that only allowed protocols such as http: pass. In the query string the name was percent-encoded. Inside the script element it became a quoted JavaScript string with < and > written as < and >, so it cannot close the element. The same source parsed by text/template emitted the raw <script> tags and the javascript: URL unchanged; the lab keeps that as a negative control.
The typed strings template.HTML, template.JS, template.URL and their relatives switch escaping off for one value. They are assertions that the content is already safe, and the lab confirms that template.HTML with an <img onerror> payload is written out verbatim. Treat every conversion to one of these types as a security review point, and never apply one to user input.
The escaper itself keeps being refined. Go 1.27 escapes URLs in the url= part of a meta tag's content attribute, the form <meta http-equiv="refresh"> uses, controlled by the htmlmetacontenturlescape GODEBUG setting and backported to 1.25.8 and 1.26.1. The lab's meta refresh with a javascript: URL rendered as url=#ZgotmplZ. The vulnerability database lists several more html/template fixes in 2026 point releases, the most recent two in Go 1.27.2 and 1.26.9, both about JavaScript context tracking. The template and a main that prints its output need only the standard library, so you can paste them into the Playground, which compiles and runs Go in the browser, and try your own hostile strings.
Random tokens, constant-time checks and session cookies
Session identifiers, API keys and reset links need unpredictable values, and Go 1.24 made the safe choice the short one. crypto/rand.Text returns a string in the RFC 4648 base32 alphabet carrying at least 128 bits of randomness, which its documentation calls enough to prevent brute-force guessing and to make collisions vanishingly unlikely. In Go 1.27.3 the string is 26 characters long. The same release guaranteed that crypto/rand.Read does not fail: it always returns a nil error, and if reading from Reader ever does fail, the program crashes irrecoverably instead of carrying on with weak bytes. The release notes name the exception, Linux kernels before 3.17, where the default Reader still opens /dev/urandom and may fail.
// NewToken returns a secret for a session, API key or reset link.
// crypto/rand.Text (Go 1.24 and later) returns 26 base32 characters carrying
// at least 128 bits of randomness, and crypto/rand no longer returns errors.
func NewToken() string { return rand.Text() }
// HashToken is what the server stores instead of the token, so a leaked
// table of digests does not hand out working credentials.
func HashToken(token string) [sha256.Size]byte {
return sha256.Sum256([]byte(token))
}
// TokenMatches reports whether presented is the token whose digest is stored.
// It compares two fixed-length digests with crypto/subtle, so the time taken
// does not depend on where the inputs differ or on the presented length.
func TokenMatches(presented string, stored [sha256.Size]byte) bool {
got := HashToken(presented)
return subtle.ConstantTimeCompare(got[:], stored[:]) == 1
}Storing a SHA-256 digest instead of the token means a leaked table of digests contains no working credentials. That suits random tokens with 128 bits of entropy; user-chosen passwords are a different problem and need a deliberately slow password hash.
The comparison uses crypto/subtle.ConstantTimeCompare, whose running time depends on the length of its inputs but not on their contents. Its documentation adds that it returns 0 immediately when the lengths differ, which is why the lab compares two 32-byte digests rather than the raw strings: the presented length cannot change the timing. For MACs, crypto/hmac.Equal does the same job. The lab's tests check correctness only. The issued token matches, while an empty, shortened, lengthened, lower-cased or different token does not. No unit test can show that a comparison takes constant time, so the review checklist has to catch == on secrets. On arm64, subtle.WithDataIndependentTiming, added in Go 1.24, also enables the processor's data-independent timing mode for code already written to be constant-time; on other architectures it currently just runs the function.
Go 1.26 changed how crypto code meets tests. Most functions in crypto/... now ignore their random io.Reader parameter and always use the secure source, with the GODEBUG setting cryptocustomrand=1 as a temporary way back. For deterministic tests, testing/cryptotest.SetGlobalRandom(t, seed) replaces the randomness for one test, crypto/rand included. In the lab, seed 42 produced the same token twice. The setting affects the whole process, so it cannot be used in parallel tests.
The token travels in a cookie, and its attributes matter as much as its value:
// SessionCookie carries a session token. Browsers accept a cookie named with
// the __Host- prefix only if it is Secure, has Path=/ and has no Domain, which
// keeps it bound to this exact host.
func SessionCookie(token string, maxAge time.Duration) *http.Cookie {
return &http.Cookie{
Name: "__Host-session",
Value: token,
Path: "/",
MaxAge: int(maxAge / time.Second),
Secure: true, // never sent over plain HTTP
HttpOnly: true, // not readable from JavaScript
SameSite: http.SameSiteLaxMode, // not sent on cross-site subrequests
}
}http.SetCookie wrote __Host-session=TOKEN; Path=/; Max-Age=3600; HttpOnly; Secure; SameSite=Lax, and a copy of the lab without Secure failed the test. MDN describes what the prefix buys: a __Host- cookie is accepted only if it is set with Secure from an HTTPS page, has no Domain attribute and has Path=/, so it is sent only to the host that set it. HttpOnly keeps it away from JavaScript, and SameSite=Lax keeps it off cross-site subrequests and cross-site POSTs. On the parsing side, Go 1.26 added the httpcookiemaxnum setting: cookie parsing fails early when a header carries more than 3,000 cookies, a default that was backported to 1.25.2 and 1.24.8.
govulncheck reports what your code can reach
Every defence above is code in the standard library, and the vulnerability database shows that code being fixed: CrossOriginProtection in 1.25.1, os.Root five times, html/template repeatedly, and net/http in 1.27.4. The tool that connects those advisories to your program is govulncheck. As of 3 December 2026, the latest golang.org/x/vuln on the Go module proxy is v1.10.0, published on 17 November 2026.
govulncheck does more than list modules with known advisories. Its documentation says it uses static analysis of source code, or a binary's symbol table, to narrow reports to those that could affect the application, and the Go vulnerability management page says it surfaces only vulnerabilities your code transitively calls. Advisories for packages you import but do not call are summarised separately, and -show verbose lists them under package and module results.
The lab was scanned with the toolchain it was tested with:
$ go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./...
=== Symbol Results ===
Vulnerability #1: GO-2026-6859
HTTP/1 server crash due to MaxBytesReader header race in net/http
More info: https://pkg.go.dev/vuln/GO-2026-6859
Standard library
Found in: net/http@go1.27.3
Fixed in: net/http@go1.27.4
Example traces found:
#1: csrf.go:21:31: websafe.CrossOrigin calls http.CrossOriginProtection.AddInsecureBypassPattern
#2: csrf.go:16:33: websafe.CrossOrigin calls http.CrossOriginProtection.AddTrustedOrigin
#3: body.go:20:14: websafe.DecodeJSON calls http.Error
#4: files.go:47:12: websafe.Files.Routes calls http.ServeMux.Handle
#5: files.go:48:16: websafe.Files.Routes calls http.ServeMux.HandleFunc
#6: token.go:14:42: websafe.NewToken calls rand.Text, which eventually calls http.bodyEOFSignal.Read
#7: body.go:16:22: websafe.DecodeJSON calls json.Decoder.Decode, which eventually calls http.maxBytesReader.Read
Your code is affected by 1 vulnerability from the Go standard library.
This scan found no other vulnerabilities in packages you import or modules you
require.
Use '-show verbose' for more details.
exit status 3The finding is specific. Go 1.27.3's net/http contains GO-2026-6859, the MaxBytesReader header race described earlier, and the lab reaches it through ordinary calls such as http.Error, ServeMux.Handle and the maxBytesReader.Read behind DecodeJSON. Trace 6, websafe.NewToken calls rand.Text, which eventually calls http.bodyEOFSignal.Read, shows a documented limitation: calls through function pointers and interfaces are analysed conservatively, which can produce inaccurate call stacks, and crypto/rand reads through an io.Reader variable. The verbose run reported no other findings at package or module level. It also did not list the toolchain advisories for cgo, the go command, the compiler and the linker that 1.27.4 fixed, so read the release notes as well as the scan. With Go 1.27.4 first on PATH, the same scan printed No vulnerabilities found. and the lab's tests passed.
Three practical details came out of the runs:
- The Go version comes from PATH. For source scans, govulncheck uses the Go version of the
gocommand it finds onPATH. On the test machine, an installed govulncheck reportedGo: go1.24.2from an older system Go, whilego run golang.org/x/vuln/cmd/govulncheck@v1.10.0 -versionreported the Go 1.27.3 toolchain that ran it. Check theGo:line of-versionin CI. - Exit status. With findings, govulncheck exits unsuccessfully, with status 3 in this run, which fails a CI step; through
go run, the go command printsexit status 3and exits with 1. With-format json,sariforopenvexit exits 0 regardless, so a pipeline using those formats must inspect the results itself. - Binaries.
govulncheck -mode binarychecks a built executable using the configuration it was built with, which catches release builds made with a different toolchain from CI. Binary reports have no call stacks and may include code that is in the binary but unreachable.
Other security changes in Go 1.26 and 1.27
Several changes in the last two releases tighten defaults or add security-relevant APIs. Each item below comes from the release notes or the GODEBUG history on go.dev.
Go 1.26:
net/url.Parserejects malformed URLs with colons in the host, such ashttp://::1/orhttp://localhost:80:80/; bracketed IPv6 addresses are still accepted, andurlstrictcolons=0restores the old behaviour.- Query parsing stops at 10,000 parameters by default (
urlmaxqueryparams, backported to 1.25.6 and 1.24.12), alongside the 3,000-cookie limit. httputil.ReverseProxy.Directoris deprecated in favour ofRewrite, because a malicious client can remove headers that a Director adds by naming them as hop-by-hop.- On 64-bit platforms the runtime randomizes the heap base address at startup, which makes memory addresses harder for an attacker to predict in programs that use cgo.
crypto/tlsenables the hybrid post-quantum key exchanges SecP256r1MLKEM768 and SecP384r1MLKEM1024 by default,crypto/hpkeis new, andcrypto/rsadeprecates PKCS #1 v1.5 encryption padding. The experimentalruntime/secretpackage, behindGOEXPERIMENT=runtimesecret, erases temporaries used with secrets on Linux amd64 and arm64.
Go 1.27:
- The GODEBUG settings
tls10server,tls3des,tlsrsakex,tlsunsafeekmandx509keypairleafare removed. The Go 1.26 notes announced the consequence: TLS 1.2 as the default minimum version for clients and servers, no 3DES in the default cipher suites and no RSA-only key exchange by default now apply regardless of GODEBUG or go.mod version. Server.MaxHeaderValueCountand thehtml/templatemeta refresh escaping, both tested above.- The new
crypto/mldsapackage implements the ML-DSA signatures of FIPS 204, andcrypto/x509and TLS 1.3 accept them. go tool trace -http=:6060now listens on localhost only when given just a port, matchinggo tool pprof.
Point releases matter as much as major ones. Go 1.27.2 limited FileServer, ServeContent and ServeFile to 200 ranges in a Range header (httpservecontentmaxranges, also in 1.26.9) and fixed several HTTP/2 server denial-of-service and crash bugs, and 1.27.4 fixed the cgo and MaxBytesReader issues already described.
A checklist for Go web services
Use this list when reviewing a service or a pull request that touches HTTP handling. Each line corresponds to a test in the lab or a documented default.
- Toolchain: build with the newest patch release (Go 1.27.4 as of 3 December 2026), run
go run golang.org/x/vuln/cmd/govulncheck@v1.10.0 ./...in CI, check itsGo:line, and scan release binaries with-mode binary. - CSRF: wrap the whole mux in
http.CrossOriginProtection; keep GET, HEAD and OPTIONS free of side effects; serve only HTTPS with HSTS; review everyAddTrustedOriginandAddInsecureBypassPatterncall, and authenticate bypassed endpoints another way. - Cookies: name session cookies with the
__Host-prefix and setSecure,HttpOnly,Path=/andSameSite=LaxorStrict. - Files: open every externally named file through
os.Rootoros.OpenInRoot; serve user-writable directories withhttp.FileServerFS(root.FS()), neverhttp.Dir; remember that path values arrive decoded. - Bodies: read every body through
http.MaxBytesReaderorhttp.MaxBytesHandler; answer*http.MaxBytesErrorwith 413 viaerrors.As; set limits beforeParseFormandParseMultipartForm. - Server: never serve production traffic with
http.ListenAndServe; setReadHeaderTimeout,ReadTimeout,WriteTimeout,IdleTimeoutandMaxHeaderBytes, and adjust slow routes withhttp.ResponseController. - HTML: render HTML only with
html/template; search the code for conversions totemplate.HTML,template.JSandtemplate.URL, and justify each one. - Secrets: generate tokens with
crypto/rand.Text, store digests, and compare withcrypto/subtle.ConstantTimeCompareorcrypto/hmac.Equal. - Tests: test limits with
httptest.NewTestServerandtesting/synctest, and keep a negative control that shows the attack succeeding without the defence.
The websafe folder in this edition's lab archive contains every example in this guide. Run go test -race -count=3 ./... inside it, then delete one defence, such as the ReadHeaderTimeout line or the cop.Handler wrapper, and watch which test fails.
Primary sources & editorial method
We checked these primary references on 3 December 2026. Release facts are attributed; recommended workflows and examples are GopherForge analysis. Illustrations are conceptual, not vendor screenshots or benchmarks.
- Go 1.24 Release Notes
- Go 1.25 Release Notes
- Go 1.26 Release Notes
- Go 1.27 Release Notes
- Go release history
- Go, Backwards Compatibility, and GODEBUG
- Package net/http (CrossOriginProtection, MaxBytesReader, Server, Cookie)
- Package net/http/httptest (NewTestServer)
- Package os (Root, OpenInRoot, DirFS)
- Package path/filepath (IsLocal)
- Traversal-resistant file APIs (The Go Blog)
- Package html/template
- Package crypto/rand
- Package crypto/subtle
- Package testing/synctest
- Package testing/cryptotest
- govulncheck command documentation
- Go Vulnerability Management
- GO-2026-6859: HTTP/1 server crash due to MaxBytesReader header race
- GO-2025-3955: CrossOriginProtection insecure bypass patterns
- GO-2026-4403: Improper access to parent directory of root
- GO-2026-4602: FileInfo can escape from a Root
- GO-2026-4864: Root escape on Linux via Root.Chmod
- GO-2026-4970: Root escape via symlink plus trailing slash
- GO-2026-6604: Root.Mkdir(All) can follow junctions on Windows
- GO-2026-6599: html/template context tracking on consecutive expressions
- GO-2026-6600: html/template yield as regexp preceder
- GO-2026-6603: HTTP/2 server memory exhaustion due to Trailer headers
- OWASP Cross-Site Request Forgery Prevention Cheat Sheet
- MDN: Sec-Fetch-Site
- MDN: Set-Cookie (SameSite and cookie prefixes)