Skip to content
KitploitKITPLOIT
工具博客
提交
工具博客
提交

黑客、渗透测试和网络安全工具,武装您的安全武器库!

Kitploit 是一个黑客、网络安全和渗透测试工具的目录。发现最新的项目更新,查找漏洞、分析系统、自动化测试并加强你的安全。

··订阅源·联系·隐私·© 2026 Kitploit

工具目录

分类

查看所有分类
Loading categories
工具/GitHubGitHub/yelp/detect-secrets
静态分析代码分析DevSecOps秘密检测
GitHubyelp/detect-secrets

detect-secrets

一种企业友好的检测和预防代码中机密信息的方式。

查看仓库
4.6k5644个月前Kitploit 审核通过

最受欢迎

查看全部 →

发现我们社区最常用的工具。

探索所有工具

浏览我们的工具集合

查看所有工具 →
分享

Build Status PyPI version Homebrew PRs Welcome AMF

detect-secrets

关于

detect-secrets 是一个恰如其名的模块,用于(惊喜,惊喜)检测代码库中的秘密。

然而,与其他仅专注于查找秘密的类似包不同,该包专为企业客户设计:提供一种向后兼容、系统化的方式:

  1. 防止新的秘密进入代码库,
  2. 检测此类预防措施是否被明确绕过,以及
  3. 提供一个需要轮换并迁移到更安全存储的秘密清单。

这样,您就创建了一个关注点分离: 承认您的庞大仓库中可能目前隐藏着秘密(我们称之为_基线_),但避免这一问题进一步扩大,而无需处理将现有秘密迁出的巨大工作量。

它通过定期对启发式构建的正则表达式语句运行差异输出来实现这一点,以识别是否有新的秘密被提交。这样,它避免了挖掘所有git历史记录的开销,也无需每次都扫描整个仓库。

有关最近更改,请参阅CHANGELOG.md。

如果您希望贡献,请参阅CONTRIBUTING.md。

有关更详细的文档,请查看我们的其他文档。

示例

快速开始:

在当前git仓库中创建潜在秘密的基线。```bash $ detect-secrets scan > .secrets.baseline

root@kitploit:~
或者,从其他目录运行:```bash
$ detect-secrets -C /path/to/directory scan > /path/to/directory/.secrets.baseline

扫描非 git 跟踪的文件:```bash $ detect-secrets scan test_data/ --all-files > .secrets.baseline

root@kitploit:~
### 将新秘密添加到基线:

这将重新扫描你的代码库,并且:

1. 更新/升级你的基线以兼容最新版本,
2. 将任何新发现的秘密添加到你的基线,
3. 移除代码库中不再存在的任何秘密

这也会保留你已有的任何标记过的秘密。```bash
$ detect-secrets scan --baseline .secrets.baseline

对于早于 0.9 版本的基线,只需重新创建它。

关闭新增秘密的警报:

仅扫描暂存文件:```bash $ git diff --staged --name-only -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline

root@kitploit:~
**扫描所有已跟踪的文件:**```bash
$ git ls-files -z | xargs -0 detect-secrets-hook --baseline .secrets.baseline

查看所有启用的插件:```bash

$ detect-secrets scan --list-all-plugins ArtifactoryDetector AWSKeyDetector AzureStorageKeyDetector BasicAuthDetector CloudantDetector DiscordBotTokenDetector GitHubTokenDetector GitLabTokenDetector Base64HighEntropyString HexHighEntropyString IbmCloudIamDetector IbmCosHmacDetector IPPublicDetector JwtTokenDetector KeywordDetector MailchimpDetector NpmDetector OpenAIDetector PrivateKeyDetector PypiTokenDetector SendGridDetector SlackDetector SoftlayerDetector SquareOAuthDetector StripeDetector TelegramBotTokenDetector TwilioKeyDetector

root@kitploit:~
### 禁用插件:```bash
$ detect-secrets scan --disable-plugin KeywordDetector --disable-plugin AWSKeyDetector

如果你只想运行特定插件,可以执行:```bash $ detect-secrets scan --list-all-plugins |
grep -v 'BasicAuthDetector' |
sed "s#^#--disable-plugin #g" |
xargs detect-secrets scan test_data

root@kitploit:~
### 审计基线:

这是一个可选步骤,用于标记基线中的结果。它可以用来缩小需要迁移的机密清单,或者更好地配置插件以提高信噪比。```bash
$ detect-secrets audit .secrets.baseline

在其他 Python 脚本中的使用

基本用法:```python from detect_secrets import SecretsCollection from detect_secrets.settings import default_settings

secrets = SecretsCollection() with default_settings(): secrets.scan_file('test_data/config.ini')

import json print(json.dumps(secrets.json(), indent=2))

root@kitploit:~
**更多高级配置:**```python
from detect_secrets import SecretsCollection
from detect_secrets.settings import transient_settings

secrets = SecretsCollection()
with transient_settings({
    # Only run scans with only these plugins.
    # This format is the same as the one that is saved in the generated baseline.
    'plugins_used': [
        # Example of configuring a built-in plugin
        {
            'name': 'Base64HighEntropyString',
            'limit': 5.0,
        },

        # Example of using a custom plugin
        {
            'name': 'HippoDetector',
            'path': 'file:///Users/aaronloo/Documents/github/detect-secrets/testing/plugins.py',
        },
    ],

    # We can also specify whichever additional filters we want.
    # This is an example of using the function `is_identified_by_ML_model` within the
    # local file `./private-filters/example.py`.
    'filters_used': [
        {
            'path': 'file://private-filters/example.py::is_identified_by_ML_model',
        },
    ]
}) as settings:
    # If we want to make any further adjustments to the created settings object (e.g.
    # disabling default filters), we can do so as such.
    settings.disable_filters(
        'detect_secrets.filters.heuristic.is_prefixed_with_dollar_sign',
        'detect_secrets.filters.heuristic.is_likely_id_string',
    )

    secrets.scan_file('test_data/config.ini')

安装```bash

$ pip install detect-secrets ✨🍰✨

root@kitploit:~
通过 [brew](https://brew.sh/) 安装:```bash
$ brew install detect-secrets

用法

detect-secrets 附带三种不同工具,常常会让人困惑该用哪一个。请使用这个便捷的清单来帮助您决定:

  1. 您想向基线添加秘密吗?如果是,请使用 detect-secrets scan。
  2. 您想对不在基线中的新秘密发出警报吗?如果是,请使用 detect-secrets-hook。
  3. 您正在分析基线本身吗?如果是,请使用 detect-secrets audit。

向基线添加秘密```

$ detect-secrets scan --help usage: detect-secrets scan [-h] [--string [STRING]] [--only-allowlisted] [--all-files] [--baseline FILENAME] [--force-use-all-plugins] [--slim] [--list-all-plugins] [-p PLUGIN] [--base64-limit [BASE64_LIMIT]] [--hex-limit [HEX_LIMIT]] [--disable-plugin DISABLE_PLUGIN] [-n | --only-verified] [--exclude-lines EXCLUDE_LINES] [--exclude-files EXCLUDE_FILES] [--exclude-secrets EXCLUDE_SECRETS] [--word-list WORD_LIST_FILE] [-f FILTER] [--disable-filter DISABLE_FILTER] [path [path ...]]

Scans a repository for secrets in code. The generated output is compatible with detect-secrets-hook --baseline.

positional arguments: path Scans the entire codebase and outputs a snapshot of currently identified secrets.

optional arguments: -h, --help show this help message and exit --string [STRING] Scans an individual string, and displays configured plugins' verdict. --only-allowlisted Only scans the lines that are flagged with allowlist secret. This helps verify that individual exceptions are indeed non-secrets.

scan options: --all-files Scan all files recursively (as compared to only scanning git tracked files). --baseline FILENAME If provided, will update existing baseline by importing settings from it. --force-use-all-plugins If a baseline is provided, detect-secrets will default to loading the plugins specified by that baseline. However, this may also mean it doesn't perform the scan with the latest plugins. If this flag is provided, it will always use the latest plugins --slim Slim baselines are created with the intention of minimizing differences between commits. However, they are not compatible with the audit functionality, and slim baselines will need to be remade to be audited.

plugin options: Configure settings for each secret scanning ruleset. By default, all plugins are enabled unless explicitly disabled.

--list-all-plugins Lists all plugins that will be used for the scan. -p PLUGIN, --plugin PLUGIN Specify path to custom secret detector plugin. --base64-limit [BASE64_LIMIT] Sets the entropy limit for high entropy strings. Value must be between 0.0 and 8.0, defaults to 4.5. --hex-limit [HEX_LIMIT] Sets the entropy limit for high entropy strings. Value must be between 0.0 and 8.0, defaults to 3.0. --disable-plugin DISABLE_PLUGIN Plugin class names to disable. e.g. Base64HighEntropyString

filter options: Configure settings for filtering out secrets after they are flagged by the engine.

-n, --no-verify Disables additional verification of secrets via network call. --only-verified Only flags secrets that can be verified. --exclude-lines EXCLUDE_LINES If lines match this regex, it will be ignored. --exclude-files EXCLUDE_FILES If filenames match this regex, it will be ignored. --exclude-secrets EXCLUDE_SECRETS If secrets match this regex, it will be ignored. --word-list WORD_LIST_FILE Text file with a list of words, if a secret contains a word in the list we ignore it. -f FILTER, --filter FILTER Specify path to custom filter. May be a python module path (e.g. detect_secrets.filters.common.is_invalid_file) or a local file path (e.g. file://path/to/file.py::function_name). --disable-filter DISABLE_FILTER Specify filter to disable. e.g. detect_secrets.filters.common.is_invalid_file

root@kitploit:~
### 阻止不在基线中的秘密```
$ detect-secrets-hook --help
usage: detect-secrets-hook [-h] [-v] [--version] [--baseline FILENAME]
                           [--list-all-plugins] [-p PLUGIN]
                           [--base64-limit [BASE64_LIMIT]]
                           [--hex-limit [HEX_LIMIT]]
                           [--disable-plugin DISABLE_PLUGIN]
                           [-n | --only-verified]
                           [--exclude-lines EXCLUDE_LINES]
                           [--exclude-files EXCLUDE_FILES]
                           [--exclude-secrets EXCLUDE_SECRETS]
                           [--word-list WORD_LIST_FILE] [-f FILTER]
                           [--disable-filter DISABLE_FILTER]
                           [filenames [filenames ...]]

positional arguments:
  filenames             Filenames to check.

optional arguments:
  -h, --help            show this help message and exit
  -v, --verbose         Verbose mode.
  --version             Display version information.
  --json                Print detect-secrets-hook output as JSON
  --baseline FILENAME   Explicitly ignore secrets through a baseline generated
                        by `detect-secrets scan`

plugin options:
  Configure settings for each secret scanning ruleset. By default, all
  plugins are enabled unless explicitly disabled.

  --list-all-plugins    Lists all plugins that will be used for the scan.
  -p PLUGIN, --plugin PLUGIN
                        Specify path to custom secret detector plugin.
  --base64-limit [BASE64_LIMIT]
                        Sets the entropy limit for high entropy strings. Value
                        must be between 0.0 and 8.0, defaults to 4.5.
  --hex-limit [HEX_LIMIT]
                        Sets the entropy limit for high entropy strings. Value
                        must be between 0.0 and 8.0, defaults to 3.0.
  --disable-plugin DISABLE_PLUGIN
                        Plugin class names to disable. e.g.
                        Base64HighEntropyString

filter options:
  Configure settings for filtering out secrets after they are flagged by the
  engine.

  -n, --no-verify       Disables additional verification of secrets via
                        network call.
  --only-verified       Only flags secrets that can be verified.
  --exclude-lines EXCLUDE_LINES
                        If lines match this regex, it will be ignored.
  --exclude-files EXCLUDE_FILES
                        If filenames match this regex, it will be ignored.
  --exclude-secrets EXCLUDE_SECRETS
                        If secrets match this regex, it will be ignored.
  -f FILTER, --filter FILTER
                        Specify path to custom filter. May be a python module
                        path (e.g.
                        detect_secrets.filters.common.is_invalid_file) or a
                        local file path (e.g.
                        file://path/to/file.py::function_name).
  --disable-filter DISABLE_FILTER
                        Specify filter to disable. e.g.
                        detect_secrets.filters.common.is_invalid_file

我们建议将其设置为 pre-commit 钩子。实现这一点的一种方法是使用 pre-commit 框架:```yaml

.pre-commit-config.yaml

repos:

  • repo: https://github.com/Yelp/detect-secrets rev: v1.5.0 hooks:
    • id: detect-secrets args: ['--baseline', '.secrets.baseline'] exclude: package.lock.json
root@kitploit:~
#### 内联允许列表

有时我们希望排除一个误报,不让其阻止提交,但又不想为此创建基线。你可以通过添加如下注释来实现:

```bash
# pragma: allowlist secret
``````python
secret = "hunter2"      # pragma: allowlist secret

或```javascript // pragma: allowlist nextline secret const secret = "hunter2";

root@kitploit:~
### 基线中的秘密审计```bash
$ detect-secrets audit --help
usage: detect-secrets audit [-h] [--diff] [--stats]
                      [--report] [--only-real | --only-false]
                      [--json]
                      filename [filename ...]

Auditing a baseline allows analysts to label results, and optimize plugins for
the highest signal-to-noise ratio for their environment.

positional arguments:
  filename      Audit a given baseline file to distinguish the difference
                between false and true positives.

optional arguments:
  -h, --help    show this help message and exit
  --diff        Allows the comparison of two baseline files, in order to
                effectively distinguish the difference between various plugin
                configurations.
  --stats       Displays the results of an interactive auditing session which
                have been saved to a baseline file.
  --report      Displays a report with the secrets detected

reporting:
  Display a summary with all the findings and the made decisions. To be used with the report mode (--report).

  --only-real   Only includes real secrets in the report
  --only-false  Only includes false positives in the report

analytics:
  Quantify the success of your plugins based on the labelled results in your
  baseline. To be used with the statistics mode (--stats).

  --json        Outputs results in a machine-readable format.

配置

该工具通过插件和过滤器系统运行。

  • 插件在代码中查找秘密
  • 过滤器忽略误报以提高扫描精度

您可以调整两者以满足您的精确度/召回率需求。

插件

我们采用三种不同的策略来尝试在代码中查找秘密:

  1. 基于正则表达式的规则

    这是最常见的插件类型,适用于结构良好的秘密。 这些秘密可以选择验证,这会提高扫描精度。 但是,仅依赖这些可能会对扫描的召回率产生负面影响。

  2. 熵检测器

    它通过各种启发式方法搜索看起来像秘密的字符串。这对于非结构化的秘密非常有用,但可能需要调整以调整扫描精度。

  3. 关键词检测器

    它忽略秘密值,搜索与硬编码赋值秘密相关的变量名。这对于看起来不像秘密的字符串(例如 le3tc0de 密码)非常有用,但可能需要调整过滤器以调整扫描精度。

想要找到我们当前未捕获的秘密?您也可以(轻松地)开发自己的插件,并将其与引擎一起使用!有关更多信息,请查看插件文档。

过滤器

detect-secrets 提供了几种不同的内置过滤器,可能适合您的需求。

--exclude-lines

有时,您希望能够全局允许扫描中的某些行,如果它们匹配特定模式。您可以指定一个正则表达式规则,如下所示:```bash $ detect-secrets scan --exclude-lines 'password = (blah|fake)'

root@kitploit:~
或者,你可以像这样指定多个正则规则:```bash
$ detect-secrets scan --exclude-lines 'password = blah' --exclude-lines 'password = fake'

--exclude-files

有时,您希望在扫描时忽略某些文件。您可以指定一个正则表达式模式来实现,如果文件名匹配该正则表达式模式,则不会对其进行扫描:```bash $ detect-secrets scan --exclude-files '.*.signature$'

root@kitploit:~
或者你可以像这样指定多个正则表达式模式:```bash
$ detect-secrets scan --exclude-files '.*\.signature$' --exclude-files '.*/i18n/.*'

--exclude-secrets

有时,您可能希望忽略扫描中的某些秘密值。您可以指定一个正则表达式规则,如下所示:```bash $ detect-secrets scan --exclude-secrets '(fakesecret|${.*})'

root@kitploit:~
或者你可以像这样指定多个正则表达式规则:```bash
$ detect-secrets scan --exclude-secrets 'fakesecret' --exclude-secrets '\${.*})'

内联白名单

有时,您希望对特定行应用排除,而不是全局排除。 您可以通过内联白名单实现这一点,如下所示:```python API_KEY = 'this-will-ordinarily-be-detected-by-a-plugin' # pragma: allowlist secret

root@kitploit:~
这些注释支持多种语言。例如:```java
const GoogleCredentialPassword = "something-secret-here";     //  pragma: allowlist secret

您还可以使用:```python

pragma: allowlist nextline secret

API_KEY = 'WillAlsoBeIgnored'

root@kitploit:~
这可能是你忽略秘密的一种便捷方式,无需重新生成整个基线。如果你需要显式搜索这些已列入白名单的秘密,你也可以这样做:```bash
$ detect-secrets scan --only-allowlisted

想要编写更多自定义逻辑来过滤误报?请查看我们的过滤器文档了解如何操作。

扩展

wordlist

--exclude-secrets 标志允许你指定正则规则来排除机密值。不过,如果你想指定一个大的词列表,可以使用 --word-list 标志。

要使用此功能,请确保安装 pyahocorasick 包,或者直接使用:```bash $ pip install detect-secrets[word_list]

root@kitploit:~
然后,你可以这样使用它:```bash
$ cat wordlist.txt
not-a-real-secret
$ cat sample.ini
password = not-a-real-secret

# Will show results
$ detect-secrets scan sample.ini

# No results found
$ detect-secrets scan --word-list wordlist.txt

Gibberish Detector

Gibberish Detector 是一个简单的机器学习模型,它尝试判断一个秘密值是否真的是乱码,其假设是真实的秘密值不应该像单词。

要使用此功能,请确保安装 gibberish-detector 包,或者使用:```bash $ pip install detect-secrets[gibberish]

root@kitploit:~
查看 [gibberish-detector](https://github.com/domanchi/gibberish-detector) 包以获取
关于如何训练模型的更多信息。一个预训练的模型(通过处理RFC文档初始化)将
包含在内,方便使用。

您还可以指定自己的模型,如下所示:```bash
$ detect-secrets scan --gibberish-model custom.model

这不是一个默认插件,因为它会忽略像 password 这样的密钥。

注意事项

这并非旨在成为防止机密进入代码库的万无一失的解决方案。只有适当的教育开发者才能真正做到这一点。这个 pre-commit 钩子只是实现了多种试探法,试图防止明显的情况提交机密。

以下情况不会被阻止:

  • 多行密钥
  • 不会触发 KeywordDetector 的默认密码(例如 login = "hunter2")

常见问题

通用

  • 即使我位于 Git 仓库中,也遇到 'Did not detect git repository.' 警告。

    检查你的 git 版本是否 >= 1.8.5。如果不是,请升级后再试。 更多详情请点击此处。

Windows

  • detect-secrets audit 在创建基线后显示 'Not a valid baseline file!'。

    确保基线文件的编码为 UTF-8。 更多详情请点击此处。

下载工具