references/golang-general-backend-security.md · 24000
cks (not only extensions).
- MUST store uploads outside executable/static roots when possible.
- SHOULD generate server-side filenames (random IDs) and avoid trusting original names.
- MUST serve potentially active formats safely (download attachment) unless explicitly intended.
Insecure patterns:
- Accepting arbitrary file types and serving them back inline.
- Using user-supplied filename as storage path.
- Missing size/type validation.
Detection hints:
- Search for
multipart,FormFile,ParseMultipartForm,io.Copyto disk. - Check where files are stored and how they are served.
Fix:
- Implement allowlist validation + safe storage + safe serving.
- Add scanning/quarantine workflows where applicable.
GO-INJECT-001: Prevent SQL injection (parameterized queries / ORM)
Severity: High
Required:
- MUST use parameterized queries or an ORM that parameterizes under the hood.
- MUST NOT build SQL by string concatenation /
fmt.Sprintf/ string interpolation with untrusted input.
Insecure patterns:
fmt.Sprintf("SELECT ... WHERE id=%s", r.URL.Query().Get("id"))query := "UPDATE users SET role='" + role + "' WHERE id=" + id
Detection hints:
- Grep for
SELECT,INSERT,UPDATE,DELETEand check how query strings are built. - Trace untrusted data into
db.Query,db.Exec,QueryRow, etc.
Fix:
- Replace with placeholders (
?,$1, etc.) and pass parameters separately. - Validate and type-check IDs before use.
GO-INJECT-002: Prevent OS command injection; avoid shelling out with untrusted input
Severity: Critical to High (depends on exposure)
Required:
- MUST avoid executing external commands with attacker-controlled strings.
- If subprocess is necessary:
- MUST use
exec.CommandContextwith an argument list (notsh -c). - MUST NOT pass untrusted input to a shell (
bash -c,sh -c, PowerShell). - SHOULD use strict allowlists for any variable component (subcommand, flags, filenames).
- MUST use
- MUST assume CLI tools may interpret attacker-controlled args as flags or special values.
Insecure patterns:
exec.Command("sh", "-c", userString)exec.Command("bash", "-c", fmt.Sprintf("tool %s", user))- Calling the shell to get glob expansion for user-supplied globs.
Detection hints:
- Search for
os/exec,exec.Command(,CommandContext(,"sh","bash","-c". - Trace untrusted input into command name/args.
Fix:
- Use library APIs instead of subprocesses.
- Hardcode command and allowlist/validate args.
- If a shell is unavoidable, escape robustly and treat as high risk (prefer avoiding).
Notes:
- The Go
os/execpackage intentionally does invoke a shell; introducingsh -creintroduces shell injection hazards.
GO-SSRF-001: Prevent SSRF in outbound HTTP requests
Severity: Medium (High in cloud/LAN environments)
- Note: For small stand alone projects this is less important. It is most important when deploying into an LAN or with other services listening on the same server.
Required:
- MUST treat outbound requests to user-provided URLs as high risk.
- SHOULD allowlist hosts/domains for any user-influenced URL fetch.
- SHOULD block access to localhost/private IP ranges/link-local addresses and cloud metadata endpoints.
- MUST restrict schemes to
http/https(nofile:,gopher:, etc.). - MUST set client timeouts and restrict redirects.
Insecure patterns:
http.Get(r.URL.Query().Get("url"))- “URL preview” / “webhook test” endpoints that fetch arbitrary URLs.
Detection hints:
- Search for
http.Get,client.Do, and URL values derived from requests/DB. - Identify features that fetch remote resources.
Fix:
- Parse URLs strictly; enforce scheme and allowlisted hostnames.
- Resolve DNS and enforce IP-range restrictions (with care for DNS rebinding).
- Set timeouts, disable redirects unless needed, and cap response sizes.
GO-HTTPCLIENT-001: Outbound HTTP clients MUST set timeouts and close bodies
Severity: High (DoS and resource exhaustion)
Required:
- MUST set an overall timeout on
http.Clientusage (or equivalent per-request deadlines via context + transport timeouts). - MUST ensure
resp.Body.Close()is called for all successful requests (typicallydefer resp.Body.Close()immediately after error check). - SHOULD limit response body reads (do not
io.ReadAllunbounded responses). - SHOULD restrict redirects for security-sensitive fetches (SSRF, auth flows).
Insecure patterns:
- Using
http.DefaultClient/http.Getfor user-influenced destinations with no timeout policy. - Missing
defer resp.Body.Close()leading to resource leaks. io.ReadAll(resp.Body)with no limit.
Detection hints:
- Search for
http.Get(,http.Post(,client := &http.Client{}withoutTimeout,client.Do(and missing closes. - Search for
io.ReadAll(resp.Body).
Fix:
- Use a configured client with timeouts.
- Always close response bodies.
- Use bounded readers (
io.LimitReader) for large/untrusted responses.
Notes:
- The net/http package exposes
DefaultClientas a zero-valuedhttp.Client, which can easily lead to “no timeout” behavior unless configured.
GO-REDIRECT-001: Prevent open redirects
Severity: Medium (can be High with auth flows)
Required:
- MUST validate redirect targets derived from untrusted input (
next,redirect,return_to). - SHOULD prefer only same-site relative paths.
- SHOULD fall back to a safe default on validation failure.
Insecure patterns:
http.Redirect(w, r, r.URL.Query().Get("next"), http.StatusFound)with no validation.
Detection hints:
- Search for
http.Redirect(and check origin of the location.
Fix:
- Allowlist internal paths or known domains.
- Reject absolute URLs unless explicitly needed and allowlisted.
GO-CRYPTO-001: Cryptographic randomness MUST come from crypto/rand
Severity: High (Critical if used for auth/session tokens or keys)
Required:
- MUST use
crypto/randfor:- session IDs, password reset tokens, API keys, CSRF tokens, nonces
- encryption keys, signing keys, salts when required
- MUST NOT use
math/randfor any security-sensitive value. - SHOULD use built-in helpers that produce appropriately strong tokens when available.
Insecure patterns:
math/rand.Seed(time.Now().UnixNano())followed by token generation for auth or sessions.- Using UUIDv4-like constructs built from
math/rand.
Detection hints:
- Search for
math/rand,rand.Seed,rand.Intnin code that touches auth/session/token flows. - Search for custom token generators.
Fix:
- Switch to
crypto/rand(rand.Reader,rand.Read, or secure token helpers). - Ensure sufficient entropy and use URL-safe encoding.
Notes:
- The crypto/rand package provides secure randomness APIs and token generation helpers.
GO-AUTH-001: Password storage MUST use adaptive hashing (bcrypt/argon2id) and safe comparisons
Severity: High
Required:
- MUST hash passwords using an adaptive password hashing function (bcrypt or argon2id).
- MUST NOT store plaintext passwords or reversible encryption of passwords.
- MUST compare secrets in constant time when relevant (tokens, MACs, API keys) to reduce timing leaks.
- SHOULD ensure password policies do not exceed algorithm constraints (e.g., bcrypt has input length limits; handle long passphrases appropriately).
Insecure patterns:
sha256(password)stored as password hash.- Plaintext password storage.
- Comparing secrets with
==in timing-sensitive contexts.
Detection hints:
- Search for
sha1,sha256,md5used on passwords. - Search for
bcrypt/argon2usage; if absent, suspect. - Search for
==comparisons on tokens/API keys.
Fix:
- Use
bcrypt.GenerateFromPassword/CompareHashAndPasswordor argon2id with recommended parameters. - Use constant-time compare helpers when comparing MACs/tokens.
Notes:
- Go provides bcrypt in
golang.org/x/crypto/bcrypt, and constant-time comparisons incrypto/subtle.
GO-CONC-001: Data races and concurrency hazards MUST be treated as security-relevant
Severity: Medium to High (depends on what races affect)
Required:
- MUST run tests with the race detector (
go test -race) in CI for security-sensitive services. - MUST fix detected races; do not suppress without deep justification.
- SHOULD treat shared mutable state in handlers as high risk; enforce synchronization or avoid shared mutability.
Insecure patterns:
- Global maps/slices mutated from multiple goroutines without a mutex.
- Caches or auth/session state stored in globals without concurrency protection.
- Racy access to authorization state (can lead to bypasses or inconsistent enforcement).
Detection hints:
- Search for
var someMap = map[...]...used in handlers. - Look for missing
sync.Mutex,sync.Map, channels, or other synchronization. - Ensure CI includes
-raceand that it runs relevant tests.
Fix:
- Add proper synchronization or redesign to avoid shared mutable state.
- Add race tests and run them continuously.
Notes:
- The Go race detector only finds races that occur in executed code paths; improve test coverage and run realistic workloads with
-racewhere feasible.
GO-UNSAFE-001: Use of unsafe/cgo MUST be minimized and audited like memory-unsafe code
Severity: High (Critical in high-risk code paths)
Required:
- SHOULD avoid importing
unsafein application code unless absolutely necessary. - If
unsafeis used, MUST treat it as “manual memory safety” requiring careful review and test coverage. - If
cgois used, MUST treat the C/C++ boundary as memory-unsafe; apply secure coding practices on the C side and isolate where possible.
Insecure patterns:
- Widespread
unsafe.Pointercasts in parsing, serialization, auth, or network code. cgoused for parsing or security boundaries without sandboxing.
Detection hints:
- Search for
import "unsafe",unsafe.Pointer,// #cgo,import "C". - Prioritize review where unsafe touches untrusted input.
Fix:
- Replace unsafe/cgo usage with safe standard library alternatives where possible.
- Isolate unsafe code in small, well-tested modules with fuzz/race tests.
Notes:
- The unsafe package explicitly provides operations that step around Go’s type safety guarantees.
5) Practical scanning heuristics (how to “hunt”)
When actively scanning, use these high-signal patterns:
Toolchain & dependencies:
FROM golang:(Dockerfiles),go-version:(CI),toolchain go(go.mod), pinned old versionsGOSUMDB=off,GOINSECURE,GONOSUMDB,GOPROXY=directreplacedirectives ingo.modto forks/pathsgovulncheckmissing in CI
HTTP server hardening:
http.ListenAndServe(,ListenAndServeTLS(,&http.Server{with missing timeoutsReadHeaderTimeout: 0,ReadTimeout: 0,WriteTimeout: 0,IdleTimeout: 0, missingMaxHeaderBytes
Body parsing / DoS:
io.ReadAll(r.Body),json.NewDecoder(r.Body)without size capParseMultipartForm,FormFile,multipart.NewReaderwithout explicit limits- Missing
http.MaxBytesReader
Debug exposure:
import _ "net/http/pprof"/debug/pprof,/debug/vars
Templates / XSS / SSTI:
text/templateused for HTML outputtemplate.HTML(,template.JS(,template.URL(with user-controlled data.Parse(on user-controlled strings
Files:
http.ServeFile(with user pathhttp.FileServer(http.Dir(pointing at repo root or uploadsos.Open(filepath.Join(base, user))without containment checks
Injection:
- SQL building with
fmt.Sprintf, string concatenation neardb.Query/Exec exec.Command("sh","-c", ...),exec.Command("bash","-c", ...)
SSRF / outbound HTTP:
http.Get(userURL),client.Do(req)where URL comes from request/DB- Missing client timeout, missing
resp.Body.Close(), unboundedio.ReadAll(resp.Body)
Crypto:
math/randin token/session generationInsecureSkipVerify: true- Password hashing with
sha256/md5instead of bcrypt/argon2
Concurrency:
- Shared maps/slices mutated from handlers without locks
- CI lacking
go test -race
Always try to confirm:
- data origin (untrusted vs trusted)
- sink type (template/SQL/subprocess/files/http)
- protective controls present (limits, validation, allowlists, middleware, network controls)
6) Sources (accessed 2026-01-28)
Primary Go documentation:
- Go Security Policy — https://go.dev/doc/security/policy
- Go Release History (security fixes in patch releases) — https://go.dev/doc/devel/release
- Go 1.25 Release Notes — https://go.dev/doc/go1.25
- net/http (server timeouts, MaxHeaderBytes, DefaultClient) — https://pkg.go.dev/net/http
- html/template (auto-escaping and trusted-template assumptions) — https://pkg.go.dev/html/template
- crypto/tls (MinVersion defaults, InsecureSkipVerify warnings) — https://pkg.go.dev/crypto/tls
- crypto/rand (secure randomness, token helpers) — https://pkg.go.dev/crypto/rand
- crypto/subtle (constant-time comparisons) — https://pkg.go.dev/crypto/subtle
- os/exec (no shell by default; command execution guidance) — https://pkg.go.dev/os/exec
- unsafe (bypasses type safety) — https://go.dev/src/unsafe/unsafe.go
- net/http/pprof (debug endpoints) — https://pkg.go.dev/net/http/pprof
- cmd/go (module authentication via go.sum/checksum DB; env vars like GOINSECURE) — https://pkg.go.dev/cmd/go
- Module Mirror and Checksum Database Launched (Go blog) — https://go.dev/blog/module-mirror-launch
- govulncheck documentation — https://pkg.go.dev/golang.org/x/vuln/cmd/govulncheck
- Go Race Detector documentation — https://go.dev/doc/articles/race_detector
- bcrypt (password hashing) — https://pkg.go.dev/golang.org/x/crypto/bcrypt
- Go vulnerability entry example (multipart resource consumption) — https://pkg.go.dev/vuln/GO-2023-1569
OWASP Cheat Sheet Series (general web security):
- Session Management — https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html
- CSRF Prevention — https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html
- SSRF Prevention — https://cheatsheetseries.owasp.org/cheatsheets/Server_Side_Request_Forgery_Prevention_Cheat_Sheet.html
- XSS Prevention — https://cheatsheetseries.owasp.org/cheatsheets/Cross_Site_Scripting_Prevention_Cheat_Sheet.html
- HTTP Security Response Headers — https://cheatsheetseries.owasp.org/cheatsheets/HTTP_Headers_Cheat_Sheet.html