Generated banner for Golang Security
Generated logo for Golang Security

Golang Security

Samuel BertheCommunityCreated by samberDistributed by Samuel Berthe

  • Skill
  • Guidelines
  • Security
  • MIT
  • Medium risk

From the author

Security best practices and vulnerability prevention for Golang — injection (SQL, command, XSS), cryptography, path traversal, SSRF and HTTP security headers, cookies, secrets management, memory safety, PII in logs, STRIDE/DREAD threat modeling, plus `gosec` SAST, race detection, and fuzz testing. Apply when writing, reviewing, or auditing Go code for security, or when touching crypto, file or network I/O, secrets, user input, or authentication. Not for non-exploitable defensive bugs such as nil panics or slice aliasing (→ See `samber/cc-skills-golang@golang-safety` skill), dependency vulnerability scanning with govulncheck (→ See `samber/cc-skills-golang@golang-dependency-management` skill), or wiring security scanners into CI pipelines (→ See `samber/cc-skills-golang@golang-continuous-integration` skill).
— the description by samber

AutoGineer summary

Written by AutoGineer from the skill’s own files, not by the author

The golang-security skill provides a structured approach to identifying and preventing vulnerabilities in Go applications. It acts as a senior security engineer persona, offering guidance on secure coding, threat modeling using STRIDE/DREAD, and deep-dive auditing techniques. The skill covers critical domains including injection prevention, cryptography, web security, and concurrency safety, while providing a clear methodology for tracing data flows and assessing trust boundaries.

What it does

  • Provides a structured security review checklist for Go applications.
  • Offers guidance on threat modeling using STRIDE and DREAD scoring.
  • Supports full codebase security audits through parallelized sub-agent orchestration.
  • Includes best practices for cryptography, input validation, and memory safety.
  • Integrates with standard Go security tools like gosec and govulncheck.
  • Defines clear severity levels for prioritizing security findings.

When to use it

  • During code reviews to identify potential security vulnerabilities in PRs.
  • When performing a full security audit of a Go codebase.
  • When writing new Go code that handles sensitive data, authentication, or network I/O.
  • When assessing the security posture of cryptographic implementations or file system operations.

Advantages

  • Promotes a defense-in-depth security architecture.
  • Reduces the risk of common vulnerabilities like SQL injection and path traversal.
  • Standardizes security reporting with DREAD scoring.
  • Facilitates isolated, reviewable fixes for identified security issues.
  • Encourages proactive security thinking at trust boundaries.

Usage examples

“Perform a security audit on this repository.”
The agent will initiate a multi-agent scan across five vulnerability domains, aggregate findings, score them by severity, and provide a prioritized remediation plan.
“Review this PR for potential SQL injection vulnerabilities.”
The agent will trace data flows from user input to database queries, checking for proper parameterization and upstream validation.
“How should I handle file paths securely in Go?”
The agent will provide guidance on using os.Root or filepath.IsLocal to prevent path traversal, along with code examples.

Install

  1. Download the skill as a ZIP:

    https://autogineer.com/agent-skills/samber/golang-security/download
  2. Unzip it into the cross-client skills folder of your project:

    mkdir -p .agents/skills && unzip golang-security.zip -d .agents/skills

Documentation by samber

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: Reason as thoroughly as possible for security audits and vulnerability analysis — security bugs hide in subtle interactions and deep reasoning catches what surface-level review misses. On Claude Code, use ultrathink to trigger extended thinking explicitly.

Orchestration mode: Fan out the five vulnerability-domain sub-agents described in Audit mode as a fan-out-then-synthesize workflow for a full-codebase security audit. Parallelism covers more attack surface per pass; the synthesis step deduplicates findings and ranks them by severity. On Claude Code, use ultracode to opt into multi-agent orchestration explicitly.

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, 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. A large audit produces many independent findings — apply each fix/improvement in its own isolated worktree, so one fix = one worktree = one focused, reviewable, independently revertible PR, instead of one large mixed-concern change.

  • 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.

Dependencies:

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

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 untrusted file access to an allowed rootGo 1.24+: use os.Root. Pre-Go 1.24: use filepath.IsLocal + filepath.Rel + separator-aware checks; never rely on filepath.Clean + strings.HasPrefix alone.
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-lint skill for configuration and usage.

For deeper security-specific analysis:

# Go security checker (SAST)
go get -tool github.com/securego/gosec/v2/cmd/gosec@latest
go tool gosec ./...

# Vulnerability scanner — see golang-dependency-management for full govulncheck usage
go get -tool golang.org/x/vuln/cmd/govulncheck@latest
go tool govulncheck ./...

To check the known CVEs of a specific module or version without scanning the whole tree (e.g. when vetting a dependency on pkg.go.dev), → See samber/cc-skills-golang@golang-pkg-go-dev skill.

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

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.

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

Additional Resources

Files

references/injection.md

Injection Security Rules

Injection vulnerabilities allow attackers to execute arbitrary code, queries, or commands.

Rules:

  1. SQL queries MUST use parameterized placeholders — NEVER concatenate user input.

  2. Command execution MUST use exec.Command with separate args — NEVER shell interpolation.

  3. HTML output MUST use html/template for automatic escaping.

  4. SSRF: outbound URLs MUST be validated against an allowlist.


Table of Contents

  • SQL Injection — Critical

    • Dynamic IN clauses

    • Dynamic column names and ORDER BY

    • Dynamic WHERE filters

    • Prefer sqlx or pgx over raw database/sql

  • XPath Injection — High

  • Code Injection — Critical

  • Command Injection — Critical

  • Template Injection — High

  • Cross-Site Scripting (XSS) — High

  • HTML Tag Injection — High

  • Server-Side Request Forgery (SSRF) — High

  • Unsafe Deserialization — Critical

  • CWE References

SQL Injection — Critical

Building SQL queries by concatenating user input. Always use prepared statements with placeholders.

Bad:

query := fmt.Sprintf("SELECT * FROM users WHERE name = '%s'", input)
query := "SELECT * FROM users WHERE id = " + id
query := "DELETE FROM orders WHERE id = " + strconv.Itoa(orderID) // safe but inconsistent — use placeholders everywhere

Good:

// Placeholder syntax varies by driver: $1 (pgx/lib/pq), ? (MySQL/SQLite)
db.QueryRow("SELECT * FROM users WHERE name = $1", input)
db.Exec("DELETE FROM orders WHERE id = $1", orderID)
Dynamic IN clauses

Never build IN (...) by joining user strings. Generate numbered placeholders.

Bad:

query := fmt.Sprintf("SELECT * FROM users WHERE id IN (%s)", strings.Join(ids, ","))

Good:

// Build placeholders: $1, $2, $3, ...
placeholders := make([]string, len(ids))
args := make([]any, len(ids))
for i, id := range ids {
    placeholders[i] = fmt.Sprintf("$%d", i+1)
    args[i] = id
}
query := fmt.Sprintf("SELECT * FROM users WHERE id IN (%s)", strings.Join(placeholders, ","))
rows, err := db.Query(query, args...)

With sqlx:

query, args, err := sqlx.In("SELECT * FROM users WHERE id IN (?)", ids)
query = db.Rebind(query) // converts ? to $1,$2,... for postgres
rows, err := db.Query(query, args...)
Dynamic column names and ORDER BY

Placeholders only work for values, not identifiers (table/column names) or SQL keywords. Allowlist identifiers explicitly.

Bad:

query := fmt.Sprintf("SELECT * FROM users ORDER BY %s", sortCol) // SQL injection

Good:

allowed := map[string]string{
    "name": "name", "created": "created_at", "email": "email",
}
col, ok := allowed[sortCol]
if !ok {
    col = "created_at"
}
query := fmt.Sprintf("SELECT * FROM users ORDER BY %s", col) // safe: col is from allowlist
Dynamic WHERE filters

Build queries incrementally; parameterize every user-supplied value.

var conditions []string
var args []any
idx := 1

if name != "" {
    conditions = append(conditions, fmt.Sprintf("name = $%d", idx))
    args = append(args, name)
    idx++
}
if minAge > 0 {
    conditions = append(conditions, fmt.Sprintf("age >= $%d", idx))
    args = append(args, minAge)
    idx++
}

query := "SELECT * FROM users"
if len(conditions) > 0 {
    query += " WHERE " + strings.Join(conditions, " AND ")
}
rows, err := db.Query(query, args...)
Prefer sqlx or pgx over raw database/sql

Libraries like sqlx and pgx provide safer ergonomics (named parameters, IN clause expansion, struct scanning) while still using prepared statements under the hood. They reduce the temptation to fall back to string concatenation for complex queries.


XPath Injection — High

XPath injection allows manipulation of XML data queries.

Bad:

xpathQuery := "//user[@username='" + username + "']" // Vulnerable

Good:

// Use numeric ID
xpathQuery := fmt.Sprintf("//user[@id='%d']", userID)

// Or parse XML without XPath

Code Injection — Critical

Generating code from unvalidated user input.

Bad:

template := "func handle" + resourceName + "() {...}" // DON'T

Good:

// Validate resource name matches whitelist
if !allowedResources[resourceName] {
    return errors.New("invalid resource")
}
// Use predefined templates

Command Injection — Critical

Passing unvalidated input to shell commands.

Bad:

cmd := exec.Command("sh", "-c", "rm -f /tmp/"+filename) // DON'T

Good:

cmd := exec.Command("rm", "-f", filepath.Join("/tmp", filename))

// Better: validate filename
if filepath.Base(filename) != filename {
    return errors.New("invalid filename")
}

Template Injection — High

Using untrusted input in templates.

Bad:

data := r.URL.Query().Get("user") // Untrusted input
t.Execute(w, data)

Good:

// Validate input
user := strings.TrimSpace(r.URL.Query().Get("user"))
if !allowedRoles[role] {
    role = "user"
}
t.Execute(w, data)

Cross-Site Scripting (XSS) — High

XSS allows attackers to execute malicious scripts.

Bad:

w.Write([]byte(fmt.Sprintf("<div>%s</div>", data))) // DON'T

Good:

import "html/template"
t := template.Must(template.New("safe").Parse("<div>{{.}}</div>"))
t.Execute(w, data) // Auto-escapes

HTML Tag Injection — High

Injecting HTML tags through unvalidated input.

Bad:

fmt.Fprintf(w, "<div>Welcome, %s!</div>", input) // DON'T

Good:

import "html"
escaped := html.EscapeString(input)
fmt.Fprintf(w, "<div>Welcome, %s!</div>", escaped)

Server-Side Request Forgery (SSRF) — High

Forcing the server to make requests to unintended endpoints.

Bad:

url := r.URL.Query().Get("url")
resp, _ := http.Get(url) // DON'T: No validation

Good:

u, err := url.Parse(targetURL)
// Block non-HTTP/S protocols
if u.Scheme != "http" && u.Scheme != "https" {
    return errors.New("invalid scheme")
}
// Block internal hosts
if isInternalIP(u.Hostname()) {
    return errors.New("internal host not allowed")
}
// Block metadata endpoints
if strings.Contains(u.Hostname(), "metadata.") {
    return errors.New("metadata endpoint blocked")
}

Unsafe Deserialization — Critical

Deserializing untrusted input can lead to resource exhaustion, type confusion, or unsafe object construction.

Bad:

dec := gob.NewDecoder(r.Body) // DON'T: gob is not hardened for adversarial input
var user interface{}
dec.Decode(&user)

Good:

import "encoding/json"
dec := json.NewDecoder(r.Body)
var user User
dec.Decode(&user) // JSON doesn't execute code
// Validate fields

CWE References

  • CWE-78: OS Command Injection

  • CWE-89: SQL Injection

  • CWE-94: Code Injection

  • CWE-79: Cross-site Scripting (XSS)

  • CWE-918: Server-Side Request Forgery (SSRF)

  • CWE-502: Deserialization of Untrusted Data

  • CWE-20: Improper Input Validation

Requirements and compatibility

Written for: Claude Code, OpenAI Codex

Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta

“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.

Needs: Declares allowed tools, Claude Code frontmatter

The author says: Designed for Claude Code, Codex or similar harness, and for projects using Golang.

Security

What our scanner noticed· Medium risk

  • References to credential files

A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.

Attribution and licence

Created by
samber
Publisher
Samuel Berthe (Community)
Distributed by
Samuel Berthe
Source
samber/cc-skills-golang · skills/golang-security · commit bb1d43d
Licence
MIT License (redistribution allowed)
  • LICENSE (added by AutoGineer from LICENSE)
  • ATTRIBUTION.md (written by AutoGineer)
Synced

AutoGineer is not affiliated with or endorsed by samber or Samuel Berthe.

Download ZIP

The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download golang-security.zip