API 密钥和令牌泄露 (API Key and Token Leaks)
API 密钥和令牌是管理公共和私有服务权限与访问的常用身份验证形式。泄露这些敏感数据可能导致未经授权的访问、安全受损以及潜在的数据泄露。
摘要 (Summary)
工具 (Tools)
- aquasecurity/trivy - 通用漏洞和配置错误扫描程序,也支持搜索 API 密钥/机密 (secrets)。
- blacklanternsecurity/badsecrets - 一个用于跨多个平台检测已知或弱机密的库。
- irsdl/crapsecrets - 一个用于跨多个 Web 框架检测已知机密的库。
- d0ge/sign-saboteur - SignSaboteur 是一款 Burp Suite 扩展,用于编辑、签名、验证各种签名 Web 令牌。
- mazen160/secrets-patterns-db - Secrets Patterns DB:用于检测机密、API 密钥、密码、令牌等内容的最大开源数据库。
- momenbasel/KeyFinder - 一款让您在浏览网页时查找密钥的工具。
- streaak/keyhacks - 一个展示了如何快速验证 Bug Bounty 计划中泄露的 API 密钥是否有效的仓库。
- trufflesecurity/truffleHog - 查找各处的凭据。
-
projectdiscovery/nuclei-templates - 使用这些模板针对多个 API 服务端点测试 API 令牌。
方法论 (Methodology)
- API 密钥 (API Keys): 用于验证与项目或应用程序相关的请求的唯一标识符。
- 令牌 (Tokens): 授予受保护资源访问权限的安全令牌(如 OAuth 令牌)。
常见的泄露原因 (Common Causes of Leaks)
-
在源码中硬编码 (Hardcoding in Source Code): 开发人员可能会无意中将 API 密钥或令牌直接留在源代码中。
-
公共仓库 (Public Repositories): 意外地将敏感密钥和令牌提交到公共访问的版本控制系统(如 GitHub)。
## 扫描一个 Github 组织 docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --org=trufflesecurity ## 扫描一个 GitHub 仓库及其 Issues 和 Pull Requests docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest github --repo https://github.com/trufflesecurity/test_keys --issue-comments --pr-comments -
Docker 镜像中硬编码 (Hardcoding in Docker Images): API 密钥和凭据可能被硬编码在托管在 DockerHub 或私有注册表中的 Docker 镜像里。
-
日志和调试信息 (Logs and Debug Information): 在调试过程中,密钥和令牌可能被无意中记录或打印出来。
-
配置文件 (Configuration Files): 将密钥和令牌包含在公开访问的配置文件中(例如:.env 文件、config.json、settings.py 或 .aws/credentials)。
验证 API 密钥 (Validate The API Key)
如果需要识别生成令牌的服务,可以查阅 mazen160/secrets-patterns-db。它是最大的检测机密、API 密钥、密码、令牌等的开源数据库。该数据库包含各种机密的正则 (regex) 模式。
patterns:
- pattern:
name: AWS API Gateway
regex: '[0-9a-z]+.execute-api.[0-9a-z._-]+.amazonaws.com'
confidence: low
- pattern:
name: AWS API Key
regex: AKIA[0-9A-Z]{16}
confidence: high
使用 streaak/keyhacks 或阅读服务的文档,寻找快速验证 API 密钥有效性的方法。
-
示例 (Example): Telegram Bot API Token
减少攻击面 (Reducing The Attack Surface)
在将更改提交到 GitHub 仓库之前,检查是否存在私钥或 AWS 凭据。
将这些行添加到您的 .pre-commit-config.yaml 文件中。
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.2.0
hooks:
- id: detect-aws-credentials
- id: detect-private-key