跳转至

API 密钥和令牌泄露 (API Key and Token Leaks)

API 密钥和令牌是管理公共和私有服务权限与访问的常用身份验证形式。泄露这些敏感数据可能导致未经授权的访问、安全受损以及潜在的数据泄露。

摘要 (Summary)

工具 (Tools)

方法论 (Methodology)

  • API 密钥 (API Keys): 用于验证与项目或应用程序相关的请求的唯一标识符。
  • 令牌 (Tokens): 授予受保护资源访问权限的安全令牌(如 OAuth 令牌)。

常见的泄露原因 (Common Causes of Leaks)

  • 在源码中硬编码 (Hardcoding in Source Code): 开发人员可能会无意中将 API 密钥或令牌直接留在源代码中。

    # 硬编码 API 密钥示例
    api_key = "1234567890abcdef"
    
  • 公共仓库 (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 镜像里。

    # 扫描 Docker 镜像以寻找验证过的机密
    docker run --rm -it -v "$PWD:/pwd" trufflesecurity/trufflehog:latest docker --image trufflesecurity/secrets
    
  • 日志和调试信息 (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

    curl https://api.telegram.org/bot<TOKEN>/getMe
    

减少攻击面 (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

参考资料 (References)