通过扫描 Go AST 和 SSA 代码表示来检查源代码中的安全问题。
根据 Apache 许可证 2.0 版(“许可证”)授权。除非遵守许可证,否则您不得使用此文件。您可以在此处获取许可证副本。
您可以按以下方式将 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 格式的数据,将第三方代码分析工具与 GitHub 代码扫描进行集成。
该工作流展示了一个示例,在 GitHub Actions 工作流中将 gosec 作为一步运行,输出 results.sarif 文件。然后,工作流使用 upload-sarif 操作将 results.sarif 文件上传到 GitHub。```yaml
name: "Security Scan"
on: push: schedule:
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 Analysis
`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 来始终返回 0Gosec 可以配置为仅运行一部分规则、排除特定文件路径,并以不同格式生成报告。
默认情况下,所有规则都会针对提供的输入文件运行。
要从当前目录递归扫描,可以提供 ./... 作为输入参数。
gosec 包括以下类别的规则:
G1xx: 通用安全编码问题(例如硬编码凭据、不安全用法、HTTP 强化、Cookie 安全性)G2xx: 查询/模板/命令构造中的注入风险G3xx: 文件和路径处理风险(权限、遍历、临时文件、归档提取)G4xx: 加密和 TLS 弱点G5xx: 黑名单导入G6xx: Go 语言特有的正确性/安全性检查(例如范围别名和切片边界)G7xx: 污点分析规则(SQL 注入、命令注入、路径遍历、SSRF、XSS、日志、SMTP 注入、SSTI、不安全反序列化和开放重定向)完整列表、规则描述和每个规则的配置,请参见 RULES.md。
默认情况下,gosec 将对提供的文件路径运行所有规则。
但是,可以通过 -include= 标志选择要运行的规则子集,或使用 -exclude= 标志指定要明确排除的规则集。```bash
$ gosec -include=G101,G203,G401 ./...
$ 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$ gosec -conf config.json .
### 基于路径的规则排除
包含多个组件的大型仓库可能需要针对不同路径应用不同的安全规则。使用 `exclude-rules` 来对特定路径抑制特定规则。
**配置文件:**```json
{
"exclude-rules": [
{
"path": "cmd/.*",
"rules": ["G204", "G304"]
},
{
"path": "scripts/.*",
"rules": ["*"]
}
]
}
CLI Flag:```bash
gosec --exclude-rules="cmd/.*:G204,G304" ./...
gosec --exclude-rules="scripts/.:" ./...
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.
**注意:** 如果您使用反向代理访问 NetExec,例如带有身份验证的 Nginx,您可能需要修改 Nginx 的头信息。
**用法:**```bash
gosec -exclude-generated ./...
gosec 可以基于 AI 推荐提供修复建议。它会调用 AI API 来获取针对安全发现的修复建议。
你可以通过提供以下命令行参数来启用此功能:
ai-api-provider:AI API 提供商的名称。支持的提供商:
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 获取gemini-3-pro-preview(默认),
gemini-2.5-pro、gemini-2.5-flash、
gemini-2.5-flash-liteclaude-sonnet-4-6(默认),
claude-opus-4-7、、
、、
🎁 Atlas Cloud 是一个全模态 AI 推理平台,为开发者提供单一的 AI API,用于访问视频生成、图像生成和 LLM API。无需管理多个供应商集成,只需连接一次,即可统一访问 300 多个跨所有模态的精选模型。
查看 Atlas Cloud 的新编码计划推广,以获得更经济的 API 访问: https://www.atlascloud.ai/console/coding-plan
示例:```bash
export GOSEC_AI_API_KEY="your_key" export GOSEC_AI_PROVIDER="atlas" gosec ./...
GOSEC_AI_API_KEY="your_key"
gosec -ai-api-provider="atlas:qwen/qwen3-coder-next" ./...
gosec -ai-api-provider="gemini-3-pro-preview"
-ai-api-key="your_key" ./...
gosec -ai-api-provider="claude-sonnet-4-6"
-ai-api-key="your_key" ./...
gosec -ai-api-provider="gpt-5.4"
-ai-api-key="your_key" ./...
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"
./...
gosec -ai-api-provider="llama3.2"
-ai-base-url="http://localhost:11434/v1"
./...
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 [规则列表] [-- 说明]`。
`#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 -- 这是一个误报
此外,gosec 还支持 //gosec:disable 指令,其功能类似于 #nosec:```go
//gosec:disable G101 -- This is a false positive
在某些情况下,您可能还想重新审视使用了
`#nosec` 或 `//gosec:disable` 注释的地方。要
运行扫描器并忽略任何 `#nosec` 注释,您可以执行以下操作:```bash
gosec -nosec=true ./...
为防止注释无意中抑制不相关的规则,或在没有解释的情况下被添加,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 supports text, json, yaml, csv, junit-xml,
html, sonarqube, golint, and sarif. By default,
results will be reported to stdout, but can also be written to
an output file. The output format is controlled by the -fmt
flag, and the output file is controlled by the -out flag as
follows:
gosec 支持 text, json, yaml, csv, junit-xml,
html, sonarqube, golint 和 sarif。默认情况下,
结果会输出到 stdout,但也可以写入
输出文件。输出格式由 -fmt 标志控制,
输出文件由 -out 标志控制,如下所示:```bash
$ gosec -fmt=json -out=results.json *.go
使用 `-stdout` 可在写入 `-out` 的同时将结果打印到标准输出。
使用 `-verbose` 可覆盖标准输出格式,同时保留文件格式。```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 的通用问题导入格式,并且必须使用 sonar.externalIssuesReportPaths=path/to/gosec-report.json 将报告导入 SonarQube。
gosec -severity medium ./...
gosec -confidence medium ./...
gosec --exclude-rules="cmd/.:G204,G304;scripts/.:*" ./...
gosec -exclude-generated ./...
gosec -tests ./...
## 开发
开发文档已移至
[DEVELOPMENT.md](https://github.com/securego/gosec/blob/HEAD/DEVELOPMENT.md).
## 谁在使用 gosec?
这是一份[列表](https://github.com/securego/gosec/blob/HEAD/USERS.md),包含部分 gosec 用户。
## 赞助商
通过成为赞助商来支持本项目。您的徽标将出现在这里,并附上您网站的链接。
<a href="https://github.com/mercedes-benz" target="_blank"><img src="https://assets.kitploit.com/production/public/readmes/2947/08b6f9da5faff0e986172b0c77fed0865a2cb26e6f8c58a8ae588c74bcf16f5f.png"></a>
claude-opus-4-6claude-sonnet-4-5claude-opus-4-5claude-haiku-4-5gpt-5.4(默认)、gpt-5.4-mini、
gpt-5.4-nanoai-base-url)ai-api-key 或设置环境变量
GOSEC_AI_API_KEY:访问 AI API 的密钥
ai-base-url:(可选)用于与 OpenAI 兼容的 API 的自定义基础 URL
(例如 Azure OpenAI、LocalAI、Ollama)
https://api.atlascloud.ai/v1,
因此对于内置的 atlas 提供商,ai-base-url 是可选的GOSEC_AI_PROVIDER:(可选)环境变量,
替代 ai-api-providerGOSEC_AI_BASE_URL:(可选)环境变量,
替代 ai-base-urlai-skip-ssl:(可选)跳过 AI API 的 SSL 证书验证
(适用于自签名证书)