golang-security by samber/cc-skills-golang
npx skills add https://github.com/samber/cc-skills-golang --skill golang-security角色: 您是一名高级 Go 安全工程师。无论是在审计现有代码还是编写新代码时,您都应用安全思维——预防威胁比修复威胁更容易。
思维模式: 使用 ultrathink 进行安全审计和漏洞分析。安全漏洞隐藏在细微的交互中——深度推理能发现表层审查遗漏的问题。
模式:
Go 中的安全遵循纵深防御原则:在多层进行保护,验证所有输入,使用安全默认值,并利用标准库的安全意识设计。Go 的类型系统和并发模型提供了一些固有的保护,但仍需保持警惕。
在编写或审查代码之前,问三个问题:
| 等级 | DREAD |
|---|
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
| 含义 |
|---|
| 严重 | 8-10 | RCE、完全数据泄露、凭据窃取——立即修复 |
| 高 | 6-7.9 | 认证绕过、显著数据暴露、加密损坏——在当前冲刺中修复 |
| 中 | 4-5.9 | 有限暴露、会话问题、防御削弱——在下一个冲刺中修复 |
| 低 | 1-3.9 | 次要信息泄露、最佳实践偏差——在方便时修复 |
等级与 DREAD 评分 保持一致。
在标记安全问题之前,追踪整个代码库的完整数据流——不要孤立地评估代码片段。
严重性调整,而非驳回: 上游保护不会消除一个发现——纵深防御意味着每一层都应该保护自己。但它会改变严重性:一个只能通过严格输入解析器访问的 SQL 拼接是中等的,而不是严重的。始终报告发现,并调整严重性,注明存在哪些上游防御,以及如果它们被移除或绕过会发生什么。
当降级或跳过某个发现时: 添加一个简短的内联注释(例如,// security: SQL concat safe here — input is validated by parseUserID() which returns int),以便记录决策、可供审查,并且不会被未来的审计重新标记。
将 STRIDE 应用于系统中每个跨越信任边界和数据流:S 欺骗(认证)、T 篡改(完整性)、R 抵赖(审计日志)、I 信息泄露(加密)、D 拒绝服务(速率限制)、E 权限提升(授权)。使用 DREAD(损害、可重现性、可利用性、受影响用户、可发现性)对每个威胁进行评分,以确定修复优先级——严重(8-10)需要立即采取行动。
有关完整的方法论、Go 示例、DFD 信任边界、DREAD 评分和 OWASP Top 10 映射,请参阅 威胁建模指南。
| 严重性 | 漏洞 | 防御 | 标准库解决方案 |
|---|---|---|---|
| 严重 | SQL 注入 | 参数化查询将数据与代码分离 | 使用 ? 占位符的 database/sql |
| 严重 | 命令注入 | 单独传递参数,切勿通过 shell 拼接 | 带有单独参数的 exec.Command |
| 高 | XSS | 自动转义将用户数据呈现为文本,而非 HTML/JS | html/template, text/template |
| 高 | 路径遍历 | 将文件访问限定在根目录,防止 ../ 逃逸 | os.Root (Go 1.24+), filepath.Clean |
| 中 | 时序攻击 | 恒定时间比较避免逐字节泄露 | crypto/subtle.ConstantTimeCompare |
| 高 | 加密问题 | 使用经过审查的算法;切勿自己发明 | crypto/aes, crypto/rand |
| 中 | HTTP 安全 | TLS + 安全头部防止降级攻击 | net/http, 配置 TLSConfig |
| 低 | 缺少头部 | HSTS、CSP、X-Frame-Options 防止浏览器攻击 | 安全头部中间件 |
| 中 | 速率限制 | 速率限制防止暴力破解和资源耗尽 | golang.org/x/time/rate, 服务器超时 |
| 高 | 竞态条件 | 保护共享状态以防止数据损坏 | sync.Mutex, 通道, 避免共享状态 |
有关完整示例、代码片段和 CWE 映射,请参阅:
unsafe 使用。有关按领域(输入处理、数据库、加密、Web、认证、错误、依赖项、并发)组织的完整安全审查清单,请参阅 安全审查清单 —— 一个全面的代码审查清单,涵盖所有主要漏洞类别。
安全相关的检查器:bodyclose, sqlclosecheck, nilerr, errcheck, govet, staticcheck。有关配置和使用,请参阅 samber/cc-skills-golang@golang-linter 技能。
用于更深层次的安全特定分析:
# Go 安全检查器 (SAST)
go install github.com/securego/gosec/v2/cmd/gosec@latest
gosec ./...
# 漏洞扫描器 —— 有关完整的 govulncheck 用法,请参阅 golang-dependency-management
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
# 竞态检测器
go test -race ./...
# 模糊测试
go test -fuzz=Fuzz
| 严重性 | 错误 | 修复 |
|---|---|---|
| 高 | 使用 math/rand 生成令牌 | 输出可预测——攻击者可以重现序列。使用 crypto/rand |
| 严重 | SQL 字符串拼接 | 攻击者可以修改查询逻辑。参数化查询保持数据和代码分离 |
| 严重 | exec.Command("bash -c") | Shell 解释元字符(;, ` |
| 高 | 信任未清理的输入 | 在信任边界进行验证——内部代码信任边界,因此在那里捕获不良输入可以保护一切 |
| 严重 | 硬编码密钥 | 源代码中的密钥最终会出现在版本历史、CI 日志和备份中。使用环境变量或密钥管理器 |
| 中 | 使用 == 比较密钥 | == 在第一个不同字节处短路,泄露时序信息。使用 crypto/subtle.ConstantTimeCompare |
| 中 | 返回详细错误 | 堆栈跟踪和数据库错误帮助攻击者映射您的系统。返回通用消息,在服务器端记录详细信息 |
| 高 | 忽略 -race 发现 | 竞态导致数据损坏,并可能在并发情况下绕过授权检查。修复所有竞态 |
| 高 | 使用 MD5/SHA1 处理密码 | 两者都有已知的碰撞攻击,并且易于暴力破解。使用 Argon2id 或 bcrypt(故意慢速、内存密集型) |
| 高 | 使用不带 GCM 的 AES | ECB/CBC 模式缺乏认证——攻击者可以修改密文而不被检测。GCM 提供加密+认证 |
| 中 | 绑定到 0.0.0.0 | 将服务暴露给所有网络接口。绑定到特定接口以限制攻击面 |
| 严重性 | 反模式 | 失败原因 | 修复 |
|---|---|---|---|
| 高 | 通过隐匿实现安全 | 隐藏的 URL 可通过模糊测试、日志或源代码发现 | 对所有端点进行认证 + 授权 |
| 高 | 信任客户端头部 | X-Forwarded-For, X-Is-Admin 极易伪造 | 服务器端身份验证 |
| 高 | 客户端授权 | JavaScript 检查可被任何 HTTP 客户端绕过 | 在每个处理程序上进行服务器端权限检查 |
| 高 | 跨环境共享密钥 | 暂存环境泄露会危及生产环境 | 通过密钥管理器使用每个环境的密钥 |
| 严重 | 忽略加密错误 | _, _ = encrypt(data) 静默地继续未加密 | 始终检查错误——失败时关闭,切勿开放 |
| 严重 | 自己发明加密 | 自定义加密未经密码学家分析 | 使用 crypto/aes GCM, golang.org/x/crypto/argon2 |
有关带有 Go 代码示例的详细反模式,请参阅 安全架构。
请参阅 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 技能。
每周安装
94
仓库
GitHub 星标
184
首次出现
3 天前
安全审计
安装于
opencode76
codex75
gemini-cli75
kimi-cli74
github-copilot74
cursor74
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:
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.
Before writing or reviewing code, ask three questions:
| 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.
Before flagging a security issue, trace the full data flow through the codebase — don't assess a code snippet in isolation.
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.
Apply STRIDE to every trust boundary crossing and data flow in your system: S poofing (authentication), T ampering (integrity), R epudiation (audit logging), I nformation Disclosure (encryption), D enial of Service (rate limiting), E levation 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.
| 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 |
For complete examples, code snippets, and CWE mappings, see:
unsafe usage.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.
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 ./...
# Race detector
go test -race ./...
# Fuzz testing
go test -fuzz=Fuzz
| 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 |
| 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 | silently proceeds unencrypted |
See Security Architecture for detailed anti-patterns with Go code examples.
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.
Weekly Installs
94
Repository
GitHub Stars
184
First Seen
3 days ago
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode76
codex75
gemini-cli75
kimi-cli74
github-copilot74
cursor74
Azure PostgreSQL 无密码身份验证配置指南:Entra ID 迁移与访问管理
34,800 周安装
| 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 |
_, _ = encrypt(data)| 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 |