implementing-secret-scanning-with-gitleaks skill (Anthropic-Cybersecurity-Skills)

From Public Agent Wiki
Contents
  1. Install
  2. SKILL.md (verbatim)
  3. When to Use
  4. Prerequisites
  5. Workflow
  6. Step 1: Install and Run Initial Repository Scan
  7. Step 2: Configure Pre-Commit Hook
  8. Step 3: Integrate into GitHub Actions
  9. Step 4: Author Custom Detection Rules
  10. Step 5: Manage Baselines for Existing Repositories
  11. Step 6: Remediate Exposed Secrets
  12. Key Concepts
  13. Tools & Systems
  14. Common Scenarios
  15. Scenario: Onboarding Secret Scanning on a Legacy Repository
  16. Output Format
  17. Other files in this skill
  18. assets/template.md (verbatim)
  19. Pre-Commit Configuration
  20. Organization Gitleaks Configuration
  21. GitHub Actions Workflow
  22. Incident Response Template for Exposed Secrets
  23. references/api-reference.md (verbatim)
  24. Libraries Used
  25. Installation
  26. CLI Commands
  27. Scan a Git Repository
  28. Scan a Directory (Non-Git)
  29. Scan from stdin
  30. Key CLI Flags
  31. Custom Configuration (.gitleaks.toml)
  32. Python Integration
  33. Run Gitleaks and Parse Results
  34. Categorize Findings by Severity
  35. GitHub Actions Integration
  36. Output Format
  37. references/standards.md (verbatim)
  38. OWASP Top 10 - A07:2021 Identification and Authentication Failures
  39. NIST SSDF (SP 800-218)
  40. PW.1: Design Software to Meet Security Requirements
  41. PS.1: Protect All Forms of Code
  42. PS.2: Provide a Mechanism for Verifying Software Release Integrity
  43. CIS Software Supply Chain Security Guide
  44. Source Code Controls
  45. OWASP SAMM - Secure Build
  46. Maturity Level 1
  47. Maturity Level 2
  48. Maturity Level 3
  49. PCI DSS v4.0
  50. SOC 2 Trust Service Criteria
  51. references/workflows.md (verbatim)
  52. Secret Detection Pipeline
  53. Gitleaks Rule Configuration Deep Dive
  54. Rule Anatomy
  55. Built-in Rule Categories
  56. Entropy Scoring
  57. Remediation Process
  58. Secret Rotation Checklist
  59. History Cleanup Decision Matrix

What it does. 'This skill covers implementing Gitleaks for detecting and preventing Part of mukul975/Anthropic-Cybersecurity-Skills (817 security skills) (mukul975/Anthropic-Cybersecurity-Skills).

Upstream mukul975/Anthropic-Cybersecurity-Skills
Skill file skills/implementing-secret-scanning-with-gitleaks/SKILL.md
License Apache-2.0 (skill folder LICENSE)
Author mukul975
Fetched 2026-09-10

Install

  • npx skills add mukul975/Anthropic-Cybersecurity-Skills --skill implementing-secret-scanning-with-gitleaks, or copy the skill folder into ~/.claude/skills/implementing-secret-scanning-with-gitleaks/.
  • Raw file: curl -sL https://raw.githubusercontent.com/mukul975/Anthropic-Cybersecurity-Skills/HEAD/skills/implementing-secret-scanning-with-gitleaks/SKILL.md

SKILL.md (verbatim)

name: implementing-secret-scanning-with-gitleaks
description: 'This skill covers implementing Gitleaks for detecting and preventing
  hardcoded secrets in git repositories. It addresses configuring pre-commit hooks,
  CI/CD pipeline integration, custom rule authoring for organization-specific secrets,
  baseline management for existing repositories, and remediation workflows for exposed
  credentials.

  '
domain: cybersecurity
subdomain: devsecops
tags:
- devsecops
- cicd
- secret-scanning
- gitleaks
- pre-commit
- secure-sdlc
version: 1.0.0
author: mahipal
license: Apache-2.0
nist_csf:
- PR.PS-01
- GV.SC-07
- ID.IM-04
- PR.PS-04
mitre_attack:
- T1195
- T1554
- T1059.004
- T1003
- T1110

Implementing Secret Scanning with Gitleaks

When to Use

  • When developers may accidentally commit API keys, passwords, tokens, or private keys to repositories
  • When establishing pre-commit gates that prevent secrets from entering the git history
  • When scanning existing repository history for previously committed secrets that need rotation
  • When compliance requirements mandate secret detection across all source code repositories
  • When migrating from manual secret audits to automated continuous scanning

Do not use for detecting secrets in running applications or memory (use runtime secret detection), for managing secrets after detection (use Vault or AWS Secrets Manager), or for scanning container images (use Trivy or Grype).

Prerequisites

  • Gitleaks v8.18+ installed via binary, Go install, or Docker
  • Pre-commit framework installed for local hook integration
  • Git repository with history to scan
  • CI/CD platform access (GitHub Actions, GitLab CI, or equivalent)

Workflow

Step 1: Install and Run Initial Repository Scan

Perform a baseline scan of the repository to identify all existing secrets in the git history.

# Install Gitleaks
brew install gitleaks  # macOS
# or download binary from https://github.com/gitleaks/gitleaks/releases

# Scan entire git history for secrets
gitleaks detect --source . --report-format json --report-path gitleaks-report.json -v

# Scan only staged changes (for pre-commit)
gitleaks protect --staged --report-format json --report-path gitleaks-staged.json

# Scan specific commit range
gitleaks detect --source . --log-opts="HEAD~10..HEAD" --report-format json

# Scan without git history (filesystem only)
gitleaks detect --source . --no-git --report-format json

Step 2: Configure Pre-Commit Hook

Set up Gitleaks as a pre-commit hook to prevent secrets from being committed.

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks
        name: gitleaks
        description: Detect hardcoded secrets using Gitleaks
        entry: gitleaks protect --staged --verbose --redact
        language: golang
        pass_filenames: false
# Install pre-commit framework
pip install pre-commit

# Install hooks defined in .pre-commit-config.yaml
pre-commit install

# Run against all files (not just staged)
pre-commit run gitleaks --all-files

# Test the hook with a deliberate secret
echo 'AWS_SECRET_ACCESS_KEY="wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"' >> test.txt
git add test.txt
git commit -m "test"  # Should be blocked by gitleaks

Step 3: Integrate into GitHub Actions

# .github/workflows/secret-scanning.yml
name: Secret Scanning

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]

jobs:
  gitleaks:
    name: Gitleaks Secret Scan
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0  # Full history for comprehensive scanning

      - name: Run Gitleaks
        uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          GITLEAKS_LICENSE: ${{ secrets.GITLEAKS_LICENSE }}  # Required for gitleaks-action v2

      # Alternative: Run Gitleaks directly
      - name: Install Gitleaks
        run: |
          wget -q https://github.com/gitleaks/gitleaks/releases/download/v8.21.2/gitleaks_8.21.2_linux_x64.tar.gz
          tar -xzf gitleaks_8.21.2_linux_x64.tar.gz
          chmod +x gitleaks

      - name: Scan for secrets
        run: |
          if [ "${{ github.event_name }}" == "pull_request" ]; then
            ./gitleaks detect \
              --source . \
              --log-opts="${{ github.event.pull_request.base.sha }}..${{ github.event.pull_request.head.sha }}" \
              --report-format sarif \
              --report-path gitleaks.sarif \
              --exit-code 1
          else
            ./gitleaks detect \
              --source . \
              --report-format sarif \
              --report-path gitleaks.sarif \
              --exit-code 1 \
              --baseline-path .gitleaks-baseline.json
          fi

      - name: Upload SARIF
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: gitleaks.sarif
          category: gitleaks

Step 4: Author Custom Detection Rules

Create organization-specific rules for internal secret patterns.

# .gitleaks.toml
title = "Organization Gitleaks Configuration"

[extend]
useDefault = true  # Include all default rules

# Custom rule for internal API tokens
[[rules]]
id = "internal-api-token"
description = "Internal API token for service-to-service auth"
regex = '''(?i)x-internal-token["\s:=]+["\']?([a-zA-Z0-9_\-]{40,})["\']?'''
entropy = 3.5
keywords = ["x-internal-token"]
tags = ["internal", "api"]

[[rules]]
id = "database-connection-string"
description = "Database connection string with embedded credentials"
regex = '''(?i)(postgres|mysql|mongodb|redis)://[^:]+:[^@]+@[^/]+/\w+'''
keywords = ["postgres://", "mysql://", "mongodb://", "redis://"]
tags = ["database", "credentials"]

[[rules]]
id = "jwt-secret"
description = "JWT signing secret"
regex = '''(?i)(jwt[_-]?secret|jwt[_-]?key)["\s:=]+["\']?([a-zA-Z0-9/+_\-]{32,})["\']?'''
entropy = 3.0
keywords = ["jwt_secret", "jwt-secret", "jwt_key", "jwt-key"]

# Allowlist for test files and known safe patterns
[allowlist]
description = "Global allowlist"
paths = [
  '''(^|/)test(s)?/''',
  '''(^|/)spec/''',
  '''\.test\.(js|ts|py)$''',
  '''\.spec\.(js|ts|py)$''',
  '''__mocks__/''',
  '''fixtures/''',
  '''(^|/)vendor/''',
  '''node_modules/'''
]
regexes = [
  '''EXAMPLE''',
  '''example\.com''',
  '''test[-_]?(key|secret|token|password)''',
  '''(?i)placeholder''',
  '''000000+'''
]

Step 5: Manage Baselines for Existing Repositories

Create a baseline of known findings to avoid blocking development while historical secrets are being rotated.

# Generate baseline from current state
gitleaks detect --source . --report-format json --report-path .gitleaks-baseline.json

# Subsequent scans compare against baseline (only new findings trigger failures)
gitleaks detect --source . --baseline-path .gitleaks-baseline.json --exit-code 1

# Review baseline periodically and remove entries as secrets are rotated
cat .gitleaks-baseline.json | python3 -m json.tool | head -50

Step 6: Remediate Exposed Secrets

When a secret is detected, follow the rotation and history cleanup procedure.

# 1. Immediately rotate the exposed credential
#    - Revoke the old API key/token in the service provider
#    - Generate a new credential
#    - Store the new credential in a secrets manager

# 2. Remove secret from git history using git-filter-repo
pip install git-filter-repo

# Create expressions file for secrets to remove
cat > /tmp/expressions.txt << 'EOF'
regex:AKIA[0-9A-Z]{16}==>REDACTED_AWS_KEY
regex:(?i)password\s*=\s*"[^"]*"==>password="REDACTED"
EOF

git filter-repo --replace-text /tmp/expressions.txt --force

# 3. Force-push the cleaned history (coordinate with team)
# git push --force --all  # WARNING: Requires team coordination

# 4. Add the secret pattern to .gitleaks.toml rules
# 5. Update the baseline file to remove the resolved finding

Key Concepts

Term Definition
Secret Any credential, token, key, or sensitive string that should not appear in source code
Pre-commit Hook Git hook that runs before a commit is created, blocking commits containing detected secrets
Entropy Measure of randomness in a string; high-entropy strings are more likely to be secrets
Baseline Snapshot of existing findings used to differentiate new secrets from pre-existing ones
Allowlist Configuration specifying paths, patterns, or commits to exclude from detection
SARIF Static Analysis Results Interchange Format for uploading findings to security dashboards
git-filter-repo Tool for rewriting git history to remove sensitive data from all commits

Tools & Systems

  • Gitleaks: Open-source secret detection tool supporting pre-commit hooks, CI/CD, and historical scanning
  • pre-commit: Framework for managing and maintaining multi-language pre-commit hooks
  • git-filter-repo: History rewriting tool for removing secrets from git history
  • TruffleHog: Alternative secret scanner with verified secret detection capabilities
  • GitHub Secret Scanning: Native GitHub feature that detects secrets matching partner patterns

Common Scenarios

Scenario: Onboarding Secret Scanning on a Legacy Repository

Context: A 5-year-old repository has never been scanned. The team needs to enable secret scanning without blocking all development while historical secrets are rotated.

Approach:

  1. Run gitleaks detect against full history and generate a baseline JSON file
  2. Triage each finding: classify as active (needs rotation), inactive (already rotated), or false positive
  3. Immediately rotate all active secrets and update consuming services
  4. Commit the baseline file (excluding active secrets that have been fixed)
  5. Enable pre-commit hooks for new development immediately
  6. Add CI/CD scanning with the baseline to catch only new secrets
  7. Progressively reduce the baseline as historical secrets are rotated

Pitfalls: Generating a baseline without triaging means accepting risk on unrotated secrets. Never assume a historical secret is inactive without verifying with the service provider. Running git-filter-repo on a shared repository without coordination will cause rebase conflicts for all team members.

Output Format

Gitleaks Secret Scanning Report
=================================
Repository: org/web-application
Scan Type: Full History
Commits Scanned: 4,523
Date: 2026-02-23

FINDINGS:
  Total: 12
  New (not in baseline): 3
  Baseline (pre-existing): 9

NEW FINDINGS (blocking):
  [1] AWS Access Key ID
      Rule: aws-access-key-id
      File: src/config/aws.py:23
      Commit: a1b2c3d (2026-02-22, dev@company.com)
      Secret: AKIA...REDACTED
      Entropy: 3.8

  [2] GitHub Personal Access Token
      Rule: github-pat
      File: scripts/deploy.sh:15
      Commit: d4e5f6g (2026-02-21, ops@company.com)
      Secret: ghp_...REDACTED
      Entropy: 4.2

  [3] Internal API Token
      Rule: internal-api-token
      File: src/services/auth.py:89
      Commit: h7i8j9k (2026-02-20, dev@company.com)

QUALITY GATE: FAILED (3 new findings)
Action: Rotate exposed credentials immediately.

Other files in this skill

assets/template.md (verbatim)

Gitleaks Secret Scanning Templates

Pre-Commit Configuration

# .pre-commit-config.yaml
repos:
  - repo: https://github.com/gitleaks/gitleaks
    rev: v8.21.2
    hooks:
      - id: gitleaks
        name: Detect secrets with Gitleaks
        entry: gitleaks protect --staged --verbose --redact
        language: golang
        pass_filenames: false

Organization Gitleaks Configuration

# .gitleaks.toml
title = "Organization Secret Scanning Rules"

[extend]
useDefault = true

# ─── Custom Rules ───

[[rules]]
id = "internal-service-token"
description = "Internal service-to-service authentication token"
regex = '''(?i)(service[_-]?token|internal[_-]?key)["\s:=]+["']?([A-Za-z0-9_\-]{36,})["']?'''
entropy = 3.5
keywords = ["service_token", "service-token", "internal_key", "internal-key"]

[[rules]]
id = "database-url-with-password"
description = "Database connection URL with embedded password"
regex = '''(?i)(DATABASE_URL|DB_URL|SQLALCHEMY_DATABASE_URI)\s*=\s*["']?(postgres|mysql|mongodb)\+?[a-z]*://[^:]+:[^@]+@'''
keywords = ["DATABASE_URL", "DB_URL", "SQLALCHEMY_DATABASE_URI"]

[[rules]]
id = "encryption-key-hex"
description = "Encryption key in hexadecimal format"
regex = '''(?i)(encryption[_-]?key|aes[_-]?key|secret[_-]?key)\s*=\s*["']?([0-9a-fA-F]{32,64})["']?'''
entropy = 3.0
keywords = ["encryption_key", "aes_key", "secret_key"]

# ─── Allowlist ───

[allowlist]
description = "Global allowlist for false positive reduction"
paths = [
  '''(^|/)test(s)?/''',
  '''(^|/)spec(s)?/''',
  '''\.test\.(js|ts|py|go|rb)$''',
  '''\.spec\.(js|ts|py|go|rb)$''',
  '''(^|/)__tests__/''',
  '''(^|/)__mocks__/''',
  '''(^|/)fixtures/''',
  '''(^|/)testdata/''',
  '''(^|/)vendor/''',
  '''(^|/)node_modules/''',
  '''\.md$''',
  '''CHANGELOG'''
]
regexes = [
  '''(?i)EXAMPLE''',
  '''(?i)PLACEHOLDER''',
  '''(?i)CHANGEME''',
  '''(?i)your[-_]?(api[-_]?key|secret|token|password)''',
  '''(?i)test[-_]?(key|secret|token|password|credential)''',
  '''example\.com''',
  '''localhost''',
  '''0{8,}''',
  '''x{8,}'''
]

# Per-rule allowlists
[[rules.allowlist]]
description = "Allow AWS example keys"
regexes = ["AKIAIOSFODNN7EXAMPLE"]

GitHub Actions Workflow

# .github/workflows/secret-scanning.yml
name: Secret Scanning

on:
  push:
    branches: [main, develop]
  pull_request:
    branches: [main]
  schedule:
    - cron: '0 6 * * *'

jobs:
  gitleaks:
    name: Gitleaks
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: Install Gitleaks
        run: |
          GITLEAKS_VERSION="8.21.2"
          wget -qO- "https://github.com/gitleaks/gitleaks/releases/download/v${GITLEAKS_VERSION}/gitleaks_${GITLEAKS_VERSION}_linux_x64.tar.gz" | tar xz
          sudo mv gitleaks /usr/local/bin/

      - name: Run scan
        run: |
          if [ "${{ github.event_name }}" == "pull_request" ]; then
            gitleaks detect \
              --source . \
              --log-opts="${{ github.event.pull_request.base.sha }}..${{ github.sha }}" \
              --report-format sarif \
              --report-path gitleaks.sarif \
              --exit-code 1 \
              --verbose
          else
            gitleaks detect \
              --source . \
              --baseline-path .gitleaks-baseline.json \
              --report-format sarif \
              --report-path gitleaks.sarif \
              --exit-code 1 \
              --verbose
          fi

      - name: Upload SARIF
        if: always()
        uses: github/codeql-action/upload-sarif@v3
        with:
          sarif_file: gitleaks.sarif
          category: gitleaks

Incident Response Template for Exposed Secrets

## Secret Exposure Incident Report

**Date Detected**: YYYY-MM-DD
**Detected By**: Gitleaks CI scan / Pre-commit hook / Manual review
**Repository**: org/repo-name
**Severity**: Critical / High

### Exposed Credential Details
- **Type**: [AWS Access Key | GitHub PAT | Database Password | etc.]
- **Rule ID**: [gitleaks rule that detected it]
- **File**: [path/to/file:line]
- **Commit**: [short SHA]
- **Author**: [email]
- **Date Committed**: [date]
- **Exposure Duration**: [time from commit to detection]

### Remediation Actions
- [ ] Credential revoked at service provider
- [ ] New credential generated and stored in secrets manager
- [ ] Consuming services updated to use new credential
- [ ] Service functionality verified
- [ ] Git history cleaned (if required)
- [ ] Baseline updated
- [ ] Root cause documented

### Root Cause
[Why was the secret committed? Missing pre-commit hook? Developer education gap?]

### Preventive Measures
[What changes prevent recurrence? Hook enforcement? Rule addition?]

references/api-reference.md (verbatim)

API Reference: Gitleaks Secret Scanning

Libraries Used

Library Purpose
subprocess Execute gitleaks CLI commands
json Parse gitleaks JSON report output
pathlib Handle repository and report file paths
os Read GITLEAKS_CONFIG environment variable

Installation

# Install gitleaks binary
# macOS
brew install gitleaks

# Linux
curl -sSfL https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_linux_x64 -o gitleaks
chmod +x gitleaks && sudo mv gitleaks /usr/local/bin/

# Docker
docker pull ghcr.io/gitleaks/gitleaks:latest

CLI Commands

Scan a Git Repository

gitleaks git --source=/path/to/repo --report-format=json --report-path=results.json

Scan a Directory (Non-Git)

gitleaks dir --source=/path/to/code --report-format=json --report-path=results.json

Scan from stdin

echo "aws_secret_access_key=AKIAIOSFODNN7EXAMPLE" | gitleaks stdin

Key CLI Flags

Flag Description
--source Path to repository or directory to scan
--config, -c Path to custom gitleaks.toml config
--report-format, -f Output format: json, csv, junit, sarif
--report-path, -r Path to write the report file
--baseline-path Ignore known findings from baseline file
--exit-code Exit code when leaks found (default: 1)
--redact Redact secrets in output (percent: 0-100)
--verbose, -v Show verbose scan output
--no-git Treat source as plain directory
--log-level Log level: trace, debug, info, warn, error
--max-target-megabytes Skip files larger than this size

Custom Configuration (.gitleaks.toml)

title = "Custom Gitleaks Config"

[extend]
useDefault = true  # Extend the default ruleset

[[rules]]
id = "custom-internal-token"
description = "Internal API token pattern"
regex = '''(?i)internal[_-]?token\s*[:=]\s*['"]?([a-zA-Z0-9]{32,})'''
tags = ["internal", "token"]
keywords = ["internal_token", "internal-token"]

[[rules]]
id = "custom-db-password"
description = "Database password in config"
regex = '''(?i)(db|database|mysql|postgres)[_-]?pass(word)?\s*[:=]\s*['"]?[^\s'"]{8,}'''
tags = ["database", "password"]

[rules.allowlist]
paths = ['''test/.*''', '''mock/.*''']
regexTarget = "line"
regexes = ['''(?i)example|placeholder|changeme|test''']

[[allowlist.paths]]
regex = '''vendor/.*'''

[[allowlist.commits]]
sha = "abc123def456"

Python Integration

Run Gitleaks and Parse Results

import subprocess
import json
from pathlib import Path

def scan_repository(repo_path, config_path=None):
    cmd = [
        "gitleaks", "git",
        "--source", str(repo_path),
        "--report-format", "json",
        "--report-path", "/tmp/gitleaks-report.json",
        "--exit-code", "0",
    ]
    if config_path:
        cmd.extend(["--config", str(config_path)])

    result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)

    report_path = Path("/tmp/gitleaks-report.json")
    if report_path.exists():
        with open(report_path) as f:
            findings = json.load(f)
        return findings
    return []

Categorize Findings by Severity

HIGH_SEVERITY_RULES = {
    "aws-access-key", "aws-secret-key", "gcp-api-key",
    "github-pat", "private-key", "generic-api-key",
}

def categorize_findings(findings):
    high, medium, low = [], [], []
    for f in findings:
        rule = f.get("RuleID", "")
        if rule in HIGH_SEVERITY_RULES:
            high.append(f)
        elif "password" in rule or "token" in rule:
            medium.append(f)
        else:
            low.append(f)
    return {"high": high, "medium": medium, "low": low}

GitHub Actions Integration

name: Gitleaks Secret Scan
on: [push, pull_request]
jobs:
  gitleaks:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0
      - uses: gitleaks/gitleaks-action@v2
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

Output Format

[
  {
    "Description": "Detected a Generic API Key",
    "StartLine": 42,
    "EndLine": 42,
    "StartColumn": 15,
    "EndColumn": 55,
    "Match": "REDACTED",
    "Secret": "REDACTED",
    "File": "config/settings.py",
    "Commit": "a1b2c3d4e5f6",
    "Author": "developer@example.com",
    "Date": "2025-01-15T10:30:00Z",
    "RuleID": "generic-api-key",
    "Tags": ["api", "key"],
    "Fingerprint": "a1b2c3d4:config/settings.py:generic-api-key:42"
  }
]

references/standards.md (verbatim)

Standards Reference: Secret Scanning with Gitleaks

OWASP Top 10 - A07:2021 Identification and Authentication Failures

  • Hardcoded credentials in source code enable unauthorized access
  • Gitleaks detects API keys, passwords, tokens, and private keys before they reach repositories
  • CWE-798: Use of Hard-coded Credentials is a direct mapping

NIST SSDF (SP 800-218)

PW.1: Design Software to Meet Security Requirements

  • PW.1.1: Identify security requirements including credential management
  • Secrets should never be stored in source code; use environment variables or secrets managers

PS.1: Protect All Forms of Code

  • PS.1.1: Store code securely with access controls and secret scanning
  • Implement pre-commit hooks to prevent secrets from entering version control

PS.2: Provide a Mechanism for Verifying Software Release Integrity

  • Code signing and secret scanning ensure software releases do not contain embedded credentials

CIS Software Supply Chain Security Guide

Source Code Controls

  • SC-1: Automated secret scanning on all commits
  • SC-5: No hardcoded credentials in source repositories
  • SC-6: Secrets detection integrated into CI/CD pipeline

OWASP SAMM - Secure Build

Maturity Level 1

  • Scan repositories for common secret patterns using default rulesets
  • Alert developers when secrets are detected in pull requests

Maturity Level 2

  • Custom rules for organization-specific secret patterns
  • Pre-commit hooks prevent secrets from entering history
  • Baseline management for legacy codebases

Maturity Level 3

  • Automated secret rotation workflow triggered by detection
  • Correlation with secrets management systems for validation
  • Historical scanning with git-filter-repo remediation

PCI DSS v4.0

  • Requirement 6.3.1: Security vulnerabilities identified through a defined process including code analysis
  • Requirement 8.6.1: Secrets stored in code or configuration files must be protected
  • Requirement 8.6.3: Passwords/passphrases for application and system accounts are protected against misuse

SOC 2 Trust Service Criteria

  • CC6.1: Logical access security over protected information assets including credential management
  • CC6.7: Restrict transmission of data to authorized external parties (prevent credential leakage)

references/workflows.md (verbatim)

Workflow Reference: Secret Scanning with Gitleaks

Secret Detection Pipeline

Developer Workstation          CI/CD Pipeline              Security Response
     │                              │                           │
     ▼                              │                           │
┌──────────────┐                    │                           │
│ Pre-commit   │                    │                           │
│ Hook (local) │                    │                           │
└──────┬───────┘                    │                           │
       │                            │                           │
  ┌────┴────┐                       │                           │
  │         │                       │                           │
PASS      FAIL                      │                           │
  │     (blocked)                   │                           │
  ▼                                 │                           │
Push to                             │                           │
Remote                              │                           │
  │                                 ▼                           │
  │                        ┌──────────────┐                     │
  └───────────────────────>│ Gitleaks CI  │                     │
                           │ Scan (PR)    │                     │
                           └──────┬───────┘                     │
                                  │                             │
                            ┌─────┴─────┐                      │
                            │           │                       │
                          PASS        FAIL                      │
                            │     ┌─────┴──────┐               │
                            │     │ Block PR   │               │
                            │     │ + Alert    │──────────────>│
                            │     └────────────┘    ┌──────────┴──────┐
                            │                       │ Rotate Secret   │
                            │                       │ Update Baseline │
                            │                       │ Clean History   │
                            │                       └─────────────────┘
                            ▼
                    Merge Permitted

Gitleaks Rule Configuration Deep Dive

Rule Anatomy

[[rules]]
id = "rule-unique-identifier"          # Unique rule ID
description = "Human-readable desc"     # What this rule detects
regex = '''pattern'''                   # Detection regex
entropy = 3.5                           # Minimum entropy threshold (optional)
secretGroup = 1                         # Regex capture group containing secret
keywords = ["key1", "key2"]             # Fast pre-filter keywords
tags = ["aws", "credential"]            # Categorization tags
path = '''\.env$'''                     # Path filter regex (optional)

Built-in Rule Categories

Category Example Rules Count
Cloud Provider Keys aws-access-key-id, gcp-service-account 15+
API Tokens github-pat, gitlab-pat, slack-token 20+
Private Keys private-key, rsa-private-key 5+
Database Credentials generic-password, connection-string 10+
Service Tokens stripe-api-key, sendgrid-api-key 30+

Entropy Scoring

  • Entropy measures string randomness (Shannon entropy)
  • Random-looking strings (API keys) have entropy > 3.5
  • Regular English text has entropy around 2.0-3.0
  • Setting entropy threshold reduces false positives on non-random strings
  • Combine entropy with regex for highest accuracy

Remediation Process

Secret Rotation Checklist

  1. Identify the exposed secret type and associated service
  2. Log into the service provider and revoke the exposed credential
  3. Generate a new credential with the same permissions
  4. Store the new credential in a secrets manager (Vault, AWS SM, etc.)
  5. Update all consuming services to use the new credential
  6. Verify service functionality with the new credential
  7. Update the Gitleaks baseline to remove the resolved finding
  8. Optionally clean git history with git-filter-repo

History Cleanup Decision Matrix

Factor Clean History Keep History
Secret is rotated Optional Acceptable
Repo is public Required Never
Compliance mandate Required Not compliant
Active contributor count < 10 preferred > 10 difficult
Secret exposure duration Long (high risk) Short (lower risk)

Back to mukul975/Anthropic-Cybersecurity-Skills (817 security skills) or Agent skills.