# gosec - Go 安全检查器
通过扫描 Go AST 和 SSA 代码表示来检查源代码中的安全问题。
<img src="https://assets.kitploit.com/production/public/readmes/2947/83d294db3a312bcea542b6eb8261128e6f09b50a95271788fe301e164b1655b1.png" width="320">
## 快速链接
- [GitHub Action](#github-action)
- [本地安装](#local-installation)
- [快速开始](#quick-start)
- [常见使用模式](#common-usage-patterns)
- [选择规则](#selecting-rules)
- [输出格式](#output-formats)
## 特性
- **基于模式的规则**,用于检测 Go 代码中的常见安全问题
- **基于 SSA 的分析器**,用于类型转换、切片边界和加密问题
- **污点分析**,用于追踪从用户输入到危险函数的数据流(SQL 注入、命令注入、路径遍历、SSRF、XSS、日志注入、SMTP 注入、SSTI、不安全反序列化、开放重定向)
## 许可证
根据 Apache License, Version 2.0(“许可证”)授权。
除非遵守许可证,否则不得使用此文件。
您可以在[此处](http://www.apache.org/licenses/LICENSE-2.0)获取许可证副本。
## 项目状态
[](https://bestpractices.coreinfrastructure.org/projects/3218)
[](https://github.com/securego/gosec/actions?query=workflows%3ACI)
[](https://codecov.io/gh/securego/gosec)
[](https://goreportcard.com/report/github.com/securego/gosec)
[](https://pkg.go.dev/github.com/securego/gosec/v2)
[](https://securego.io/)
[](https://github.com/securego/gosec/releases)
[](https://github.com/orgs/securego/packages/container/package/gosec)
[](http://securego.slack.com)
[](https://github.com/nikolaydubina/go-recipes)
## 安装
### GitHub Action
您可以按如下方式将 `gosec` 作为 GitHub action 运行:
使用带有 `@master` 的版本化标签,该标签固定指向最新的稳定版本。这将提供稳定的行为。
```yaml
name: Run Gosec
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
tests:
runs-on: ubuntu-latest
env:
GO111MODULE: on
steps:
- name: Checkout Source
uses: actions/checkout@v3
- name: Run Gosec Security Scanner
uses: securego/gosec@master
with:
args: ./...
```
#### 扫描包含私有模块的项目
如果你的项目导入了私有 Go 模块,你需要配置身份验证,以便 `gosec` 能够获取这些依赖项。请在工作流中设置以下环境变量:
- `GOPRIVATE`:以逗号分隔的模块路径前缀列表,这些前缀应被视为私有(例如 `github.com/your-org/*`)。
- `GITHUB_AUTHENTICATION_TOKEN`:具有私有仓库读取权限的 GitHub 令牌。
```yaml
name: Run Gosec
on:
push:
branches:
- master
pull_request:
branches:
- master
jobs:
tests:
runs-on: ubuntu-latest
env:
GO111MODULE: on
GOPRIVATE: github.com/your-org/*
GITHUB_AUTHENTICATION_TOKEN: ${{ secrets.PRIVATE_REPO_TOKEN }}
steps:
- name: Checkout Source
uses: actions/checkout@v3
- name: Run Gosec Security Scanner
uses: securego/gosec@v2
with:
args: ./...
```
### 与代码扫描集成
你可以通过将数据作为 SARIF 文件上传,将[第三方代码分析工具](https://docs.github.com/en/github/finding-security-vulnerabilities-and-errors-in-your-code/integrating-with-code-scanning)与 GitHub 代码扫描集成。
该工作流展示了一个示例:在 GitHub action 工作流中将 `gosec` 作为一步运行,并输出 `results.sarif` 文件。随后,该工作流使用 `upload-sarif` action 将 `results.sarif` 文件上传到 GitHub。
```yaml
name: "Security Scan"
# Run workflow each time code is pushed to your repository and on a schedule.
# The scheduled workflow runs every at 00:00 on Sunday UTC time.
on:
push:
schedule:
- cron: '0 0 * * 0'
jobs:
tests:
runs-on: ubuntu-latest
env:
GO111MODULE: on
steps:
- name: Checkout Source
uses: actions/checkout@v3
- name: Run Gosec Security Scanner
uses: securego/gosec@v2
with:
# we let the report trigger content trigger a failure using the GitHub Security features.
args: '-no-fail -fmt sarif -out results.sarif ./...'
- name: Upload SARIF file
uses: github/codeql-action/upload-sarif@v2
with:
# Path to SARIF file relative to the root of the repository
sarif_file: results.sarif
```
### Go 分析
`goanalysis` 包提供了一个
[`golang.org/x/tools/go/analysis.Analyzer`](https://pkg.go.dev/golang.org/x/tools/go/analysis),
用于与支持标准 Go
分析接口的工具集成,例如 Bazel 的
[nogo](https://github.com/bazelbuild/rules_go/blob/master/go/nogo.rst)
框架:
```starlark
nogo(
name = "nogo",
deps = [
"@com_github_securego_gosec_v2//goanalysis",
# add more analyzers as needed
],
visibility = ["//visibility:public"],
)
```
### 本地安装
gosec 需要 Go 1.25 或更高版本。
```bash
go install github.com/securego/gosec/v2/cmd/gosec@latest
```
## 快速开始
```bash
# Scan all packages in current module
gosec ./...
# Write JSON report
gosec -fmt json -out results.json ./...
# Write SARIF report for code scanning
gosec -fmt sarif -out results.sarif ./...
```
### 退出码
- `0`:扫描完成,没有未抑制的发现/错误
- `1`:至少有一个未抑制的发现或处理错误
- 使用 `-no-fail` 以始终返回 `0`
## 用法
Gosec 可以配置为仅运行一部分规则、排除某些文件路径,并以不同格式生成报告。默认情况下,所有规则都会针对提供的输入文件运行。要从当前目录递归扫描,可以将 `./...` 作为输入参数提供。
### 可用规则
gosec 包含以下类别的规则:
- `G1xx`:通用安全编码问题(例如硬编码凭据、不安全用法、HTTP 加固、Cookie 安全)
- `G2xx`:查询/模板/命令构造中的注入风险
- `G3xx`:文件和路径处理风险(权限、路径遍历、临时文件、归档解压)
- `G4xx`:加密和 TLS 弱点
- `G5xx`:黑名单导入
- `G6xx`:Go 特有的正确性/安全检查(例如 range 别名和切片边界)
- `G7xx`:污点分析规则(SQL 注入、命令注入、路径遍历、SSRF、XSS、日志注入、SMTP 注入、SSTI、不安全反序列化和开放重定向)
有关完整列表、规则描述和逐规则配置,请参阅 [RULES.md](https://github.com/securego/gosec/blob/master/RULES.md)。
### 已停用规则
- G105:审计 math/big.Int.Exp 的使用 -
[CVE 已修复](https://github.com/golang/go/issues/15184)
- G307:延迟调用返回错误的方法 - 相比修复安全问题带来更多不便,尽管有这篇
[博客文章](https://www.joeshaw.org/dont-defer-close-on-writable-files/)
中的细节
### 选择规则
默认情况下,gosec 会针对提供的文件路径运行所有规则。不过,可以通过 `-include=` 标志选择要运行的规则子集,或使用 `-exclude=` 标志明确指定要排除的一组规则。
```bash
# Run a specific set of rules
$ gosec -include=G101,G203,G401 ./...
# Run everything except for rule G303
$ gosec -exclude=G303 ./...
```
### CWE 映射
`gosec` 检测到的每个问题都会映射到一个
[CWE(通用缺陷枚举)](http://cwe.mitre.org/data/index.html),
它以更通用的术语描述该漏洞。确切的映射关系可以在
[此处](https://github.com/securego/gosec/blob/master/issue/issue.go#L50)找到。
### 配置
可以在配置文件中提供若干全局设置,如下所示:
```JSON
{
"global": {
"nosec": "enabled",
"audit": "enabled"
}
}
```
- `nosec`:此设置将覆盖整个代码库中定义的所有 `#nosec` 指令
- `audit`:以审计模式运行,该模式会启用一些额外的检查,而这些检查对于常规代码分析来说可能过于繁琐
```bash
# Run with a global configuration file
$ gosec -conf config.json .
```
### 基于路径的规则排除
包含多个组件的大型仓库可能需要针对不同路径应用不同的安全规则。使用 `exclude-rules` 来抑制特定路径下的特定规则。
**配置文件:**
```json
{
"exclude-rules": [
{
"path": "cmd/.*",
"rules": ["G204", "G304"]
},
{
"path": "scripts/.*",
"rules": ["*"]
}
]
}
```
**CLI 标志:**
```bash
# Exclude G204 and G304 from cmd/ directory
gosec --exclude-rules="cmd/.*:G204,G304" ./...
# Exclude all rules from scripts/ directory
gosec --exclude-rules="scripts/.*:*" ./...
# Multiple exclusions
gosec --exclude-rules="cmd/.*:G204,G304;test/.*:G101" ./...
```
| 字段 | 类型 | 描述 |
|-------|------|-------------|
| `path` | string (regex) | 与文件路径匹配的正则表达式 |
| `rules` | []string | 要排除的规则 ID。`*` 表示全部 |
#### 规则配置
部分规则还接受配置标志;这些标志记录在
[RULES.md](https://github.com/securego/gosec/blob/master/RULES.md) 中。
#### Go 版本
部分规则需要特定的 Go 版本,该版本从项目中存在的 Go 模块文件中获取。如果无法找到该版本,则会回退到 Go 运行时版本。
Go 模块版本通过 `go list` 命令解析,在某些情况下这可能导致性能下降。在这种情况下,可以通过设置环境变量 `GOSECGOVERSION=go1.21.1` 轻松提供 Go 模块版本。
### 依赖
gosec 使用 Go 模块加载包。在大多数项目中,依赖会在扫描期间自动解析。
如果缺少依赖,请运行:
```bash
go mod tidy
go mod download
```
### 排除测试文件和文件夹
gosec 将忽略所有包中的测试文件以及
vendor 目录中的任何依赖项。
可以使用以下标志启用对测试文件的扫描:
```bash
gosec -tests ./...
```
此外,还可以按如下方式排除其他文件夹:
```bash
gosec -exclude-dir=rules -exclude-dir=cmd ./...
```
### 排除生成的文件
gosec 可以通过默认的生成代码注释来忽略生成的 go 文件。
```
// Code generated by some generator DO NOT EDIT.
```
```bash
gosec -exclude-generated ./...
```
### 自动修复漏洞
gosec 可以基于 AI 建议提供修复方案。它会调用 AI API 来获取针对安全发现项的建议。
你可以通过提供以下命令行参数来启用此功能:
- `ai-api-provider`:AI API 提供商的名称。
支持的提供商:
- **Atlas Cloud**:`atlas`(默认模型
`deepseek-ai/deepseek-v4-flash`)、
`atlas-deepseek-v4-flash`、
`atlas-qwen3-coder-next`、`atlas-kimi-k2.6`,或
`atlas:<model-id>` 用于任意 Atlas Cloud 托管的聊天模型。
Atlas Cloud 是一个兼容 OpenAI 的提供商,可通过
[atlascloud.ai](https://www.atlascloud.ai/?utm_source=github&utm_medium=link&utm_campaign=gosec) 访问
- **Gemini**:`gemini-3.1-pro-preview`(默认)、
`gemini-2.5-pro`、`gemini-2.5-flash`、
`gemini-2.5-flash-lite`
- **Claude**:`claude-sonnet-4-6`(默认)、
`claude-opus-4-7`、`claude-opus-4-6`、
`claude-sonnet-4-5`、`claude-opus-4-5`、
`claude-haiku-4-5`
- **OpenAI**:`gpt-5.4`(默认)、`gpt-5.4-mini`、
`gpt-5.4-nano`
- **自定义 OpenAI 兼容**:任意自定义模型名称
(需要 `ai-base-url`)
- `ai-api-key` 或设置环境变量
`GOSEC_AI_API_KEY`:访问 AI API 的密钥
- 对于 Gemini,你可以按照
[这些说明](https://ai.google.dev/gemini-api/docs/api-key)创建 API 密钥
- 对于 Claude,请从
[Anthropic Console](https://console.anthropic.com/) 获取你的 API 密钥
- 对于 OpenAI,请从
[OpenAI Platform](https://platform.openai.com/api-keys) 获取你的 API 密钥
- `ai-base-url`:(可选)用于
OpenAI 兼容 API 的自定义基础 URL(例如 Azure OpenAI、LocalAI、
Ollama)
- Atlas Cloud 默认使用 `https://api.atlascloud.ai/v1`,
因此对于内置的 `atlas`
提供商,`ai-base-url` 是可选的
- `GOSEC_AI_PROVIDER`:(可选)环境变量,
作为 `ai-api-provider` 的替代
- `GOSEC_AI_BASE_URL`:(可选)环境变量,
作为 `ai-base-url` 的替代
- `ai-skip-ssl`:(可选)跳过 AI API 的 SSL 证书验证
(适用于自签名证书)
> 🎁 **[Atlas Cloud](https://www.atlascloud.ai/?utm_source=github&utm_medium=link&utm_campaign=gosec)** 是一个全模态 AI 推理平台,为开发者提供统一的 AI API,用于访问视频生成、图像生成和 LLM API。你无需管理多个供应商集成,只需连接一次即可统一访问跨所有模态的 300+ 精选模型。
>
> 查看 Atlas Cloud 新的编码计划促销活动,获取更经济实惠的 API 访问: [https://www.atlascloud.ai/console/coding-plan](https://www.atlascloud.ai/console/coding-plan)
**示例:**
```bash
# Using Atlas Cloud with the default DeepSeek V4 Flash model
export GOSEC_AI_API_KEY="your_key"
export GOSEC_AI_PROVIDER="atlas"
gosec ./...
# Using Atlas Cloud with an explicit hosted model
GOSEC_AI_API_KEY="your_key" \
gosec -ai-api-provider="atlas:qwen/qwen3-coder-next" ./...
# Using Gemini
gosec -ai-api-provider="gemini-3.1-pro-preview" \
-ai-api-key="your_key" ./...
# Using Claude
gosec -ai-api-provider="claude-sonnet-4-6" \
-ai-api-key="your_key" ./...
# Using OpenAI
gosec -ai-api-provider="gpt-5.4" \
-ai-api-key="your_key" ./...
# Using Azure OpenAI
gosec -ai-api-provider="gpt-5.4" \
-ai-api-key="your_azure_key" \
-ai-base-url="https://your-resource.openai.azure.com/openai/deployments/your-deployment" \
./...
# Using local Ollama with custom model
gosec -ai-api-provider="llama3.2" \
-ai-base-url="http://localhost:11434/v1" \
./...
# Using self-signed certificate API
gosec -ai-api-provider="custom-model" \
-ai-api-key="your_key" \
-ai-base-url="https://internal-api.company.com/v1" \
-ai-skip-ssl \
./...
```
### 为代码添加注解
与所有自动化检测工具一样,也会出现误报的情况。当 gosec 报告了一个失败项,但经人工核实确认其安全时,可以用以 `#nosec` 开头的注释对代码进行标注。
`#nosec` 注释的格式应为
`#nosec [RuleList] [-- Justification]`。
`#nosec` 注释需要放在报告警告所在的那一行。
```go
func main() {
tr := &http.Transport{
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true, // #nosec G402
},
}
client := &http.Client{Transport: tr}
_, err := client.Get("https://go.dev/")
if err != nil {
fmt.Println(err)
}
}
```
当已识别并验证某个特定的误报为安全时,你可能希望仅在代码的某个部分中抑制该单条规则(或一组特定规则),同时继续扫描其他问题。为此,你可以在 `#nosec` 注释中列出要抑制的规则,例如:`/* #nosec G401 */` 或 `//#nosec G201 G202 G203`
你可以为注释添加描述或理由文本。理由应放在要抑制的规则之后,并以两个或更多短横线开头,例如:`//#nosec G101 G102 -- This is a false positive`
或者,gosec 也支持 `//gosec:disable` 指令,其功能类似于 `#nosec`:
```go
//gosec:disable G101 -- This is a false positive
```
在某些情况下,你可能还想重新审视那些使用了 `#nosec` 或 `//gosec:disable` 注解的位置。要运行扫描器并忽略所有 `#nosec` 注解,你可以执行以下操作:
```bash
gosec -nosec=true ./...
```
#### 要求规则 ID 和理由说明
为防止注解无意中抑制无关规则,或在没有解释的情况下被添加,gosec 接受两个可选启用的标志。两者默认均为 `false`,因此现有代码库可保持不变继续工作。
- `-nosec-require-rules` 拒绝未列出任何规则 ID 的裸 `#nosec` / `//gosec:disable` 指令。
- `-nosec-require-justification` 拒绝在规则列表之后未携带 `-- justification` 的指令。
启用后,未通过检查的指令不再抑制任何发现,并会在输出中作为错误报告,同时报告该行上的任何底层问题。
```bash
gosec -nosec-require-rules -nosec-require-justification ./...
```
可以通过全局配置块设置相同的选项:
```json
{
"global": {
"nosec-require-rules": "enabled",
"nosec-require-justification": "enabled"
}
}
```
### 跟踪抑制
如上所述,我们可以从外部抑制违规(使用 `-include`/`-exclude`)或在行内抑制(使用 `#nosec` 注解)。可以输出抑制元数据以供审计。
使用 `-track-suppressions` 启用抑制跟踪:
```bash
gosec -track-suppressions -exclude=G101 \
-fmt=sarif -out=results.sarif ./...
```
- 对于外部抑制,gosec 会记录抑制信息,其中 `kind` 为 `external`,`justification` 为 `Globally suppressed.`。
- 对于内联抑制,gosec 会记录抑制信息,其中 `kind` 为 `inSource`,`justification` 为注释中两个或更多破折号之后的文本。
**注意:** 只有 SARIF 和 JSON 格式支持跟踪抑制。
### 构建标签
gosec 能够将你的
[Go 构建标签](https://pkg.go.dev/go/build/) 传递给分析器。
它们可以以逗号分隔列表的形式提供,如下所示:
```bash
gosec -tags debug,ignore ./...
```
### 输出格式
gosec 支持 `text`、`json`、`yaml`、`csv`、`junit-xml`、
`html`、`sonarqube`、`golint` 和 `sarif`。默认情况下,
结果会输出到 stdout,但也可以写入
输出文件。输出格式由 `-fmt`
标志控制,输出文件由 `-out` 标志控制,具体
如下:
```bash
# Write output in json format to results.json
$ gosec -fmt=json -out=results.json *.go
```
使用 `-stdout` 在写入 `-out` 的同时打印结果。
使用 `-verbose` 覆盖 stdout 格式,同时保留
文件格式。
```bash
# Write output in json format to results.json as well as stdout
$ gosec -fmt=json -out=results.json -stdout *.go
# Overrides the output format to 'text' when stdout the results,
# while writing it to results.json
$ gosec -fmt=json -out=results.json -stdout -verbose=text *.go
```
**注意:** gosec 会为 SonarQube 生成
[通用问题导入格式](https://docs.sonarqube.org/latest/analysis/generic-issue/),
并且必须使用
`sonar.externalIssuesReportPaths=path/to/gosec-report.json`
将报告导入 SonarQube。
## 常见用法模式
```bash
# Fail only on medium+ severity findings
gosec -severity medium ./...
# Fail only on medium+ confidence findings
gosec -confidence medium ./...
# Exclude specific rules for specific paths
gosec --exclude-rules="cmd/.*:G204,G304;scripts/.*:*" ./...
# Exclude generated files in scan
gosec -exclude-generated ./...
# Include test files in scan
gosec -tests ./...
```
## 开发
开发文档已移至
[DEVELOPMENT.md](https://github.com/securego/gosec/blob/master/DEVELOPMENT.md)。
## 谁在使用 gosec?
这是一个包含部分 gosec 用户的[列表](https://github.com/securego/gosec/blob/master/USERS.md)。
## 赞助商
通过成为赞助商来支持本项目。您的徽标将
显示在此处,并附有指向您网站的链接
<a href="https://github.com/mercedes-benz" target="_blank"><img src="https://assets.kitploit.com/production/public/readmes/2947/08b6f9da5faff0e986172b0c77fed0865a2cb26e6f8c58a8ae588c74bcf16f5f.png"></a>