git-security-2025

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

🚨 CRITICAL GUIDELINES

🚨 关键指南

Windows File Path Requirements

Windows文件路径要求

MANDATORY: Always Use Backslashes on Windows for File Paths
When using Edit or Write tools on Windows, you MUST use backslashes (
\
) in file paths, NOT forward slashes (
/
).
Examples:
  • ❌ WRONG:
    D:/repos/project/file.tsx
  • ✅ CORRECT:
    D:\repos\project\file.tsx
This applies to:
  • Edit tool file_path parameter
  • Write tool file_path parameter
  • All file operations on Windows systems
强制要求:在Windows系统中始终使用反斜杠作为文件路径分隔符
在Windows系统上使用编辑或写入工具时,文件路径必须使用反斜杠(
\
),而不能使用正斜杠(
/
)。
示例:
  • ❌ 错误:
    D:/repos/project/file.tsx
  • ✅ 正确:
    D:\repos\project\file.tsx
此要求适用于:
  • 编辑工具的file_path参数
  • 写入工具的file_path参数
  • Windows系统上的所有文件操作

Documentation Guidelines

文档指南

NEVER create new documentation files unless explicitly requested by the user.
  • Priority: Update existing README.md files rather than creating new documentation
  • Repository cleanliness: Keep repository root clean - only README.md unless user requests otherwise
  • Style: Documentation should be concise, direct, and professional - avoid AI-generated tone
  • User preference: Only create additional .md files when user specifically asks for documentation

除非用户明确要求,否则绝不要创建新的文档文件。
  • 优先级:优先更新现有的README.md文件,而非创建新文档
  • 仓库整洁性:保持仓库根目录整洁——除非用户要求,否则仅保留README.md
  • 风格:文档应简洁、直接且专业——避免AI生成的语气
  • 用户偏好:仅在用户明确要求文档时,才创建额外的.md文件

Git Security Best Practices 2025

2025年Git安全最佳实践

Zero-Trust Security Model (2025 Standard)

零信任安全模型(2025标准)

What: Every developer identity must be authenticated and authorized explicitly. All Git operations are logged, signed, and continuously monitored.
Core Principles:
  1. Never trust, always verify - Every commit verified
  2. Least privilege access - Minimal permissions required
  3. Continuous monitoring - All operations logged and audited
  4. Assume breach - Defense in depth strategies
定义: 每个开发者身份都必须经过明确的认证和授权。所有Git操作都需记录、签名并持续监控。
核心原则:
  1. 永不信任,始终验证——每个提交都需验证
  2. 最小权限访问——仅授予所需的最低权限
  3. 持续监控——所有操作都需记录并审计
  4. 假设已泄露——采用纵深防御策略

Implementing Zero-Trust for Git

为Git实现零信任

1. Mandatory Signed Commits:
bash
undefined
1. 强制签名提交:
bash
undefined

Global requirement

全局配置要求

git config --global commit.gpgsign true git config --global tag.gpgsign true
git config --global commit.gpgsign true git config --global tag.gpgsign true

Enforce via branch protection (GitHub/GitLab/Azure DevOps)

通过分支保护强制执行(GitHub/GitLab/Azure DevOps)

Repository Settings → Branches → Require signed commits

仓库设置 → 分支 → 要求签名提交


**2. Identity Verification:**
```bash

**2. 身份验证:**
```bash

Every commit must verify identity

每个提交都必须验证身份

git log --show-signature -10
git log --show-signature -10

Reject unsigned commits in CI/CD

在CI/CD中拒绝未签名的提交

.github/workflows/verify.yml

.github/workflows/verify.yml

  • name: Verify all commits are signed run: | git log --pretty="%H" origin/main..HEAD | while read commit; do if ! git verify-commit "$commit" 2>/dev/null; then echo "ERROR: Unsigned commit $commit" exit 1 fi done

**3. Continuous Audit Logging:**
```bash
  • name: Verify all commits are signed run: | git log --pretty="%H" origin/main..HEAD | while read commit; do if ! git verify-commit "$commit" 2>/dev/null; then echo "ERROR: Unsigned commit $commit" exit 1 fi done

**3. 持续审计日志:**
```bash

Enable Git audit trail

启用Git审计追踪

git config --global alias.audit 'log --all --pretty="%H|%an|%ae|%ad|%s|%GK" --date=iso'
git config --global alias.audit 'log --all --pretty="%H|%an|%ae|%ad|%s|%GK" --date=iso'

Export audit log

导出审计日志

git audit > git-audit.log
git audit > git-audit.log

Monitor for suspicious activity

监控可疑活动

git log --author="*" --since="24 hours ago" --pretty=format:"%an %ae %s"

**4. Least Privilege Access:**
```yaml
git log --author="*" --since="24 hours ago" --pretty=format:"%an %ae %s"

**4. 最小权限访问:**
```yaml

GitHub branch protection (zero-trust model)

GitHub分支保护(零信任模型)

branches: main: protection_rules: required_pull_request_reviews: true dismiss_stale_reviews: true require_code_owner_reviews: true required_approving_review_count: 2 require_signed_commits: true enforce_admins: true restrictions: users: [] # No direct push teams: ["security-team"]

**5. Continuous Monitoring:**
```bash
branches: main: protection_rules: required_pull_request_reviews: true dismiss_stale_reviews: true require_code_owner_reviews: true required_approving_review_count: 2 require_signed_commits: true enforce_admins: true restrictions: users: [] # 禁止直接推送 teams: ["security-team"]

**5. 持续监控:**
```bash

Monitor all repository changes

监控所有仓库变更

.github/workflows/security-monitor.yml

.github/workflows/security-monitor.yml

name: Security Monitoring on: [push, pull_request] jobs: monitor: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0
  - name: Check for unsigned commits
    run: git verify-commit HEAD || echo "::warning::Unsigned commit detected"

  - name: Scan for secrets
    run: gitleaks detect --exit-code 1

  - name: Check commit author
    run: |
      AUTHOR=$(git log -1 --format='%an <%ae>')
      echo "Commit by: $AUTHOR"
      # Log to SIEM/security monitoring
undefined
name: Security Monitoring on: [push, pull_request] jobs: monitor: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 with: fetch-depth: 0
  - name: Check for unsigned commits
    run: git verify-commit HEAD || echo "::warning::Unsigned commit detected"

  - name: Scan for secrets
    run: gitleaks detect --exit-code 1

  - name: Check commit author
    run: |
      AUTHOR=$(git log -1 --format='%an <%ae>')
      echo "Commit by: $AUTHOR"
      # 记录到SIEM/安全监控系统
undefined

Signed Commits (Mandatory in 2025)

签名提交(2025年强制要求)

Why: Cryptographically verify commit authorship, prevent impersonation, ensure audit trail.
Industry Trend: Signed commits increasingly required in 2025 workflows.
原因: 通过加密方式验证提交者身份,防止冒充,确保审计追踪的有效性。
行业趋势: 2025年的工作流中,签名提交的要求日益普遍。

GPG Signing (Traditional)

GPG签名(传统方式)

Setup:
bash
undefined
配置步骤:
bash
undefined

Generate GPG key

生成GPG密钥

gpg --full-generate-key
gpg --full-generate-key

Choose: RSA and RSA, 4096 bits, expires in 2y

选择:RSA和RSA,4096位,2年后过期

List keys

列出密钥

gpg --list-secret-keys --keyid-format=long
gpg --list-secret-keys --keyid-format=long

Example output:

示例输出:

sec rsa4096/ABC123DEF456 2025-01-15 [SC] [expires: 2027-01-15]

sec rsa4096/ABC123DEF456 2025-01-15 [SC] [expires: 2027-01-15]

uid [ultimate] Your Name your.email@example.com

uid [ultimate] Your Name your.email@example.com

ssb rsa4096/GHI789JKL012 2025-01-15 [E] [expires: 2027-01-15]

ssb rsa4096/GHI789JKL012 2025-01-15 [E] [expires: 2027-01-15]

Configure Git

配置Git

git config --global user.signingkey ABC123DEF456 git config --global commit.gpgsign true git config --global tag.gpgsign true
git config --global user.signingkey ABC123DEF456 git config --global commit.gpgsign true git config --global tag.gpgsign true

Export public key for GitHub/GitLab

导出公钥用于GitHub/GitLab

gpg --armor --export ABC123DEF456
gpg --armor --export ABC123DEF456

Copy output and add to GitHub/GitLab/Bitbucket

复制输出并添加到GitHub/GitLab/Bitbucket

Sign commits

签名提交

git commit -S -m "feat: add authentication"
git commit -S -m "feat: add authentication"

Verify signatures

验证签名

git log --show-signature git verify-commit HEAD git verify-tag v1.0.0

**Troubleshooting:**

```bash
git log --show-signature git verify-commit HEAD git verify-tag v1.0.0

**故障排除:**

```bash

GPG agent not running

GPG代理未运行

export GPG_TTY=$(tty) echo 'export GPG_TTY=$(tty)' >> ~/.bashrc
export GPG_TTY=$(tty) echo 'export GPG_TTY=$(tty)' >> ~/.bashrc

Cache passphrase longer

延长密码短语缓存时间

echo 'default-cache-ttl 34560000' >> ~/.gnupg/gpg-agent.conf echo 'max-cache-ttl 34560000' >> ~/.gnupg/gpg-agent.conf gpg-connect-agent reloadagent /bye
echo 'default-cache-ttl 34560000' >> ~/.gnupg/gpg-agent.conf echo 'max-cache-ttl 34560000' >> ~/.gnupg/gpg-agent.conf gpg-connect-agent reloadagent /bye

Test signing

测试签名

echo "test" | gpg --clearsign
undefined
echo "test" | gpg --clearsign
undefined

SSH Signing (Modern Alternative - 2023+)

SSH签名(现代替代方案——2023年后)

Why SSH: Simpler, reuse existing SSH keys, no GPG required.
Setup:
bash
undefined
选择SSH的原因: 更简单,可复用现有SSH密钥,无需GPG。
配置步骤:
bash
undefined

Check if SSH key exists

检查SSH密钥是否存在

ls -la ~/.ssh/id_ed25519.pub
ls -la ~/.ssh/id_ed25519.pub

Generate if needed

若不存在则生成

ssh-keygen -t ed25519 -C "your.email@example.com"
ssh-keygen -t ed25519 -C "your.email@example.com"

Configure Git to use SSH signing

配置Git使用SSH签名

git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519.pub git config --global commit.gpgsign true
git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519.pub git config --global commit.gpgsign true

Add public key to GitHub

将公钥添加到GitHub

cat ~/.ssh/id_ed25519.pub
cat ~/.ssh/id_ed25519.pub

GitHub Settings → SSH and GPG keys → New SSH key → Key type: Signing Key

GitHub设置 → SSH和GPG密钥 → 新建SSH密钥 → 密钥类型:签名密钥

Sign commits (automatic with commit.gpgsign=true)

签名提交(开启commit.gpgsign=true后自动完成)

git commit -m "feat: add feature"
git commit -m "feat: add feature"

Verify

验证

git log --show-signature

**Configure allowed signers file (for verification):**

```bash
git log --show-signature

**配置允许签名者文件(用于验证):**

```bash

Create allowed signers file

创建允许签名者文件

echo "your.email@example.com $(cat ~/.ssh/id_ed25519.pub)" > ~/.ssh/allowed_signers
echo "your.email@example.com $(cat ~/.ssh/id_ed25519.pub)" > ~/.ssh/allowed_signers

Configure Git

配置Git

git config --global gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers
git config --global gpg.ssh.allowedSignersFile ~/.ssh/allowed_signers

Verify commits

验证提交

git verify-commit HEAD
undefined
git verify-commit HEAD
undefined

Secret Scanning & Prevention

密钥扫描与防护

GitHub Secret Scanning (Push Protection)

GitHub密钥扫描(推送保护)

Enable in repository:
  • Settings → Code security → Secret scanning → Enable
  • Enable push protection (blocks secrets at push time)
AI-powered detection (2025):
  • AWS credentials
  • Azure service principals
  • Google Cloud keys
  • GitHub tokens
  • Database connection strings
  • API keys (OpenAI, Stripe, Anthropic, etc.)
  • Private keys
  • OAuth tokens
  • Custom patterns
Example blocked push:
bash
$ git push
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote:
remote: - Push cannot contain secrets
remote:
remote:   Resolve the following violations before pushing again
remote:
remote:   — AWS Access Key
remote:     locations:
remote:       - config.py:12
remote:
remote:   (Disable push protection: https://github.com/settings/security_analysis)
remote:
To github.com:user/repo.git
 ! [remote rejected] main -> main (push declined due to repository rule violations)
Fix:
bash
undefined
在仓库中启用:
  • 设置 → 代码安全 → 密钥扫描 → 启用
  • 启用推送保护(在推送时阻止密钥泄露)
2025年AI驱动的检测范围:
  • AWS凭证
  • Azure服务主体
  • Google Cloud密钥
  • GitHub令牌
  • 数据库连接字符串
  • API密钥(OpenAI、Stripe、Anthropic等)
  • 私钥
  • OAuth令牌
  • 自定义规则
推送被阻止的示例:
bash
$ git push
remote: error: GH013: Repository rule violations found for refs/heads/main.
remote:
remote: - Push cannot contain secrets
remote:
remote:   Resolve the following violations before pushing again
remote:
remote:   — AWS Access Key
remote:     locations:
remote:       - config.py:12
remote:
remote:   (Disable push protection: https://github.com/settings/security_analysis)
remote:
To github.com:user/repo.git
 ! [remote rejected] main -> main (push declined due to repository rule violations)
修复方法:
bash
undefined

Remove secret from file

从文件中移除密钥

Use environment variable instead

改用环境变量

echo "AWS_ACCESS_KEY=your_key" >> .env echo ".env" >> .gitignore
echo "AWS_ACCESS_KEY=your_key" >> .env echo ".env" >> .gitignore

Remove from history if already committed

若已提交则从暂存区移除

git rm --cached config.py git commit -m "Remove secrets"
git rm --cached config.py git commit -m "Remove secrets"

If in history, use filter-repo

若已进入提交历史,使用filter-repo

git filter-repo --path config.py --invert-paths git push --force
undefined
git filter-repo --path config.py --invert-paths git push --force
undefined

Gitleaks (Local Scanning)

Gitleaks(本地扫描工具)

Install:
bash
undefined
安装:
bash
undefined

macOS

macOS

brew install gitleaks
brew install gitleaks

Linux

Linux

wget https://github.com/gitleaks/gitleaks/releases/download/v8.18.0/gitleaks_8.18.0_linux_x64.tar.gz tar -xzf gitleaks_8.18.0_linux_x64.tar.gz sudo mv gitleaks /usr/local/bin/
wget https://github.com/gitleaks/gitleaks/releases/download/v8.18.0/gitleaks_8.18.0_linux_x64.tar.gz tar -xzf gitleaks_8.18.0_linux_x64.tar.gz sudo mv gitleaks /usr/local/bin/

Windows

Windows

choco install gitleaks

**Usage:**

```bash
choco install gitleaks

**使用方法:**

```bash

Scan entire repository

扫描整个仓库

gitleaks detect
gitleaks detect

Scan uncommitted changes

扫描未提交的变更

gitleaks protect
gitleaks protect

Scan specific directory

扫描指定目录

gitleaks detect --source ./src
gitleaks detect --source ./src

Generate report

生成报告

gitleaks detect --report-format json --report-path gitleaks-report.json
gitleaks detect --report-format json --report-path gitleaks-report.json

Use in CI/CD

在CI/CD中使用

gitleaks detect --exit-code 1

**Pre-commit hook:**

```bash
gitleaks detect --exit-code 1

**提交前钩子:**

```bash

.git/hooks/pre-commit

.git/hooks/pre-commit

#!/bin/bash gitleaks protect --staged --verbose if [ $? -ne 0 ]; then echo "⚠️ Gitleaks detected secrets. Commit blocked." exit 1 fi
undefined
#!/bin/bash gitleaks protect --staged --verbose if [ $? -ne 0 ]; then echo "⚠️ Gitleaks检测到密钥,提交被阻止。" exit 1 fi
undefined

Git-secrets (AWS-focused)

Git-secrets(AWS专用工具)

bash
undefined
bash
undefined

Install

安装

brew install git-secrets # macOS
brew install git-secrets # macOS

or

git clone https://github.com/awslabs/git-secrets.git cd git-secrets sudo make install
git clone https://github.com/awslabs/git-secrets.git cd git-secrets sudo make install

Initialize in repository

在仓库中初始化

git secrets --install git secrets --register-aws
git secrets --install git secrets --register-aws

Add custom patterns

添加自定义规则

git secrets --add 'password\s*=\s*[^\s]+' git secrets --add 'api[_-]?key\s*=\s*[^\s]+'
git secrets --add 'password\s*=\s*[^\s]+' git secrets --add 'api[_-]?key\s*=\s*[^\s]+'

Scan

扫描

git secrets --scan git secrets --scan-history
undefined
git secrets --scan git secrets --scan-history
undefined

Enforce Signed Commits

强制执行签名提交

Branch Protection Rules

分支保护规则

GitHub:
Repository → Settings → Branches → Branch protection rules
☑ Require signed commits
☑ Require linear history
☑ Require status checks to pass
GitLab:
Repository → Settings → Repository → Protected branches
☑ Allowed to push: No one
☑ Allowed to merge: Maintainers
☑ Require all commits be signed
Azure DevOps:
Branch Policies → Add policy → Require signed commits
GitHub:
仓库 → 设置 → 分支 → 分支保护规则
☑ 要求签名提交
☑ 要求线性提交历史
☑ 要求状态检查通过
GitLab:
仓库 → 设置 → 仓库 → 受保护分支
☑ 允许推送:无
☑ 允许合并:维护者
☑ 要求所有提交都已签名
Azure DevOps:
分支策略 → 添加策略 → 要求签名提交

Pre-receive Hook (Server-side enforcement)

预接收钩子(服务器端强制执行)

bash
#!/bin/bash
bash
#!/bin/bash

.git/hooks/pre-receive (on server)

.git/hooks/pre-receive(服务器端)

zero_commit="0000000000000000000000000000000000000000"
while read oldrev newrev refname; do

Skip branch deletion

if [ "$newrev" = "$zero_commit" ]; then continue fi

Check all commits in push

for commit in $(git rev-list "$oldrev".."$newrev"); do # Verify commit signature if ! git verify-commit "$commit" 2>/dev/null; then echo "Error: Commit $commit is not signed" echo "All commits must be signed. Configure with:" echo " git config commit.gpgsign true" exit 1 fi done done
exit 0
undefined
zero_commit="0000000000000000000000000000000000000000"
while read oldrev newrev refname; do

跳过分支删除操作

if [ "$newrev" = "$zero_commit" ]; then continue fi

检查推送中的所有提交

for commit in $(git rev-list "$oldrev".."$newrev"); do # 验证提交签名 if ! git verify-commit "$commit" 2>/dev/null; then echo "Error: Commit $commit is not signed" echo "所有提交都必须签名。配置方法:" echo " git config commit.gpgsign true" exit 1 fi done done
exit 0
undefined

Security Configuration

安全配置

Recommended Git Config

推荐的Git配置

bash
undefined
bash
undefined

Enforce signed commits

强制执行签名提交

git config --global commit.gpgsign true git config --global tag.gpgsign true
git config --global commit.gpgsign true git config --global tag.gpgsign true

Use SSH signing (modern)

使用SSH签名(现代方式)

git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global gpg.format ssh git config --global user.signingkey ~/.ssh/id_ed25519.pub

Security settings

安全设置

git config --global protocol.version 2 git config --global transfer.fsckobjects true git config --global fetch.fsckobjects true git config --global receive.fsckobjects true
git config --global protocol.version 2 git config --global transfer.fsckobjects true git config --global fetch.fsckobjects true git config --global receive.fsckobjects true

Prevent credential leaks

防止凭证泄露

git config --global credential.helper cache --timeout=3600
git config --global credential.helper cache --timeout=3600

Or use system credential manager

或使用系统凭证管理器

git config --global credential.helper wincred # Windows git config --global credential.helper osxkeychain # macOS
git config --global credential.helper wincred # Windows git config --global credential.helper osxkeychain # macOS

Line ending safety

行尾安全设置

git config --global core.autocrlf true # Windows git config --global core.autocrlf input # macOS/Linux
git config --global core.autocrlf true # Windows git config --global core.autocrlf input # macOS/Linux

Editor safety (avoid nano/vim leaks)

编辑器安全设置(避免nano/vim泄露)

git config --global core.editor "code --wait"
undefined
git config --global core.editor "code --wait"
undefined

.gitignore Security

.gitignore安全配置

gitignore
undefined
gitignore
undefined

Secrets

密钥文件

.env .env.* *.pem *.key *.p12 *.pfx *_rsa *_dsa *_ecdsa *_ed25519 credentials.json secrets.yaml config/secrets.yml
.env .env.* *.pem *.key *.p12 *.pfx *_rsa *_dsa *_ecdsa *_ed25519 credentials.json secrets.yaml config/secrets.yml

Cloud provider

云提供商配置

.aws/ .azure/ .gcloud/ gcloud-service-key.json
.aws/ .azure/ .gcloud/ gcloud-service-key.json

Databases

数据库文件

*.sqlite *.db
*.sqlite *.db

Logs (may contain sensitive data)

日志文件(可能包含敏感数据)

*.log logs/
*.log logs/

IDE secrets

IDE配置文件(可能包含敏感信息)

.vscode/settings.json .idea/workspace.xml
.vscode/settings.json .idea/workspace.xml

Build artifacts (may contain embedded secrets)

构建产物(可能嵌入密钥)

dist/ build/ node_modules/ vendor/
undefined
dist/ build/ node_modules/ vendor/
undefined

Credential Management

凭证管理

SSH Keys

SSH密钥

bash
undefined
bash
undefined

Generate secure SSH key

生成安全的SSH密钥

ssh-keygen -t ed25519 -C "your.email@example.com" -f ~/.ssh/id_ed25519_work
ssh-keygen -t ed25519 -C "your.email@example.com" -f ~/.ssh/id_ed25519_work

Use ed25519 (modern, secure, fast)

使用ed25519(现代、安全、快速)

Avoid RSA < 4096 bits

避免使用小于4096位的RSA密钥

Avoid DSA (deprecated)

避免使用DSA(已废弃)

Configure SSH agent

配置SSH代理

eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519_work
eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519_work

Test connection

测试连接

ssh -T git@github.com
ssh -T git@github.com

Use different keys for different services

为不同服务使用不同密钥

~/.ssh/config

~/.ssh/config

Host github.com IdentityFile ~/.ssh/id_ed25519_github
Host gitlab.com IdentityFile ~/.ssh/id_ed25519_gitlab
undefined
Host github.com IdentityFile ~/.ssh/id_ed25519_github
Host gitlab.com IdentityFile ~/.ssh/id_ed25519_gitlab
undefined

HTTPS Credentials

HTTPS凭证

bash
undefined
bash
undefined

Use credential manager (not plaintext!)

使用凭证管理器(绝不要使用明文!)

Windows

Windows

git config --global credential.helper wincred
git config --global credential.helper wincred

macOS

macOS

git config --global credential.helper osxkeychain
git config --global credential.helper osxkeychain

Linux (libsecret)

Linux(libsecret)

git config --global credential.helper /usr/share/git/credential/libsecret/git-credential-libsecret
git config --global credential.helper /usr/share/git/credential/libsecret/git-credential-libsecret

Cache for limited time (temporary projects)

临时缓存(适用于临时项目)

git config --global credential.helper 'cache --timeout=3600'
undefined
git config --global credential.helper 'cache --timeout=3600'
undefined

Personal Access Tokens (PAT)

个人访问令牌(PAT)

GitHub:
  • Settings → Developer settings → Personal access tokens → Fine-grained tokens
  • Set expiration (max 1 year)
  • Minimum scopes needed
  • Use for HTTPS authentication
Never commit tokens:
bash
undefined
GitHub:
  • 设置 → 开发者设置 → 个人访问令牌 → 细粒度令牌
  • 设置过期时间(最长1年)
  • 仅授予所需的最小权限
  • 用于HTTPS认证
绝不要提交令牌:
bash
undefined

Use environment variable

使用环境变量

export GITHUB_TOKEN="ghp_xxxxxxxxxxxx" git clone https://$GITHUB_TOKEN@github.com/user/repo.git
export GITHUB_TOKEN="ghp_xxxxxxxxxxxx" git clone https://$GITHUB_TOKEN@github.com/user/repo.git

Or use Git credential helper

或使用GitHub CLI方法

gh auth login # GitHub CLI method
undefined
gh auth login # GitHub CLI method
undefined

CodeQL & Security Scanning

CodeQL与安全扫描

GitHub CodeQL

GitHub CodeQL

.github/workflows/codeql.yml:
yaml
name: "CodeQL Security Scan"

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
  schedule:
    - cron: '0 0 * * 1'  # Weekly scan

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      contents: read

    strategy:
      fail-fast: false
      matrix:
        language: [ 'javascript', 'python', 'java' ]

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Initialize CodeQL
      uses: github/codeql-action/init@v3
      with:
        languages: ${{ matrix.language }}
        queries: security-and-quality

    - name: Autobuild
      uses: github/codeql-action/autobuild@v3

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v3
      with:
        category: "/language:${{ matrix.language }}"
Detects:
  • SQL injection
  • XSS vulnerabilities
  • Path traversal
  • Command injection
  • Insecure deserialization
  • Authentication bypass
  • Hardcoded secrets
.github/workflows/codeql.yml:
yaml
name: "CodeQL Security Scan"

on:
  push:
    branches: [ main, develop ]
  pull_request:
    branches: [ main ]
  schedule:
    - cron: '0 0 * * 1'  # 每周扫描一次

jobs:
  analyze:
    name: Analyze
    runs-on: ubuntu-latest
    permissions:
      security-events: write
      contents: read

    strategy:
      fail-fast: false
      matrix:
        language: [ 'javascript', 'python', 'java' ]

    steps:
    - name: Checkout repository
      uses: actions/checkout@v4

    - name: Initialize CodeQL
      uses: github/codeql-action/init@v3
      with:
        languages: ${{ matrix.language }}
        queries: security-and-quality

    - name: Autobuild
      uses: github/codeql-action/autobuild@v3

    - name: Perform CodeQL Analysis
      uses: github/codeql-action/analyze@v3
      with:
        category: "/language:${{ matrix.language }}"
检测范围:
  • SQL注入
  • XSS漏洞
  • 路径遍历
  • 命令注入
  • 不安全的反序列化
  • 身份验证绕过
  • 硬编码密钥

Audit Trail

审计追踪

Enable detailed logging

启用详细日志

bash
undefined
bash
undefined

Log all Git operations

记录所有Git操作

git config --global alias.ll 'log --all --graph --decorate --oneline --show-signature'
git config --global alias.ll 'log --all --graph --decorate --oneline --show-signature'

Check commit verification

检查提交验证情况

git log --show-signature -10
git log --show-signature -10

Export audit log

导出审计日志

git log --pretty=format:"%H,%an,%ae,%ad,%s" --date=iso > git-audit.csv
git log --pretty=format:"%H,%an,%ae,%ad,%s" --date=iso > git-audit.csv

Verify all commits in branch

验证分支中的所有提交

git log --show-signature main..HEAD
undefined
git log --show-signature main..HEAD
undefined

Security Checklist

安全检查清单

Repository Setup:
  • ☑ Enable branch protection
  • ☑ Require signed commits
  • ☑ Enable secret scanning with push protection
  • ☑ Enable CodeQL or similar scanning
  • ☑ Configure Dependabot/Renovate
  • ☑ Require 2FA for all contributors
Developer Workstation:
  • ☑ Use GPG or SSH commit signing
  • ☑ Configure credential manager (never plaintext)
  • ☑ Install and configure gitleaks
  • ☑ Create comprehensive .gitignore
  • ☑ Enable fsckobjects for transfers
  • ☑ Use SSH keys with passphrase
Workflow:
  • ☑ Never commit secrets
  • ☑ Review changes before commit
  • ☑ Verify signatures on pull/merge
  • ☑ Regular security audits
  • ☑ Rotate credentials periodically
  • ☑ Use environment variables for secrets
仓库设置:
  • ☑ 启用分支保护
  • ☑ 要求签名提交
  • ☑ 启用带推送保护的密钥扫描
  • ☑ 启用CodeQL或类似扫描工具
  • ☑ 配置Dependabot/Renovate
  • ☑ 要求所有贡献者启用2FA
开发者工作站:
  • ☑ 使用GPG或SSH提交签名
  • ☑ 配置凭证管理器(绝不要使用明文)
  • ☑ 安装并配置gitleaks
  • ☑ 创建全面的.gitignore
  • ☑ 为传输启用fsckobjects
  • ☑ 使用带密码短语的SSH密钥
工作流:
  • ☑ 绝不要提交密钥
  • ☑ 提交前审查变更
  • ☑ 在拉取/合并时验证签名
  • ☑ 定期进行安全审计
  • ☑ 定期轮换凭证
  • ☑ 使用环境变量存储密钥

Incident Response

事件响应

Secret leaked in commit:
bash
undefined
密钥泄露到提交历史中:
bash
undefined

1. Rotate compromised credentials IMMEDIATELY

1. 立即轮换泄露的凭证

2. Remove from latest commit (if not pushed)

2. 若未推送,撤销最新提交

git reset HEAD~1
git reset HEAD~1

Edit files to remove secret

编辑文件移除密钥

git add . git commit -m "Remove secrets"
git add . git commit -m "Remove secrets"

3. If pushed, remove from history

3. 若已推送,从历史中移除

git filter-repo --path config/secrets.yml --invert-paths git push --force
git filter-repo --path config/secrets.yml --invert-paths git push --force

4. Notify team to re-clone

4. 通知团队重新克隆仓库

5. Enable push protection to prevent future leaks

5. 启用推送防护防止未来泄露


**Unsigned commits detected:**

```bash

**检测到未签名提交:**

```bash

Identify unsigned commits

识别未签名提交

git log --show-signature | grep "No signature"
git log --show-signature | grep "No signature"

Re-sign commits (if you authored them)

重新签名提交(若为自己提交的)

git rebase --exec 'git commit --amend --no-edit -n -S' -i HEAD~10
git rebase --exec 'git commit --amend --no-edit -n -S' -i HEAD~10

Force push (with team coordination)

强制推送(需与团队协调)

git push --force-with-lease
undefined
git push --force-with-lease
undefined

Resources

参考资源