Skills Agentes

Golang Security

Buenas prácticas de seguridad y prevención de vulnerabilidades en Go: inyección, criptografía, filesystem, red, cookies, secretos, memoria y logging.

Solicitaread edit write glob grep bash(go:*) bash(golangci-lint:*) bash(git:*) agent webfetch bash(govulncheck:*) websearch askuserquestion enterworktree exitworktree
Estrellas
3k

en todo el repo

Actividad
63

0–100, la ruta de este skill

Actualizado
el mes pasado

último commit aquí

Commits
10

últimos 90 días

Contexto
3.5k tok

109 tok en reposo

Paquete
14 archivos

133 KB

Instalar

Funciona con cualquier agente que lea SKILL.md

npx -y skills add samber/cc-skills-golang --skill golang-security --agent claude-code

Se instala solo en este repositorio.

Qué hace

  • Aplica revisión y auditoría de seguridad en código Go usando un modelo de amenazas por capas (defense in depth)
  • Ofrece modo Review (PR), Audit (5 sub-agentes en paralelo por dominio de vulnerabilidad) y Coding (escritura o corrección de vulnerabilidades)
  • Puntúa hallazgos con DREAD y los clasifica por severidad (Critical, High, Medium, Low)
  • Aplica STRIDE en cada frontera de confianza y flujo de datos del sistema
  • Configura y ejecuta herramientas como gosec y govulncheck para análisis estático y de vulnerabilidades

Úsalo cuando

  • Al escribir, revisar o auditar código Go por motivos de seguridad
  • Al trabajar con criptografía, I/O, gestión de secretos, entrada de usuario o autenticación
  • Al revisar un PR en busca de problemas de seguridad
  • Al hacer una auditoría de seguridad de todo el código base

No lo uses cuando

    Qué lo activa

    Di cualquiera de estas frases y el agente debería cargar este skill.

    • Revisa este PR en busca de vulnerabilidades de seguridad
    • Haz una auditoría de seguridad de todo el repositorio en Go
    • Ayúdame a evitar inyección SQL en esta consulta
    • Configura gosec y govulncheck en el proyecto

    SKILL.md

    En inglés

    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.

    Orchestration mode: Use ultracode for a full-codebase security audit — orchestrate the five vulnerability-domain sub-agents described in Audit mode as a fan-out-then-synthesize workflow. Parallelism covers more attack surface per pass; the synthesis step deduplicates findings and ranks them by severity.

    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. A large audit produces many independent findings — apply each fix/improvement in its own worktree (EnterWorktree), 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

    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.

    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

    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 untrusted file access to an allowed root Go 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.
    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:

    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

    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

    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

    Reproducido de samber/cc-skills-golang bajo licencia MIT. Leer esta página en markdown.

    Archivos

    14 archivos en el paquete. Solo se lee SKILL.md al activarse — las referencias se cargan si el skill decide que las necesita.

    Antes de instalar

    Requiere los binarios go y govulncheck (instalable con go install golang.org/x/vuln/cmd/govulncheck@latest).

    Detalles

    Creador
    samber
    Categoría
    Seguridad
    Licencia
    MIT
    Recursos incluidos
    referencias
    Código fuente
    Ver SKILL.md

    Etiquetas

    Más de samber/cc-skills-golang

    Este repo incluye 46 skills. Si instalas uno, normalmente ya tienes los demás.

    Buenas prácticas de linting y configuración de golangci-lint para proyectos Golang: ejecutar linters, configurar .golangci.yml, suprimir avisos con nolint, interpretar salidas y elegir linters.

    Costo de contexto al activarse
    1.8k tok
    Tamaño del paquete
    5 archivos
    Última actualización
    hace 3 días
    herramientas desarrollo

    Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

    Costo de contexto al activarse
    3.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    hace 28 días
    testing qa

    Orquestador de skills de Golang, siempre activo en cualquier tarea de código, revisión, debug o setup: carga las skills más relevantes de samber/cc-skills-golang, a menudo varias a la vez.

    Costo de contexto al activarse
    3.8k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 20 días
    herramientas desarrollo

    Patrones y metodología de optimización de rendimiento en Golang: si hay cuello de botella X, aplica el patrón Y, una vez que profiling o benchmarks ya lo identificaron.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    9 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo

    Tests de Golang listos para producción: table-driven, suites y mocks con testify, tests paralelos, fuzzing, fixtures, detección de fugas de goroutines con goleak, snapshot testing, cobertura, tests de integración.

    Costo de contexto al activarse
    4.4k tok
    Tamaño del paquete
    6 archivos
    Última actualización
    el mes pasado
    testing qa

    Inyección de dependencias en Golang con samber/do: contenedores de servicios, gestión de ciclo de vida, scopes, health checks, apagado ordenado y organización en módulos.

    Costo de contexto al activarse
    2.3k tok
    Tamaño del paquete
    4 archivos
    Última actualización
    hace 22 días
    herramientas desarrollo

    Skills relacionados

    Benchmarking, profiling y medición de rendimiento en Golang: escribir y comparar benchmarks, perfilar con pprof, analizar con benchstat y detectar regresiones en CI.

    Costo de contexto al activarse
    3.3k tok
    Tamaño del paquete
    10 archivos
    Última actualización
    hace 28 días
    testing qa

    Desarrollo de aplicaciones CLI en Go: estructura de comandos, flags, configuración por capas, versión embebida, exit codes, señales, completions y testing con cobra, viper o urfave/cli.

    Costo de contexto al activarse
    2.6k tok
    Tamaño del paquete
    14 archivos
    Última actualización
    hace 3 meses
    herramientas desarrollo

    Convenciones de estilo en Golang: longitud y corte de líneas, declaración de variables, claridad del control de flujo y cuándo los comentarios ayudan u estorban.

    Costo de contexto al activarse
    2.5k tok
    Tamaño del paquete
    3 archivos
    Última actualización
    el mes pasado
    herramientas desarrollo