SKILL·1C5083

go-security-audit

eduardo-sl
更新于 8 days ago
64
9
64
在 GitHub 上查看
测试general

关于

This skill performs security reviews of Go applications, covering areas like input validation, SQL injection, authentication, and OWASP Top 10 vulnerabilities. Use it to harden services, check for vulnerabilities, or review security implementations. It specifically excludes dependency scanning and concurrency reviews, which are handled by separate skills.

快速安装

Claude Code

推荐
主要方式
npx skills add eduardo-sl/go-agent-skills -a claude-code
插件命令备选方式
/plugin add https://github.com/eduardo-sl/go-agent-skills
Git 克隆备选方式
git clone https://github.com/eduardo-sl/go-agent-skills.git ~/.claude/skills/go-security-audit

在 Claude Code 中复制并粘贴此命令以安装该技能

技能文档

Go Security Audit

Security is not a feature — it's a property. Every line of code either maintains it or degrades it.

Operating Modes

Pick the mode that matches the request before starting:

  • Targeted check — a single concern ("is this query injectable?", "review this auth middleware"). Apply only the relevant sections.
  • Diff audit — audit the changed lines of a PR or working tree for every concern below.
  • Full audit (default for "security review the service") — sweep the codebase using the parallel passes in "Auditing Large Codebases".

Run the Scanners First

Before manual review, run the automated scanners and fold their output into the findings (skip any that is not installed and note it):

govulncheck ./...       # known CVEs actually reachable from your code
gosec ./...             # static analysis for insecure patterns
go vet ./...            # includes some security-relevant checks

Scanners find the known patterns; the manual passes below find the logic flaws they cannot.

Auditing Large Codebases

Each numbered section below is an independent audit pass. For codebases beyond ~20 files:

  1. Locate the attack surface first: HTTP/gRPC handlers, CLI entry points, queue consumers, and anything parsing external input.
  2. Run one pass per concern: (a) input validation + injection, (b) authentication/authorization, (c) secrets + crypto, (d) TLS + security headers + rate limiting, (e) logging hygiene.
  3. If your environment supports delegating work to parallel sub-agents or tasks, assign each pass to one — the passes don't overlap. Otherwise run them sequentially.
  4. Every finding must cite file.go:line, the vulnerable input path, and a concrete fix. Aggregate into one report sorted by severity.

1. Input Validation

NEVER trust user input. Validate at the boundary:

// ✅ Good — validate before use
func (h *Handler) handleCreate(w http.ResponseWriter, r *http.Request) {
    // Limit body size
    r.Body = http.MaxBytesReader(w, r.Body, 1<<20) // 1 MB

    var req CreateRequest
    if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
        respondError(w, http.StatusBadRequest, "invalid JSON")
        return
    }

    if err := validate.Struct(req); err != nil {
        respondError(w, http.StatusBadRequest, "validation failed")
        return
    }
    // proceed with validated data
}

String sanitization:

// Sanitize HTML to prevent XSS
import "github.com/microcosm-cc/bluemonday"

p := bluemonday.UGCPolicy()
sanitized := p.Sanitize(userInput)

// Validate email format
import "net/mail"
_, err := mail.ParseAddress(email)

// Validate URLs
u, err := url.Parse(input)
if err != nil || (u.Scheme != "http" && u.Scheme != "https") {
    // reject
}

2. SQL Injection Prevention

ALWAYS use parameterized queries:

// ✅ Good — parameterized
row := db.QueryRowContext(ctx,
    "SELECT id, name FROM users WHERE email = $1", email)

// ✅ Good — with sqlx named params
query := "SELECT * FROM users WHERE name = :name AND age > :age"
rows, err := db.NamedQueryContext(ctx, query, map[string]interface{}{
    "name": name,
    "age":  minAge,
})

// ❌ CRITICAL — string concatenation = SQL injection
query := "SELECT * FROM users WHERE email = '" + email + "'"
query := fmt.Sprintf("SELECT * FROM users WHERE id = %s", id)

Dynamic queries:

When building dynamic WHERE clauses, use query builders or safe concatenation:

// ✅ Good — safe dynamic query building
var conditions []string
var args []interface{}
argIdx := 1

if name != "" {
    conditions = append(conditions, fmt.Sprintf("name = $%d", argIdx))
    args = append(args, name)
    argIdx++
}

query := "SELECT * FROM users"
if len(conditions) > 0 {
    query += " WHERE " + strings.Join(conditions, " AND ")
}

3. Authentication & Authorization

Password handling:

import "golang.org/x/crypto/bcrypt"

// Hash password
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)

// Verify password — constant-time comparison built in
err := bcrypt.CompareHashAndPassword(hash, []byte(password))

NEVER store plaintext passwords. NEVER use MD5/SHA for passwords.

JWT validation:

// ✅ Always validate:
// 1. Signature (algorithm must match expectation)
// 2. Expiration (exp claim)
// 3. Issuer (iss claim)
// 4. Audience (aud claim)

// ❌ CRITICAL — never disable signature verification
// ❌ CRITICAL — never accept "alg": "none"
// ❌ CRITICAL — never hardcode signing keys in source code

Authorization middleware:

func RequireRole(role string) func(http.Handler) http.Handler {
    return func(next http.Handler) http.Handler {
        return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
            user := UserFromContext(r.Context())
            if user == nil || !user.HasRole(role) {
                http.Error(w, "forbidden", http.StatusForbidden)
                return
            }
            next.ServeHTTP(w, r)
        })
    }
}

4. Secrets Management

Rules:

  • 🔴 NEVER hardcode secrets, tokens, or API keys in source code
  • 🔴 NEVER commit secrets to git (even in "test" files)
  • 🔴 NEVER log secrets, tokens, or passwords
// ✅ Good — from environment
dbURL := os.Getenv("DATABASE_URL")

// ✅ Good — from secrets manager
secret, err := secretsManager.GetSecret(ctx, "api-key")

// ❌ CRITICAL
const apiKey = "sk-1234567890abcdef" // hardcoded secret

Use .gitignore:

.env
*.pem
*.key
credentials.json

Scan for leaked secrets:

# Use gitleaks in CI
gitleaks detect --source=. --verbose

5. HTTP Security Headers

func SecurityHeaders(next http.Handler) http.Handler {
    return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        w.Header().Set("X-Content-Type-Options", "nosniff")
        w.Header().Set("X-Frame-Options", "DENY")
        w.Header().Set("Content-Security-Policy", "default-src 'self'")
        w.Header().Set("Strict-Transport-Security", "max-age=31536000; includeSubDomains")
        w.Header().Set("X-XSS-Protection", "0") // modern browsers handle this
        next.ServeHTTP(w, r)
    })
}

6. TLS Configuration

tlsConfig := &tls.Config{
    MinVersion: tls.VersionTLS12,
    CipherSuites: []uint16{
        tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384,
        tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
    },
    PreferServerCipherSuites: true,
}

srv := &http.Server{
    TLSConfig: tlsConfig,
    // ...
}

7. Rate Limiting

import "golang.org/x/time/rate"

type RateLimiter struct {
    limiters sync.Map
    rate     rate.Limit
    burst    int
}

func (rl *RateLimiter) Allow(key string) bool {
    limiter, _ := rl.limiters.LoadOrStore(key,
        rate.NewLimiter(rl.rate, rl.burst))
    return limiter.(*rate.Limiter).Allow()
}

Apply rate limiting to auth endpoints, public APIs, and any resource-intensive operations.

8. Logging Security

// ❌ CRITICAL — logging sensitive data
log.Printf("user login: email=%s password=%s", email, password)
log.Printf("auth token: %s", token)
log.Printf("request body: %v", req) // may contain secrets

// ✅ Good — redact sensitive fields
log.Printf("user login: email=%s", email)
logger.Info("auth completed", slog.String("user_id", userID))

Security Audit Checklist

Critical (🔴 BLOCKER)

  • No SQL injection vectors (all queries parameterized)
  • No hardcoded secrets/keys/tokens
  • No plaintext password storage
  • No disabled TLS certificate verification
  • Request body size limited
  • JWT signature verified, alg: none rejected

Important (🟡 WARNING)

  • Input validation on all external data
  • Rate limiting on auth and public endpoints
  • Security headers set on all responses
  • CORS configured restrictively
  • Error messages don't leak internals
  • Audit logging for auth events

Recommended (🟢 SUGGESTION)

  • govulncheck in CI pipeline
  • gitleaks for secret scanning
  • Structured logging with redaction
  • Dependency pinning with verified checksums

GitHub 仓库

eduardo-sl/go-agent-skills
路径: skills/(safety)/go-security-audit
0
FAQ

常见问题

什么是 go-security-audit Skill?

go-security-audit 是一个 Claude Skill,作者为 eduardo-sl。Skill 将 Claude 按需加载的说明和资源打包,让 Claude 无需额外提示即可执行与 go-security-audit 相关的任务。

如何安装 go-security-audit?

使用本页的安装命令:将 go-security-audit 作为插件添加到 Claude Code,或将其仓库克隆到 skills 目录,然后重启 Claude 以加载该 Skill。

go-security-audit 属于哪个分类?

go-security-audit 属于测试分类。

go-security-audit 可以免费使用吗?

可以。go-security-audit 已收录在 AIMCP,可免费安装。

相关推荐技能

evaluating-llms-harness
测试

该Skill通过60+个学术基准测试(如MMLU、GSM8K等)评估大语言模型质量,适用于模型对比、学术研究及训练进度追踪。它支持HuggingFace、vLLM和API接口,被EleutherAI等行业领先机构广泛采用。开发者可通过简单命令行快速对模型进行多任务批量评估。

查看技能
cloudflare-cron-triggers
测试

这个Claude Skill提供了关于Cloudflare Cron Triggers的完整知识库,用于通过cron表达式定时执行Workers。它支持配置周期性任务、维护作业和自动化工作流,并能处理常见的cron触发错误。开发者可以用它来设置定时任务、测试cron处理器,并集成Workflows和Green Compute功能。

查看技能
webapp-testing
测试

该Skill为开发者提供了基于Playwright的本地Web应用测试工具集,支持自动化测试前端功能、调试UI行为、捕获屏幕截图和查看浏览器日志。它包含管理服务器生命周期的辅助脚本,可直接作为黑盒工具运行而无需阅读源码。适用于需要快速验证本地Web应用界面和交互功能的开发场景。

查看技能
finishing-a-development-branch
测试

这个Skill用于开发分支完成后的集成决策,当代码实现完成且测试通过时,它会引导开发者选择合适的工作流。它首先验证测试状态,然后提供合并、创建PR或清理等结构化选项。核心价值在于确保代码质量的同时,标准化分支收尾流程。

查看技能