golang-security
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChinesePersona: 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 for security audits and vulnerability analysis. Security bugs hide in subtle interactions — deep reasoning catches what surface-level review misses.
ultrathinkModes:
- 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安全工程师。无论是审计现有代码还是编写新代码,你都秉持安全思维——威胁预防远比修复更简单。
思维模式:使用进行安全审计与漏洞分析。安全漏洞往往隐藏在细微的交互中——深度推理才能发现表面评审遗漏的问题。
ultrathink工作模式:
- 评审模式——评审PR中的安全问题。从变更文件入手,追踪调用站点和数据流至相邻代码——漏洞可能存在于差异之外,但会被变更触发。按顺序进行。
- 审计模式——全代码库安全扫描。最多启动5个并行子Agent(通过Agent工具),每个负责独立的漏洞领域:(1) 注入模式,(2) 加密与密钥,(3) Web安全与请求头,(4) 身份验证与授权,(5) 并发安全与依赖漏洞。汇总发现的问题,使用DREAD评分,并按严重程度报告。
- 编码模式——适用于编写新代码或修复已报告的漏洞。遵循本技能的分步指导。可选择启动后台Agent,在主Agent实现功能的同时,扫描新编写代码中的常见漏洞模式。
Go Security
Go安全
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.
Go语言的安全遵循纵深防御原则:通过多层防护、验证所有输入、使用安全默认配置,并利用标准库的安全设计。Go的类型系统和并发模型提供了一些固有防护,但仍需保持警惕。
Security Thinking Model
安全思维模型
Before writing or reviewing code, ask three questions:
- What are the trust boundaries? — Where does untrusted data enter the system? (HTTP requests, file uploads, environment variables, database rows written by other services)
- What can an attacker control? — Which inputs flow into sensitive operations? (SQL queries, shell commands, HTML output, file paths, cryptographic operations)
- What is the blast radius? — If this defense fails, what's the worst outcome? (Data leak, RCE, privilege escalation, denial of service)
在编写或评审代码前,先思考三个问题:
- 信任边界在哪里?——不可信数据从何处进入系统?(HTTP请求、文件上传、环境变量、其他服务写入的数据库行)
- 攻击者可以控制什么?——哪些输入会流向敏感操作?(SQL查询、Shell命令、HTML输出、文件路径、加密操作)
- 影响范围有多大?——如果防护失效,最坏的结果是什么?(数据泄露、远程代码执行RCE、权限提升、拒绝服务)
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.
| 等级 | DREAD评分 | 含义 |
|---|---|---|
| Critical(严重) | 8-10 | 远程代码执行、全面数据泄露、凭证窃取——立即修复 |
| High(高) | 6-7.9 | 身份验证绕过、大量数据暴露、加密逻辑失效——当前迭代修复 |
| Medium(中) | 4-5.9 | 有限数据暴露、会话问题、防护削弱——下一个迭代修复 |
| Low(低) | 1-3.9 | 轻微信息泄露、违反最佳实践——适时修复 |
等级与DREAD评分标准保持一致。
Research Before Reporting
报告前的调研
Before flagging a security issue, trace the full data flow through the codebase — don't assess a code snippet in isolation.
- 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?
- Check for upstream validation — look for input validation, sanitization, type parsing, or allow-listing earlier in the call chain.
- 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.
- 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., ) so the decision is documented, reviewable, and won't be re-flagged by future audits.
// security: SQL concat safe here — input is validated by parseUserID() which returns int在标记安全问题前,需追踪数据在代码库中的完整流向——不要孤立评估代码片段。
- 追踪数据来源——追溯变量进入系统的位置。是用户输入、硬编码常量还是仅内部使用的值?
- 检查上游验证——查看调用链上游是否有输入验证、清理、类型解析或白名单机制。
- 审视信任边界——如果数据从未跨越信任边界(例如,使用mTLS的内部服务间通信),风险等级会有所不同。
- 阅读周边代码,而非仅差异部分——中间件、拦截器或包装函数可能已提供一层防护。
调整严重程度,而非忽略问题:上游防护不能消除问题——纵深防御意味着每一层都应自我防护。但会改变严重程度:仅通过严格输入解析器才能触发的SQL拼接问题,严重程度为中而非严重。始终报告问题并调整严重程度,同时注明存在哪些上游防护,以及如果这些防护被移除或绕过会发生什么。
降低或跳过问题标记时:添加简短的内联注释(例如),以便决策可被记录、评审,且不会在未来审计中被重复标记。
// security: SQL concat safe here — input is validated by parseUserID() which returns intThreat Modeling (STRIDE)
威胁建模(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.
对系统中每一处信任边界跨越和数据流应用STRIDE模型:Spoofing(身份伪造,针对身份验证)、Tampering(篡改,针对完整性)、Repudiation(抵赖,针对审计日志)、Information Disclosure(信息泄露,针对加密)、Denial of Service(拒绝服务,针对速率限制)、Elevation of Privilege(权限提升,针对授权)。使用DREAD(Damage损害、Reproducibility可复现性、Exploitability可利用性、Affected users受影响用户、Discoverability可发现性)对每个威胁评分,以确定修复优先级——严重(8-10)级问题需立即处理。
如需包含Go示例、DFD信任边界、DREAD评分及OWASP Top 10映射的完整方法,请参阅**威胁建模指南**。
Quick Reference
快速参考
| Severity | Vulnerability | Defense | Standard Library Solution |
|---|---|---|---|
| Critical | SQL Injection | Parameterized queries separate data from code | |
| Critical | Command Injection | Pass args separately, never via shell concatenation | |
| High | XSS | Auto-escaping renders user data as text, not HTML/JS | |
| High | Path Traversal | Scope file access to a root, prevent | |
| Medium | Timing Attacks | Constant-time comparison avoids byte-by-byte leaks | |
| High | Crypto Issues | Use vetted algorithms; never roll your own | |
| Medium | HTTP Security | TLS + security headers prevent downgrade attacks | |
| 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 | |
| High | Race Conditions | Protect shared state to prevent data corruption | |
| 严重程度 | 漏洞类型 | 防护措施 | 标准库解决方案 |
|---|---|---|---|
| 严重 | SQL注入 | 参数化查询分离数据与代码 | 使用 |
| 严重 | 命令注入 | 单独传递参数,绝不通过Shell拼接 | 使用 |
| 高 | XSS | 自动转义将用户数据渲染为文本而非HTML/JS | |
| 高 | 路径遍历 | 将文件访问限制在根目录内,防止 | |
| 中 | 时序攻击 | 恒时比较避免逐字节泄露信息 | |
| 高 | 加密问题 | 使用经过验证的算法;绝不自行实现加密 | |
| 中 | HTTP安全 | TLS + 安全请求头防止降级攻击 | |
| 低 | 缺失请求头 | HSTS、CSP、X-Frame-Options防止浏览器攻击 | 安全请求头中间件 |
| 中 | 速率限制 | 速率限制防止暴力破解和资源耗尽 | |
| 高 | 竞态条件 | 保护共享状态防止数据损坏 | |
Detailed Categories
详细分类
For complete examples, code snippets, and CWE mappings, see:
- Cryptography — Algorithms, key derivation, TLS configuration.
- Injection Vulnerabilities — SQL, command, template injection, XSS, SSRF.
- Filesystem Security — Path traversal, zip bombs, file permissions, symlinks.
- Network/Web Security — SSRF, open redirects, HTTP headers, timing attacks, session fixation.
- Cookie Security — Secure, HttpOnly, SameSite flags.
- Third-Party Data Leaks — Analytics privacy risks, GDPR/CCPA compliance.
- Memory Safety — Integer overflow, memory aliasing, usage.
unsafe - Secrets Management — Hardcoded credentials, env vars, secret managers.
- Logging Security — PII in logs, log injection, sanitization.
- Threat Modeling Guide — STRIDE, DREAD scoring, trust boundaries, OWASP Top 10.
- Security Architecture — Defense-in-depth, Zero Trust, auth patterns, rate limiting, anti-patterns.
如需完整示例、代码片段及CWE映射,请参阅:
- 加密技术——算法、密钥派生、TLS配置。
- 注入漏洞——SQL、命令行、模板注入、XSS、SSRF。
- 文件系统安全——路径遍历、zip炸弹、文件权限、符号链接。
- 网络/Web安全——SSRF、开放重定向、HTTP请求头、时序攻击、会话固定。
- Cookie安全——Secure、HttpOnly、SameSite标记。
- 第三方数据泄露——分析工具隐私风险、GDPR/CCPA合规。
- 内存安全——整数溢出、内存别名、包使用。
unsafe - 密钥管理——硬编码凭证、环境变量、密钥管理器。
- 日志安全——日志中的PII数据、日志注入、数据清理。
- 威胁建模指南——STRIDE、DREAD评分、信任边界、OWASP Top 10。
- 安全架构——纵深防御、零信任、身份验证模式、速率限制、反模式。
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.
如需按领域(输入处理、数据库、加密、Web、身份验证、错误、依赖、并发)组织的完整安全评审检查清单,请参阅**安全评审检查清单**——涵盖所有主要漏洞类别的综合性代码评审检查清单。
Tooling & Verification
工具与验证
Static Analysis & Linting
静态分析与代码检查
Security-relevant linters: , , , , , . See the skill for configuration and usage.
bodyclosesqlclosechecknilerrerrcheckgovetstaticchecksamber/cc-skills-golang@golang-linterFor deeper security-specific analysis:
bash
undefined与安全相关的代码检查工具:、、、、、。配置与使用方法请参阅技能。
bodyclosesqlclosechecknilerrerrcheckgovetstaticchecksamber/cc-skills-golang@golang-linter如需更深入的安全专项分析:
bash
undefinedGo security checker (SAST)
Go安全检查器(SAST)
go install github.com/securego/gosec/v2/cmd/gosec@latest
gosec ./...
go install github.com/securego/gosec/v2/cmd/gosec@latest
gosec ./...
Vulnerability scanner — see golang-dependency-management for full govulncheck usage
漏洞扫描器——完整govulncheck使用方法请参阅golang-dependency-management
go install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
undefinedgo install golang.org/x/vuln/cmd/govulncheck@latest
govulncheck ./...
undefinedSecurity Testing
安全测试
bash
undefinedbash
undefinedRace detector
竞态检测器
go test -race ./...
go test -race ./...
Fuzz testing
模糊测试
go test -fuzz=Fuzz
undefinedgo test -fuzz=Fuzz
undefinedCommon Mistakes
常见错误
| Severity | Mistake | Fix |
| --- | --- | --- | --- |
| High | for tokens | Output is predictable — attacker can reproduce the sequence. Use |
| Critical | SQL string concatenation | Attacker can modify query logic. Parameterized queries keep data and code separate |
| Critical | | 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 |
| Medium | Returning detailed errors | Stack traces and DB errors help attackers map your system. Return generic messages, log details server-side |
| High | Ignoring 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 |
math/randcrypto/randexec.Command("bash -c");|`====crypto/subtle.ConstantTimeCompare-race| 严重程度 | 错误行为 | 修复方案 |
|---|---|---|
| 高 | 使用 | 输出可预测——攻击者可重现序列。使用 |
| 严重 | SQL字符串拼接 | 攻击者可修改查询逻辑。参数化查询分离数据与代码 |
| 严重 | 使用 | Shell会解析元字符( |
| 高 | 信任未清理的输入 | 在信任边界处验证输入——内部代码信任边界,因此在此处拦截恶意输入可保护所有后续逻辑 |
| 严重 | 硬编码密钥 | 源代码中的密钥会进入版本历史、CI日志和备份。使用环境变量或密钥管理器 |
| 中 | 使用 | |
| 中 | 返回详细错误信息 | 堆栈跟踪和数据库错误会帮助攻击者映射系统结构。返回通用消息,在服务器端记录详细信息 |
| 高 | 忽略 | 竞态条件会导致数据损坏,并可能在并发场景下绕过授权检查。修复所有竞态问题 |
| 高 | 使用MD5/SHA1存储密码 | 两者均存在已知碰撞攻击,且易被暴力破解。使用Argon2id或bcrypt(故意设计为慢算法,内存密集型) |
| 高 | AES未使用GCM模式 | ECB/CBC模式缺乏身份验证——攻击者可在未被检测到的情况下修改密文。GCM模式提供加密+身份验证 |
| 中 | 绑定到0.0.0.0 | 将服务暴露给所有网络接口。绑定到特定接口以缩小攻击面 |
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 | | 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 | | Always check errors — fail closed, never open |
| Critical | Rolling your own crypto | Custom encryption hasn't been analyzed by cryptographers | Use |
See Security Architecture for detailed anti-patterns with Go code examples.
| 严重程度 | 反模式 | 失效原因 | 修复方案 |
|---|---|---|---|
| 高 | 通过隐蔽性实现安全 | 隐藏的URL可通过模糊测试、日志或源代码发现 | 对所有端点进行身份验证+授权 |
| 高 | 信任客户端请求头 | | 服务器端身份验证 |
| 高 | 客户端授权 | JavaScript检查可被任何HTTP客户端绕过 | 每个处理器都进行服务器端权限检查 |
| 高 | 跨环境共享密钥 | Staging环境泄露会危及生产环境 | 通过密钥管理器使用每个环境专属的密钥 |
| 严重 | 忽略加密错误 | | 始终检查错误——失败时关闭服务,绝不开放 |
| 严重 | 自行实现加密 | 自定义加密算法未经过密码学家分析 | 使用 |
如需包含Go代码示例的详细反模式,请参阅**安全架构**。
Cross-References
交叉引用
See , , , skills.
samber/cc-skills-golang@golang-databasesamber/cc-skills-golang@golang-safetysamber/cc-skills-golang@golang-observabilitysamber/cc-skills-golang@golang-continuous-integration请参阅、、、技能。
samber/cc-skills-golang@golang-databasesamber/cc-skills-golang@golang-safetysamber/cc-skills-golang@golang-observabilitysamber/cc-skills-golang@golang-continuous-integration