gosec

securegoApache-2.0活跃维护

Go 语言的静态安全扫描器,检查源码中的常见安全漏洞和危险写法,可接入 CI 做安全自动化。

Go security checker

v2.30.0发布于 2026-10-23 09:22 UTC9,002star +1 / 7 天731fork同步于 2026-11-10 11:31 UTC

怎么上手

由 README 提炼,执行前请确认
go install github.com/securego/gosec/v2/cmd/gosec@latest
gosec ./...
硬件要求按 README 说明

纯静态分析工具,README 未说明硬件要求;需 Go 1.25 或更新版本。

下载:源码 zip·GitHub Releases(安装包)本站不镜像安装包

项目说明

由 README 自动翻译提炼

扫描 Go 源码 AST 与 SSA 的静态安全检测工具,帮你在提交前发现注入、弱加密等问题

Go 语言的静态安全扫描器,检查源码中的常见安全漏洞和危险写法,可接入 CI 做安全自动化。

核心能力

  • 基于模式规则检测 Go 代码常见安全问题
  • 用 SSA 分析器检查类型转换、切片边界与加密问题
  • 污点分析追踪用户输入到危险函数的数据流
  • 支持 text、json、sarif 等多种报告格式
  • 可按严重度、置信度、规则和路径过滤扫描结果

容易踩的坑

需要 Go 1.25 或更新版本才能安装;默认有未抑制的发现时退出码为 1,会中断 CI,可用 -no-fail 改为始终返回 0;扫描私有模块时需配置 GOPRIVATE 和 GITHUB_AUTHENTICATION_TOKEN。

内容由模型根据 README 生成,可能不完整或不准确,以官方文档为准。看原文 README

最近发版

5 个版本v2.30.0
  1. v2.30.0最新正式版2026-10-23 · 2026-10-23 09:22 UTC

    Changelog

    • 5eb1d104ef85ff2c905c877eb600e8c1dee33a22 fix(g602): recognize equality comparison in minimumLenForBranch (#1796)
    • cc750ddcf0d2219e121034f86db3c6c2f3c76d50 fix(G112): honor read timeouts assigned through a struct field (#1798)
    • 1cbfd7e6488c2464f18603623354de1be9565b39 fix(G112): report read timeouts explicitly set to zero (#1797)
    • 05b9c4c0a7f49e421d7a459922a11bc0c0dd7197 feat(G706): extend log/slog method coverage (#1795)
    • 17ad2dd7533fd4c773d916e2bc81446917d593b5 fix(autofix): read the first text block of a Claude response (#1794)
    • b23171c64c662de0bc757c17feced6f4c10a877e fix(autofix): give every AI request its own timeout (#1793)
    • 20b9e5b1bcc56518b240bf1afc333d6589163cae fix(resolve): treat constants from other packages as resolved (#1792)
    • 86d3c26c060940ea7b6832c3b0d41e8ebf07a146 fix(autofix): return an error when a Gemini candidate has no content (#1791)
    • 14ef84f6feccf40be7f5092fd2db119bf3f5f836 Update to go version 1.27.3 and 1.26.10 (#1790)
    • 7cbd7a927365c48badf18bfb118e5503d606351f fix(autofix): default Gemini model to gemini-3.1-pro-preview (#1788)
    • 1e26bcef55d71e330db7ca5e494be6165ffbc35f fix(G102): resolve concatenated and constant listen addresses (#1787)
    • 836dbdb55d40238f021780afc91c237898db85e3 fix: default -concurrency to GOMAXPROCS so container CPU limits apply (#1786)
    • bbd69e23f657862f7e6d615dd8ba077663d593a3 fix(g602): track statically known lengths for append results in slice bounds check (#1773)
    • 30e2d38421dc927e1f4f7148dcb822c1308cf4cc feat(rules): add G125 to detect unescaped url.JoinPath elements (#1777)
    • 57c45b800aa0cbd12994ea142537673fd15d54b8 fix: load absolute file paths so nested modules are analysed from the parent directory (#1779)
    • 77fa84e3a47a5532d6893467f3df13d2af907541 fix(G118): treat a cancel sent on a channel as handed off (#1782)
    • ca547ab2f2c6c7c378bbb91e76e5b97321b55934 fix(G112): honor read timeouts assigned after the http.Server literal (#1781)
    • 024084bafcb4182ad1c0af86134aa71a819d6f52 fix(G303): resolve constant temp file paths (#1784)
    • 782eeb188eebedaf2335f3adac7052d106670324 fix(deps): update all dependencies (#1783)
    • 707f2271f66579a18e1da25794b1e8012247274b fix(G203): treat constant template arguments as safe (#1770)
    • 8c5daa67d0e2bec9069da20146b0e928fb9fa53b fix(G402): check TLS settings assigned through a *tls.Config (#1769)
    • 71577268350e1e0f2f1491de1ef53f1227b43c1f fix(deps): update all dependencies (#1775)
    • 7b1b5cebe007d62fb58eacb90fc571112939ec30 Update to go version 1.27.2 and 1.26.9 (#1772)
    • d2b649ec01825c20bd101ec584e559adb287e578 Keep SARIF driver rules sorted and resolve rule indexes at the end (#1767)
    • 1f52e64f6dfe434ae4261574baa9495c2532a6de fix(G602): track append() results for slice bounds checking (#1754)
    • ea75d9ff49b6bbea15f0eb5e0483408a553019a6 fix(deps): update all dependencies (#1768)
    • 65c2c082857febe898116edeb1fcddea0193634a fix(G602): trust len(nilSlice) == N guards, matching make()-backed slices (#1752)
    • 6ff893e9ef3f172b24f235acba2a31dab66fa379 fix(G407): treat an array IV/nonce as a zeroed buffer (#1763)
    • aaca8946492fb2a6ff3598c185ff97776e12ea6f fix(fileperms): resolve constant file and directory permissions (#1766)
    • 826f6f4fd18b7b0cf0a76b2df1994b3eb90da8f3 fix(G102): detect binding to the IPv6 unspecified address (#1760)
    • 021cc2eae58ed8ea0160ca8beab93648daefc0e7 fix(G407): stop the nonce source walk on cycles (#1761)
    • ccb369da13791bade6e735e70e833d0d095b7db0 fix(G407): do not count AEAD.Seal as the read that fills its own nonce (#1762)
    • 9b318063d35cfc5cdf2456de3b92830270e80326 fix(deps): update all dependencies (#1764)
    • 8c77519419e934a3e158dbf1a3fbbc0871b8c691 fix(G602): validate inequality len guards (#1757)
    • 027baa29ac97f58e9200d664d4ba63c9ea47a5ae fix(G121): track request captured by closures (#1759)
    • 9ede89eea46b783aa0a1d28804b817c6d57ff36d fix(deps): update all dependencies (#1756)
    • 29a042eca11db9ff0b3985146c5dd3ac46bbd24e fix: make nosec suppression independent of comment order (#1741)
    • 681347199262bc33b9b5
  2. v2.29.02026-08-26 · 2026-08-26 08:34 UTC
    查看更新说明

    Changelog

    • deb54465fea23d19a77f037e11e6589021f8501d analyzers/G703: stop treating Clean/Abs/PathEscape as path-traversal sanitizers (#1723)
    • 2e13f16ff12497b4af18e915ba3f819916828e9e fix(junit): properly escape XML in failure text (#1718)
    • 38330372ed9a6b612bfd988ff4ecc050cc24abef fix(csv): capture and report write errors on flush (#1716)
    • f6d07d7887600938dace7f29e1b11a09130a5ac9 fix(report): root path matching in formatters (#1719)
    • 17d3916e34a3d052b67f88fcccae9f1e43730bac fix(config): handle nosec tags with leading hash (#1717)
    • 3958f0ed831c3020752ed07e45a8a24a531edd91 Update all dependencies (#1720)
    • 9c38a8648388bc22c13673207ac091df80100be2 Add support for go version 1.27.0 and update to version 1.25.14 and 1… (#1726)
    • 2eb4727ebc7504944ddbcdd2f7157db492026c3f Update all dependencies (#1713)
    • 5e72efc19d97e11549b3427b83fab3257a8c9894 Update all dependencies (#1710)
    • 45b083a0cb42119d61b1e0e364d8c62c68f6f5cd fix(G202): don't flag strings.Builder built from constants (#1707)
    • 82da19cc73c6fb5034aaab7a779a2ef1b123c791 ci: allow fork PR checkout in barry-ai-security-review job (#1708)
    • 9f7cd131bdd1160cd7c0205d89856ebd99530da7 Update all dependencies (#1709)
    • 1769a22fd149bfd9e5e546e06a7f9d596eab2f65 Downgrade min Go version (#1706)
    • 5bb2909d48fa8072136f38ad329b37575ab15c9f Udpate action to use gosec v2.28.0 (#1705)
  3. v2.28.02026-07-14 · 2026-07-14 11:26 UTC
    查看更新说明

    Changelog

    • 9e75c0576c9878035d4221392108d458abe10fc3 feat(G101): detect AWS temporary access keys (#1702)
    • 14f493ab92f212e1f3d69aeaa561989e5baf9d6f Update to go version 1.26.5 and 1.25.12 (#1704)
    • ffd5ba1d3354928fae89ac31912bd1d730798799 Update all dependencies (#1703)
    • 849570622f56a251c015c0e2417aebafc0216e17 Update all dependencies (#1699)
    • 11023e51e1f46c4ea63315bdb7670f073442168f Update all dependencies (#1698)
    • f88a0781159d73052ba792962e624749904783d6 fix: min+max G115 false positives (#1697)
    • 6a008f60b8f7f3d7fae8f126984a9df5d4b7e0cf Update all dependencies (#1696)
    • caf8857bbd3276599d0176b0528e9712bb0b5bec fix(G404): flag missing math/rand weak-random functions (#1694)
    • cbef395cb1e2e3a35f6223f5b97f1657f7144797 Update all dependencies (#1695)
    • f1c81de5fcdf7b466b229fb24ca02d1a8406dd09 Update all dependencies (#1693)
    • 9addc97cefc9460a114e3c36f536b935da3b98c9 Update to go version 1.26.4 and 1.25.11 (#1690)
    • 92ed8df32846e85d4e81b0b62012567afddfdc95 Update the gosec in the Github action to v2.27.1 (#1688)
  4. v2.27.12026-06-01 · 2026-06-01 17:24 UTC
    查看更新说明

    Changelog

    • 9e6a9843d7a4a6e3e9a8539b02612c8a4aa3f889 Downgrade google lib to avoid min Go version bump (#1687)
  5. v2.27.02026-06-01 · 2026-06-01 08:21 UTC
    查看更新说明

    Changelog

    • 0a5c6504c46569257663726ac54c7cfdad42e846 Downgrade the jsonschema dep to v0.13.0 due to incompatibility with anthropick-sdk-go (#1686)
    • b48e668764ca9fd826a7b84c9e9194af3227fade Update all dependencies (#1685)
    • bd17b2589eb634e511b352f14fc30cb40863eefe Downgrade the github.com/invopop/jsonschema v0.13.0 to solve incopatibility with anthropic-sdk (#1683)
    • c6f8c3d9a75d897612c7beb55007ac5f29b2e3a2 Update all dependencies (#1682)
    • 5676cbccda635b33fab15bb85e32b2e741c9372f Update vulnerabilities alerts for indirect dependencies
    • ce167d4a37bc5fe3f49bb9be3209f9759b69ff6f Pin dependencies (#1681)
    • 74b726dfcebf218a1984a51b44fe962aecef5921 Skip pining for my repos
    • a68f8825bfa51b46cc517a5cd8baf4848e03a8d1 Update renovate configuration
    • 2f8791bad7bf8f6a11f0b29e41aec54ddb9fcb0b Fix typo
    • ad3778a7be907bf4e5cf5ed5c63333a377f3fb3b Update branch config in renovate config
    • b1583fe2f3ffb41074cb11996e58ca554c6c04e7 Migrate config renovate.json (#1678)
    • 139e33d474374c8e26a0e480f077526e131f43bb Update renovate to refresh the branch creation
    • f3c03ebb7f077f9b9ddfc64f710e0a2d2e92ded4 Update the renovate branch prefix
    • 85814f2e3964a6d38aeb6e6002ac9268c16fcab5 Update renovate config to pin the actions dependencies by digests (#1676)
    • 55f051973281b15900b2b8b30aaf467a7b9127ea Migrate the html remport to react v19. (#1675)
    • 6ad4476d269895a4a9b77883b3e3503f7e5e4103 Manually update version to fix renovate (#1674)
    • 8f88312a5f80dbf04d2248d75c372d165e54e589 feat: integrate Atlas Cloud provider (#1672)
    • 6351b0c6fcc7d75acb230a9be7f9047aada322ae Refactor error position parsing to support path with colon. (#1673)
    • de65614d10a6b84029e3e1215567b8ce7e490f23 Add two options to require rule ID and justificaiton for inline annotations (#1671)
    • e354c572d957eb8bf63481cc9ba2704b58a6ae35 Fix false positive in G118 when cancel is stored in a slice/map (#1670)
    • 4161f0b4333859990584c9fb3fd377a892eaf477 chore(go): update supported Go versions to 1.25.10 and 1.26.3 (#1669)
    • b4f29347566880540afec8205b633d2859377cec Harden the github workflows and action (#1665)
    • b7aca268861108d4446959fa92d2fe808eb7aa6f Fix justification delimiter in annotation format doc (#1661)
    • 945bce72d26a794e25a122d87527d063bf887903 Update all dependencies (#1664)
    • 5f4eec95fa28ce5dc6cf555de8c242cb57545f01 Update action to use gosec version v2.26.1 (#1660)

用户点评

登录用户的真实使用记录,可按版本和硬件筛选
共 0 条

    还没有人点评。第一个说出真实体验的人最有价值。

    README 原文

    未翻译

    gosec - Go Security Checker

    Inspects source code for security problems by scanning the Go AST and SSA code representation.

    Quick links

    Features

    • Pattern-based rules for detecting common security issues in Go code
    • SSA-based analyzers for type conversions, slice bounds, and crypto issues
    • Taint analysis for tracking data flow from user input to dangerous functions (SQL injection, command injection, path traversal, SSRF, XSS, log injection, SMTP injection, SSTI, unsafe deserialization, open redirect)

    License

    Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with the License. You may obtain a copy of the License here.

    Project status

    CII Best Practices Build Status Coverage Status GoReport GoDoc Docs Downloads GHCR Slack go-recipes

    Installation

    GitHub Action

    You can run gosec as a GitHub action as follows:

    Use the versioned tag with @master which is pinned to the latest stable release. This will provide a stable behavior.

    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: ./...
    
    Scanning Projects with Private Modules

    If your project imports private Go modules, you need to configure authentication so that gosec can fetch the dependencies. Set the following environment variables in your workflow:

    • GOPRIVATE: A comma-separated list of module path prefixes that should be considered private (e.g., github.com/your-org/*).
    • GITHUB_AUTHENTICATION_TOKEN: A GitHub token with read access to your private repositories.
    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: ./...
    

    Integrating with code scanning

    You can integrate third-party code analysis tools with GitHub code scanning by uploading data as SARIF files.

    The workflow shows an example of running the gosec as a step in a GitHub action workflow which outputs the results.sarif file. The workflow then uploads the results.sarif file to GitHub using the upload-sarif action.

    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 Analysis

    The goanalysis package provides a golang.org/x/tools/go/analysis.Analyzer for integration with tools that support the standard Go analysis interface, such as Bazel's nogo framework:

    nogo(
        name = "nogo",
        deps = [
            "@com_github_securego_gosec_v2//goanalysis",
            # add more analyzers as needed
        ],
        visibility = ["//visibility:public"],
    )
    

    Local Installation

    gosec requires Go 1.25 or newer.

    go install github.com/securego/gosec/v2/cmd/gosec@latest
    

    Quick start

    # 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 ./...
    

    Exit codes

    • 0: scan finished without unsuppressed findings/errors
    • 1: at least one unsuppressed finding or processing error
    • Use -no-fail to always return 0

    Usage

    Gosec can be configured to only run a subset of rules, to exclude certain file paths, and produce reports in different formats. By default all rules will be run against the supplied input files. To recursively scan from the current directory you can supply ./... as the input argument.

    Available rules

    gosec includes rules across these categories:

    • G1xx: general secure coding issues (for example hardcoded credentials, unsafe usage, HTTP hardening, cookie security)
    • G2xx: injection risks in query/template/command construction
    • G3xx: file and path handling risks (permissions, traversal, temp files, archive extraction)
    • G4xx: crypto and TLS weaknesses
    • G5xx: blocklisted imports
    • G6xx: Go-specific correctness/security checks (for example range aliasing and slice bounds)
    • G7xx: taint analysis rules (SQL injection, command injection, path traversal, SSRF, XSS, log, SMTP injection, SSTI, unsafe deserialization, and open redirect)

    For the full list, rule descriptions, and per-rule configuration, see RULES.md.

    Retired rules

    • G105: Audit the use of math/big.Int.Exp - CVE is fixed
    • G307: Deferring a method which returns an error - causing more inconvenience than fixing a security issue, despite the details from this blog post

    Selecting rules

    By default, gosec will run all rules against the supplied file paths. It is however possible to select a subset of rules to run via the -include= flag, or to specify a set of rules to explicitly exclude using the -exclude= flag.

    # Run a specific set of rules
    $ gosec -include=G101,G203,G401 ./...
    
    # Run everything except for rule G303
    $ gosec -exclude=G303 ./...
    

    CWE Mapping

    Every issue detected by gosec is mapped to a CWE (Common Weakness Enumeration) which describes in more generic terms the vulnerability. The exact mapping can be found here.

    Configuration

    A number of global settings can be provided in a configuration file as follows:

    {
        "global": {
            "nosec": "enabled",
            "audit": "enabled"
        }
    }
    
    • nosec: this setting will overwrite all #nosec directives defined throughout the code base
    • audit: runs in audit mode which enables addition checks that for normal code analysis might be too nosy
    # Run with a global configuration file
    $ gosec -conf config.json .
    

    Path-Based Rule Exclusions

    Large repositories with multiple components may need different security rules for different paths. Use exclude-rules to suppress specific rules for specific paths.

    Configuration File:

    {
      "exclude-rules": [
        {
          "path": "cmd/.*",
          "rules": ["G204", "G304"]
        },
        {
          "path": "scripts/.*",
          "rules": ["*"]
        }
      ]
    }
    

    CLI Flag:

    # 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" ./...
    
    FieldTypeDescription
    pathstring (regex)Regex matched against file paths
    rules[]stringRule IDs to exclude. * for all
    Rule Configuration

    Some rules accept configuration flags as well; these flags are documented in RULES.md.

    Go version

    Some rules require a specific Go version which is retrieved from the Go module file present in the project. If this version cannot be found, it will fallback to Go runtime version.

    The Go module version is parsed using the go list command which in some cases might lead to performance degradation. In this situation, the go module version can be easily provided by setting the environment variable GOSECGOVERSION=go1.21.1.

    Dependencies

    gosec loads packages using Go modules. In most projects, dependencies are resolved automatically during scanning.

    If dependencies are missing, run:

    go mod tidy
    go mod download
    

    Excluding test files and folders

    gosec will ignore test files across all packages and any dependencies in your vendor directory.

    The scanning of test files can be enabled with the following flag:

    gosec -tests ./...
    

    Also additional folders can be excluded as follows:

     gosec -exclude-dir=rules -exclude-dir=cmd ./...
    

    Excluding generated files

    gosec can ignore generated go files with default generated code comment.

    // Code generated by some generator DO NOT EDIT.
    
    gosec -exclude-generated ./...
    

    Auto fixing vulnerabilities

    gosec can suggest fixes based on AI recommendation. It will call an AI API to receive a suggestion for a security finding.

    You can enable this feature by providing the following command line arguments:

    • ai-api-provider: the name of the AI API provider. Supported providers:
      • Atlas Cloud: atlas (default model deepseek-ai/deepseek-v4-flash), atlas-deepseek-v4-flash, atlas-qwen3-coder-next, atlas-kimi-k2.6, or atlas:<model-id> for any Atlas Cloud hosted chat model. Atlas Cloud is an OpenAI-compatible provider available at atlascloud.ai
      • Gemini: gemini-3.1-pro-preview (default), gemini-2.5-pro, gemini-2.5-flash, gemini-2.5-flash-lite
      • Claude: claude-sonnet-4-6 (default), claude-opus-4-7, claude-opus-4-6, claude-sonnet-4-5, claude-opus-4-5, claude-haiku-4-5
      • OpenAI: gpt-5.4 (default), gpt-5.4-mini, gpt-5.4-nano
      • Custom OpenAI-compatible: Any custom model name (requires ai-base-url)
    • ai-api-key or set the environment variable GOSEC_AI_API_KEY: the key to access the AI API
    • ai-base-url: (optional) custom base URL for OpenAI-compatible APIs (e.g., Azure OpenAI, LocalAI, Ollama)
      • Atlas Cloud uses https://api.atlascloud.ai/v1 by default, so ai-base-url is optional for the built-in atlas provider
    • GOSEC_AI_PROVIDER: (optional) environment variable alternative to ai-api-provider
    • GOSEC_AI_BASE_URL: (optional) environment variable alternative to ai-base-url
    • ai-skip-ssl: (optional) skip SSL certificate verification for AI API (useful for self-signed certificates)

    🎁 Atlas Cloud is a full-modal AI inference platform that gives developers a single AI API to access video generation, image generation, and LLM APIs. Instead of managing multiple vendor integrations, you connect once and get unified access to 300+ curated models across all modalities.

    Check out Atlas Cloud's new coding plan promotion for more budget-friendly API access: https://www.atlascloud.ai/console/coding-plan

    Examples:

    # 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 \
      ./...
    

    Annotating code

    As with all automated detection tools, there will be cases of false positives. In cases where gosec reports a failure that has been manually verified as being safe, it is possible to annotate the code with a comment that starts with #nosec.

    The #nosec comment should have the format #nosec [RuleList] [-- Justification].

    The #nosec comment needs to be placed on the line where the warning is reported.

    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)
    	}
    }
    

    When a specific false positive has been identified and verified as safe, you may wish to suppress only that single rule (or a specific set of rules) within a section of code, while continuing to scan for other problems. To do this, you can list the rule(s) to be suppressed within the #nosec annotation, e.g: /* #nosec G401 */ or //#nosec G201 G202 G203

    You could put the description or justification text for the annotation. The justification should be after the rule(s) to suppress and start with two or more dashes, e.g: //#nosec G101 G102 -- This is a false positive

    Alternatively, gosec also supports the //gosec:disable directive, which functions similar to #nosec:

    //gosec:disable G101 -- This is a false positive
    

    In some cases you may also want to revisit places where #nosec or //gosec:disable annotations have been used. To run the scanner and ignore any #nosec annotations you can do the following:

    gosec -nosec=true ./...
    
    Requiring rule IDs and justifications

    To prevent annotations from inadvertently suppressing unrelated rules, or from being added without explanation, gosec accepts two opt-in flags. Both default to false, so existing codebases keep working unchanged.

    • -nosec-require-rules rejects naked #nosec / //gosec:disable directives that do not list any rule ID.
    • -nosec-require-justification rejects directives that do not carry a -- justification after the rule list.

    When enabled, a directive that fails the check no longer suppresses any finding and is reported as an error in the output, alongside any underlying issue on the line.

    gosec -nosec-require-rules -nosec-require-justification ./...
    

    The same options can be set via the global config block:

    {
        "global": {
            "nosec-require-rules": "enabled",
            "nosec-require-justification": "enabled"
        }
    }
    

    Tracking suppressions

    As described above, we could suppress violations externally (using -include/-exclude) or inline (using #nosec annotations). Suppression metadata can be emitted for auditing.

    Enable suppression tracking with -track-suppressions:

    gosec -track-suppressions -exclude=G101 \
      -fmt=sarif -out=results.sarif ./...
    
    • For external suppressions, gosec records suppression info where kind is external and justification is Globally suppressed..
    • For inline suppressions, gosec records suppression info where kind is inSource and justification is the text after two or more dashes in the comment.

    Note: Only SARIF and JSON formats support tracking suppressions.

    Build tags

    gosec is able to pass your Go build tags to the analyzer. They can be provided as a comma separated list as follows:

    gosec -tags debug,ignore ./...
    

    Output formats

    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:

    # Write output in json format to results.json
    $ gosec -fmt=json -out=results.json *.go
    

    Use -stdout to print results while also writing -out. Use -verbose to override stdout format while preserving the file format.

    # 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
    

    Note: gosec generates the generic issue import format for SonarQube, and a report has to be imported into SonarQube using sonar.externalIssuesReportPaths=path/to/gosec-report.json.

    Common usage patterns

    # 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

    Development documentation was moved to DEVELOPMENT.md.

    Who is using gosec?

    This is a list with some of the gosec's users.

    Sponsors

    Support this project by becoming a sponsor. Your logo will show up here with a link to your website