golang-security

Security best practices and vulnerability prevention for Golang. Covers injection (SQL, command, XSS), cryptography, filesystem safety, network security,…

INSTALLATION
npx skills add https://github.com/samber/cc-skills-golang --skill golang-security
Run in your project or agent environment. Adjust flags if your CLI version differs.

SKILL.md

$27

  • What are the trust boundaries? — Where does untrusted data enter the system? (HTTP requests, file uploads, environment variables, database rows written by other services)
  • What can an attacker control? — Which inputs flow into sensitive operations? (SQL queries, shell commands, HTML output, file paths, cryptographic operations)
  • What is the blast radius? — If this defense fails, what's the worst outcome? (Data leak, RCE, privilege escalation, denial of service)

Severity Levels

Level

DREAD

Meaning

Critical

8-10

RCE, full data breach, credential theft — fix immediately

High

6-7.9

Auth bypass, significant data exposure, broken crypto — fix in current sprint

Medium

4-5.9

Limited exposure, session issues, defense weakening — fix in next sprint

Low

1-3.9

Minor info disclosure, best-practice deviations — fix opportunistically

Levels align with DREAD scoring.

Research Before Reporting

Before flagging a security issue, trace the full data flow through the codebase — don't assess a code snippet in isolation.

  • Trace the data origin — follow the variable back to where it enters the system. Is it user input, a hardcoded constant, or an internal-only value?
  • Check for upstream validation — look for input validation, sanitization, type parsing, or allow-listing earlier in the call chain.
  • Examine the trust boundary — if the data never crosses a trust boundary (e.g., internal service-to-service with mTLS), the risk profile is different.
  • Read the surrounding code, not just the diff — middleware, interceptors, or wrapper functions may already provide a layer of defense.

Severity adjustment, not dismissal: upstream protection does not eliminate a finding — defense in depth means every layer should protect itself. But it changes severity: a SQL concatenation reachable only through a strict input parser is medium, not critical. Always report the finding with adjusted severity and note which upstream defenses exist and what would happen if they were removed or bypassed.

When downgrading or skipping a finding: add a brief inline comment (e.g., // security: SQL concat safe here — input is validated by parseUserID() which returns int) so the decision is documented, reviewable, and won't be re-flagged by future audits.

Threat Modeling (STRIDE)

Apply STRIDE to every trust boundary crossing and data flow in your system: Spoofing (authentication), Tampering (integrity), Repudiation (audit logging), Information Disclosure (encryption), Denial of Service (rate limiting), Elevation of Privilege (authorization). Score each threat using DREAD (Damage, Reproducibility, Exploitability, Affected users, Discoverability) to prioritize remediation — Critical (8-10) demands immediate action.

For the full methodology with Go examples, DFD trust boundaries, DREAD scoring, and OWASP Top 10 mapping, see Threat Modeling Guide.

Quick Reference

Severity

Vulnerability

Defense

Standard Library Solution

Critical

SQL Injection

Parameterized queries separate data from code

database/sql with ? placeholders

Critical

Command Injection

Pass args separately, never via shell concatenation

exec.Command with separate args

High

XSS

Auto-escaping renders user data as text, not HTML/JS

html/template, text/template

High

Path Traversal

Scope file access to a root, prevent ../ escapes

os.Root (Go 1.24+), filepath.Clean

Medium

Timing Attacks

Constant-time comparison avoids byte-by-byte leaks

crypto/subtle.ConstantTimeCompare

High

Crypto Issues

Use vetted algorithms; never roll your own

crypto/aes, crypto/rand

Medium

HTTP Security

TLS + security headers prevent downgrade attacks

net/http, configure TLSConfig

Low

Missing Headers

HSTS, CSP, X-Frame-Options prevent browser attacks

Security headers middleware

Medium

Rate Limiting

Rate limits prevent brute-force and resource exhaustion

golang.org/x/time/rate, server timeouts

High

Race Conditions

Protect shared state to prevent data corruption

sync.Mutex, channels, avoid shared state

Detailed Categories

For complete examples, code snippets, and CWE mappings, see:

  • Cryptography — Algorithms, key derivation, TLS configuration.
  • Memory Safety — Integer overflow, memory aliasing, unsafe usage.

Code Review Checklist

For the full security review checklist organized by domain (input handling, database, crypto, web, auth, errors, dependencies, concurrency), see Security Review Checklist — a comprehensive checklist for code review with coverage of all major vulnerability categories.

Tooling & Verification

Static Analysis & Linting

Security-relevant linters: bodyclose, sqlclosecheck, nilerr, errcheck, govet, staticcheck. See the samber/cc-skills-golang@golang-lint skill for configuration and usage.

For deeper security-specific analysis:

# Go security checker (SAST)

go install github.com/securego/gosec/v2/cmd/gosec@latest

gosec ./...

# Vulnerability scanner — see golang-dependency-management for full govulncheck usage

go install golang.org/x/vuln/cmd/govulncheck@latest

govulncheck ./...

Security Testing

# Race detector

go test -race ./...

# Fuzz testing

go test -fuzz=Fuzz

Common Mistakes

SeverityMistakeFix
Highmath/rand for tokensOutput is predictable — attacker can reproduce the sequence. Use crypto/rand
CriticalSQL string concatenationAttacker can modify query logic. Parameterized queries keep data and code separate
Criticalexec.Command("bash -c")Shell interprets metacharacters (;, , ). Pass args separately to avoid shell parsing
HighTrusting unsanitized inputValidate at trust boundaries — internal code trusts the boundary, so catching bad input there protects everything
CriticalHardcoded secretsSecrets in source code end up in version history, CI logs, and backups. Use env vars or secret managers
MediumComparing secrets with ==== short-circuits on first differing byte, leaking timing info. Use crypto/subtle.ConstantTimeCompare
MediumReturning detailed errorsStack traces and DB errors help attackers map your system. Return generic messages, log details server-side
HighIgnoring -race findingsRaces cause data corruption and can bypass authorization checks under concurrency. Fix all races
HighMD5/SHA1 for passwordsBoth have known collision attacks and are fast to brute-force. Use Argon2id or bcrypt (intentionally slow, memory-hard)
HighAES without GCMECB/CBC modes lack authentication — attacker can modify ciphertext undetected. GCM provides encrypt+authenticate
MediumBinding to 0.0.0.0Exposes service to all network interfaces. Bind to specific interface to limit attack surface

Security Anti-Patterns

Severity

Anti-Pattern

Why It Fails

Fix

High

Security through obscurity

Hidden URLs are discoverable via fuzzing, logs, or source

Authentication + authorization on all endpoints

High

Trusting client headers

X-Forwarded-For, X-Is-Admin are trivially forged

Server-side identity verification

High

Client-side authorization

JavaScript checks are bypassed by any HTTP client

Server-side permission checks on every handler

High

Shared secrets across envs

Staging breach compromises production

Per-environment secrets via secret manager

Critical

Ignoring crypto errors

_, _ = encrypt(data) silently proceeds unencrypted

Always check errors — fail closed, never open

Critical

Rolling your own crypto

Custom encryption hasn't been analyzed by cryptographers

Use crypto/aes GCM, golang.org/x/crypto/argon2

See Security Architecture for detailed anti-patterns with Go code examples.

Cross-References

See samber/cc-skills-golang@golang-database, samber/cc-skills-golang@golang-safety, samber/cc-skills-golang@golang-observability, samber/cc-skills-golang@golang-continuous-integration skills.

  • → See samber/cc-skills-golang@golang-continuous-integration skill for automated AI-driven code review in CI using these guidelines

Additional Resources

BrowserAct

Let your agent run on any real-world website

Bypass CAPTCHA & anti-bot for free. Start local, scale to cloud.

Explore BrowserAct Skills →

Stop writing automation&scrapers

Install the CLI. Run your first Skill in 30 seconds. Scale when you're ready.

Start free
free · no credit card