# Go Secure Coding Pitfalls > 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: ```go aOK, err := A() // err from A is never checked bOK, err := B() // silently overwrites it if 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`): ```go 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`: ```go 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. ## Review checklist - [ ] `staticcheck` / `ineffassign` clean (catches `:=` error overwrite) - [ ] No narrowing cast after `strconv.Atoi`/`ParseInt` without a bitSize - [ ] HTML rendered via `html/template` only, with `Content-Type` set explicitly - [ ] JSON decoded into typed structs, and every type assertion uses `v, ok :=` - [ ] Enum and flag zero values are safe defaults - [ ] Path authz uses `EscapedPath()` or normalizes consistently - [ ] No `Sprintf` into `Query`/`Exec`; no `exec.Command("sh", "-c", ...)` with input - [ ] Every outbound `http.Client` has a `Timeout` - [ ] Secret compares use `subtle.ConstantTimeCompare`; bcrypt cost is at least the default ## Related - [[Go Security]] (hub) · [[Go Panics and Concurrency Bugs]] · [[Go unsafe and cgo]] · [[Go Security Testing Tools]] - [[Go Template SSTI]] · [[Cross-Site Scripting]] · [[SQL Injection]] · [[Mass Assignment]] ## Sources - [[raw/blog.trailofbits.com/security-assessment-techniques-for-go-projects-trail-of-bits-blog-1213|Security assessment techniques for Go projects]] - [[raw/snyk.io/go-security-cheatsheet-snyk-blog-1225|Go Security cheatsheet]] - [[raw/devs.cloudimmunity.com/50-shades-of-go-traps-gotchas-and-common-mistakes-for-new-golang-devs-1102|50 Shades of Go: Traps, Gotchas, and Common Mistakes]] - [[raw/link.medium.com/the-top-10-most-common-mistakes-i-ve-seen-in-go-projects-1366|The Top 10 Most Common Mistakes I've Seen in Go Projects]] - [[raw/unexpected-go.com/unexpected-go-1115|Unexpected Go]] - [[raw/golang.org/url-package-net-url-go-packages-1345|url package - net/url]] - [[raw/link.medium.com/learn-and-use-templates-in-go-1324|Learn and Use Templates In Go]] - [[raw/link.medium.com/building-and-testing-a-rest-api-in-golang-using-gorilla-mux-and-mysql-1168|Building and testing a REST API in golang using gorilla mux and MySQL]] - [[raw/link.medium.com/making-http-requests-in-golang-1170|Making HTTP requests in golang]] - [[raw/link.medium.com/password-hash-salt-using-golang-1173|Password Hash & Salt Using Golang]] - [[raw/about.houqp.me/write-your-own-go-static-analysis-tool-houqp-1145|Write your own Go static analysis tool]] - [[raw/deepsource.io/5-common-mistakes-in-go-1275|5 Common mistakes in Go]]