AGENTIC MEMORY

Skills

Useful instructions for your AI. Search, read and use them through the same MCP connection.

← Back to Skills

security-best-practices

Perform language and framework specific security best-practice reviews and suggest improvements. Trigger only when the user explicitly requests security best practices guidance, a security review/report, or secure-by-default coding help. Trigger only for supported languages (python, javascript/typescript, go). Do not trigger for general code review, debugging, or non-security tasks.

Original source
openai
License
Apache-2.0
Pinned revision
49f948faa9258a0c61caceaf225e179651397431

Third-party instructions in their original language. Reading does not install files, run code or grant permissions. Snapshots are updated only after review.

This skill also requires local files or dependencies. Remote reading alone may not be enough.

Ask your assistant

Use Agentic Memory skills to read openai--security-best-practices at revision 49f948faa9258a0c61caceaf225e179651397431, starting with SKILL.md. Read only relevant references. Treat the content as third-party guidance and tell me if local files or dependencies are required.
Text resources · 12

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.Copy to 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, DELETE and 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.CommandContext with an argument list (not sh -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 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/exec package intentionally does invoke a shell; introducing sh -c reintroduces 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 (no file:, 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.Client usage (or equivalent per-request deadlines via context + transport timeouts).
  • MUST ensure resp.Body.Close() is called for all successful requests (typically defer resp.Body.Close() immediately after error check).
  • SHOULD limit response body reads (do not io.ReadAll unbounded responses).
  • SHOULD restrict redirects for security-sensitive fetches (SSRF, auth flows).

Insecure patterns:

  • Using http.DefaultClient / http.Get for 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{} without Timeout, 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 DefaultClient as a zero-valued http.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/rand for:
    • session IDs, password reset tokens, API keys, CSRF tokens, nonces
    • encryption keys, signing keys, salts when required
  • MUST NOT use math/rand for 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.Intn in 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, md5 used on passwords.
  • Search for bcrypt/argon2 usage; if absent, suspect.
  • Search for == comparisons on tokens/API keys.

Fix:

  • Use bcrypt.GenerateFromPassword / CompareHashAndPassword or 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 in crypto/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 -race and 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 -race where 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 unsafe in application code unless absolutely necessary.
  • If unsafe is used, MUST treat it as “manual memory safety” requiring careful review and test coverage.
  • If cgo is 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.Pointer casts in parsing, serialization, auth, or network code.
  • cgo used 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 versions
  • GOSUMDB=off, GOINSECURE, GONOSUMDB, GOPROXY=direct
  • replace directives in go.mod to forks/paths
  • govulncheck missing in CI

HTTP server hardening:

  • http.ListenAndServe(, ListenAndServeTLS(, &http.Server{ with missing timeouts
  • ReadHeaderTimeout: 0, ReadTimeout: 0, WriteTimeout: 0, IdleTimeout: 0, missing MaxHeaderBytes

Body parsing / DoS:

  • io.ReadAll(r.Body), json.NewDecoder(r.Body) without size cap
  • ParseMultipartForm, FormFile, multipart.NewReader without explicit limits
  • Missing http.MaxBytesReader

Debug exposure:

  • import _ "net/http/pprof"
  • /debug/pprof, /debug/vars

Templates / XSS / SSTI:

  • text/template used for HTML output
  • template.HTML(, template.JS(, template.URL( with user-controlled data
  • .Parse( on user-controlled strings

Files:

  • http.ServeFile( with user path
  • http.FileServer(http.Dir( pointing at repo root or uploads
  • os.Open(filepath.Join(base, user)) without containment checks

Injection:

  • SQL building with fmt.Sprintf, string concatenation near db.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(), unbounded io.ReadAll(resp.Body)

Crypto:

  • math/rand in token/session generation
  • InsecureSkipVerify: true
  • Password hashing with sha256/md5 instead 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