Golang Security

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

MIT-0 · Free to use, modify, and redistribute. No attribution required.
0 · 66 · 0 current installs · 0 all-time installs
bySamuel Berthe@samber
MIT-0
Security Scan
VirusTotalVirusTotal
Benign
View report →
OpenClawOpenClaw
Benign
high confidence
Purpose & Capability
Name/description target Go security; declared binaries (go, govulncheck) and the single install (golang.org/x/vuln/cmd/govulncheck) are directly relevant to auditing Go projects. No unrelated credentials, config paths, or unexpected tools are requested.
Instruction Scope
SKILL.md is an instruction-only skill that directs the agent to review code, run static checks, and (optionally) spawn background sub-agents for domain-specific audits. That behavior is coherent for a security audit skill but implies the agent will read the repository and run tooling/commands — users should expect full-code access during reviews.
Install Mechanism
Single go-based install from golang.org/x/vuln (official source) to provide govulncheck. This is a standard, low-risk install for the stated purpose; no unclear download URLs or archive extraction are used.
Credentials
The skill requests no environment variables, credentials, or config paths. The lack of secrets or unrelated env requirements matches the skill's stated scope.
Persistence & Privilege
always is false and the skill does not request automatic permanent inclusion or system-wide configuration changes. It permits autonomous invocation (the platform default) and use of agent tools to run analyses, which is expected for a security-audit skill.
Assessment
This skill is a documentation + guidance pack for Go security and installs govulncheck from the official golang.org repository. It's coherent and appropriate for auditing or writing Go code. Before installing, be aware that the skill's runtime behavior expects access to your repository (it instructs the agent to read changed files and can spawn sub-agents that scan the code and run tools). If you are uncomfortable with an agent reading your full codebase or running linters/vuln scanners, restrict when and how you invoke the skill. No credentials or secret access are requested by the skill itself.

Like a lobster shell, security has layers — review code before you run it.

Current versionv1.1.2
Download zip
latestvk97astztx6b0aw0k5np0ysfg6n83rfhw

License

MIT-0
Free to use, modify, and redistribute. No attribution required.

Runtime requirements

🔒 Clawdis
Binsgo, govulncheck

Install

Go
Bins: govulncheck

SKILL.md

Persona: You are a senior Go security engineer. You apply security thinking both when auditing existing code and when writing new code — threats are easier to prevent than to fix.

Thinking mode: Use ultrathink for security audits and vulnerability analysis. Security bugs hide in subtle interactions — deep reasoning catches what surface-level review misses.

Modes:

  • Review mode — reviewing a PR for security issues. Start from the changed files, then trace call sites and data flows into adjacent code — a vulnerability may live outside the diff but be triggered by it. Sequential.
  • Audit mode — full codebase security scan. Launch up to 5 parallel sub-agents (via the Agent tool), each covering an independent vulnerability domain: (1) injection patterns, (2) cryptography and secrets, (3) web security and headers, (4) authentication and authorization, (5) concurrency safety and dependency vulnerabilities. Aggregate findings, score with DREAD, and report by severity.
  • Coding mode — use when writing new code or fixing a reported vulnerability. Follow the skill's sequential guidance. Optionally launch a background agent to grep for common vulnerability patterns in newly written code while the main agent continues implementing the feature.

Go Security

Overview

Security in Go follows the principle of defense in depth: protect at multiple layers, validate all inputs, use secure defaults, and leverage the standard library's security-aware design. Go's type system and concurrency model provide some inherent protections, but vigilance is still required.

Security Thinking Model

Before writing or reviewing code, ask three questions:

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

Severity Levels

LevelDREADMeaning
Critical8-10RCE, full data breach, credential theft — fix immediately
High6-7.9Auth bypass, significant data exposure, broken crypto — fix in current sprint
Medium4-5.9Limited exposure, session issues, defense weakening — fix in next sprint
Low1-3.9Minor 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.

  1. 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?
  2. Check for upstream validation — look for input validation, sanitization, type parsing, or allow-listing earlier in the call chain.
  3. 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.
  4. 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

SeverityVulnerabilityDefenseStandard Library Solution
CriticalSQL InjectionParameterized queries separate data from codedatabase/sql with ? placeholders
CriticalCommand InjectionPass args separately, never via shell concatenationexec.Command with separate args
HighXSSAuto-escaping renders user data as text, not HTML/JShtml/template, text/template
HighPath TraversalScope file access to a root, prevent ../ escapesos.Root (Go 1.24+), filepath.Clean
MediumTiming AttacksConstant-time comparison avoids byte-by-byte leakscrypto/subtle.ConstantTimeCompare
HighCrypto IssuesUse vetted algorithms; never roll your owncrypto/aes, crypto/rand
MediumHTTP SecurityTLS + security headers prevent downgrade attacksnet/http, configure TLSConfig
LowMissing HeadersHSTS, CSP, X-Frame-Options prevent browser attacksSecurity headers middleware
MediumRate LimitingRate limits prevent brute-force and resource exhaustiongolang.org/x/time/rate, server timeouts
HighRace ConditionsProtect shared state to prevent data corruptionsync.Mutex, channels, avoid shared state

Detailed Categories

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

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-linter 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

| Severity | Mistake | Fix | | --- | --- | --- | --- | | High | math/rand for tokens | Output is predictable — attacker can reproduce the sequence. Use crypto/rand | | Critical | SQL string concatenation | Attacker can modify query logic. Parameterized queries keep data and code separate | | Critical | exec.Command("bash -c") | Shell interprets metacharacters (;, |, `). Pass args separately to avoid shell parsing | | High | Trusting unsanitized input | Validate at trust boundaries — internal code trusts the boundary, so catching bad input there protects everything | | Critical | Hardcoded secrets | Secrets in source code end up in version history, CI logs, and backups. Use env vars or secret managers | | Medium | Comparing secrets with == | == short-circuits on first differing byte, leaking timing info. Use crypto/subtle.ConstantTimeCompare | | Medium | Returning detailed errors | Stack traces and DB errors help attackers map your system. Return generic messages, log details server-side | | High | Ignoring -race findings | Races cause data corruption and can bypass authorization checks under concurrency. Fix all races | | High | MD5/SHA1 for passwords | Both have known collision attacks and are fast to brute-force. Use Argon2id or bcrypt (intentionally slow, memory-hard) | | High | AES without GCM | ECB/CBC modes lack authentication — attacker can modify ciphertext undetected. GCM provides encrypt+authenticate | | Medium | Binding to 0.0.0.0 | Exposes service to all network interfaces. Bind to specific interface to limit attack surface |

Security Anti-Patterns

SeverityAnti-PatternWhy It FailsFix
HighSecurity through obscurityHidden URLs are discoverable via fuzzing, logs, or sourceAuthentication + authorization on all endpoints
HighTrusting client headersX-Forwarded-For, X-Is-Admin are trivially forgedServer-side identity verification
HighClient-side authorizationJavaScript checks are bypassed by any HTTP clientServer-side permission checks on every handler
HighShared secrets across envsStaging breach compromises productionPer-environment secrets via secret manager
CriticalIgnoring crypto errors_, _ = encrypt(data) silently proceeds unencryptedAlways check errors — fail closed, never open
CriticalRolling your own cryptoCustom encryption hasn't been analyzed by cryptographersUse 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.

Additional Resources

Files

14 total
Select a file
Select a file to preview.

Comments

Loading comments…