Go language semantics and standard-library defaults that compile cleanly but produce exploitable behavior: discarded errors, integer truncation, the wrong template or JSON API, decoded URL fields, string-built SQL and unbounded HTTP clients.
How it works
None of these need unsafe. They come from Go doing exactly what the spec says while the developer assumes otherwise. Trail of Bits reports that the areas where static tools raise warnings “typically lead to exploitable functionality”.
Patterns
Error handling and scoping
:= redeclaration drops errors. A multi-variable short declaration may reuse an existing err if at least one LHS name is new, so the compiler raises no “unused” error:
aOK, err := A() // err from A is never checkedbOK, err := B() // silently overwrites itif err != nil { ... }
go vet and errcheck miss this. staticcheck (SA4006) and ineffassign catch it.
Accidental shadowing in an inner block (if, for) creates a new err or variable, so the outer one is never set. go tool vet -shadow reports some cases. 50 Shades notes it doesn’t catch all of them.
Logged but not returned. In the Kubelet/cAdvisor GetDirDiskUsage bug, a stdout read error was klog.Errorf’d and execution continued to strings.Fields(stdout)[0], which panicked with an index out of range. See Go Panics and Concurrency Bugs.
Typed-nil interfaces. An error interface holding a nil pointer is non-nil (listed in Unexpected Go and 50 Shades). if err != nil then takes the failure branch, or a custom check passes when it shouldn’t.
Integer width
int is platform-sized. Parsing with strconv.Atoi and then narrowing truncates silently. TOB-K8S-015 (Kubernetes kubectl expose):
port, err = strconv.Atoi(params["port"]) // should be ParseUint(s, 10, 16)ContainerPort: int32(port) // 4294967377 wraps
To find these, review every intN(x)/uintN(x) conversion after parsing, and build and test on 32-bit targets too.
Output encoding: templates and JSON
text/template does no contextual escaping. Use html/template for HTML, which is context-aware: it encodes script content and renders maps as JSON in JS context. Snyk adds that io.WriteString of user data with an unset Content-Type is the other XSS path. Template-level code execution is covered in Go Template SSTI.
encoding/json HTML-escapes <, > and & by default (<). Only Encoder.SetEscapeHTML(false) disables it, and json.Marshal can’t. 50 Shades calls this an incomplete XSS defense: it is one context’s encoding applied everywhere. Don’t treat it as output encoding for HTML attributes or JS.
Numbers decode to float64 inside interface{}, so result["status"].(int) panics. That gives an attacker-triggerable panic on an unchecked type assertion. Use typed structs or Decoder.UseNumber().
Zero-value defaults. A missing JSON field decodes to the zero value. If an iota enum’s 0 is a meaningful state (StatusOpen), an omitted field silently means “open”. Make 0 the Unknown or invalid value. The same applies to bool authz flags.
json.Unmarshal merges into existing structs and slices but not map values (Unexpected Go). Reusing a decode target across requests can leak earlier fields.
Unexported fields aren’t marshalled. Exported ones are, which is a mass-exposure risk when whole structs are serialized. See Excessive Data Exposure.
net/url
URL.Path is stored decoded: /x/y%2Fz gives Path=/x/y/z and RawPath=/x/y%2Fz. Authorization or routing on Path can’t tell an encoded slash from a real one. Use EscapedPath() when it matters. The same is true of Fragment and EscapedFragment().
URL.Query() silently drops malformed pairs. Use ParseQuery to get the error. An unencoded ; in a query is treated as invalid, which can cause front-end/back-end parameter disagreement. See URL Parser Differentials and Server-Side Parameter Pollution.
JoinPath cleans ./ and ../ but expects already-escaped elements. Joining raw user input is not a traversal guard.
SQL and command construction
Tutorial-grade Go APIs build SQL with fmt.Sprintf:
fmt.Sprintf("UPDATE users SET name='%s', age=%d WHERE id=%d", u.Name, u.Age, u.ID)
This is classic SQL Injection. Use db.Exec("... WHERE id = ?", id) placeholders. sqlvet (see Go Security Testing Tools) statically checks SQL strings at build time.
Subshells: prefer native Go over os/exec. If you must shell out, sanitize the inputs, and treat the output as data that may leak system details (Snyk). See Command Injection and Argument Injection.
HTTP client
http.Get/http.Post use http.DefaultClient, which is &Client{} with no timeout. Calls to a slow upstream (or attacker-controlled host in SSRF) hold goroutines indefinitely. Construct &http.Client{Timeout: ...}.
Always defer resp.Body.Close(), but only after checking err. On some redirect errors both resp and err are non-nil. Unclosed bodies leak connections. Use req.Close = true or Transport{DisableKeepAlives: true} for one-shot clients.
Crypto and secrets
Prefer stdlib crypto/* over third-party crypto, which may not have the same audit depth (Snyk).
Timing-safe comparison: don’t compare tokens or MACs with bytes.Equal, bytes.Compare or reflect.DeepEqual. Use crypto/subtle.ConstantTimeCompare.
bcrypt cost:golang.org/x/crypto/bcrypt.GenerateFromPassword salts automatically, but tutorials pass bcrypt.MinCost (4). Review for MinCost and use at least DefaultCost. Verify with CompareHashAndPassword.
reflect misuse panics at runtime on unsettable values. Snyk advises using it sparingly in security paths.