Hardcoded credentials, API access keys, database passwords, and private cryptographic certificates represent some of the most critical security vulnerabilities in modern software engineering. When committed to source control systems like Git, sensitive tokens frequently persist across revision histories even if immediately deleted in subsequent commits. To prevent accidental token leakage, developers and DevOps engineers rely on automated scanning utilities. Gitleaks is an open-source, fast, and lightweight SAX-based static analysis tool designed specifically to scan Git repositories, commits, and directories for hardcoded secrets.
In this guide, you will learn how to install Gitleaks on Linux distributions, execute repository scans, inspect commit history, configure custom detection rules, and integrate pre-commit hooks to automate repository protection.
What Is Gitleaks and How Does It Work?
Gitleaks inspects text files, diff patches, and Git tree objects by matching content against regular expressions, Shannon entropy calculations, and predefined rule patterns. Unlike naive grep searches, Gitleaks understands Git internals, allowing it to parse specific commit ranges, staged changes, and uncommitted working tree modifications.
Key features of Gitleaks include:
- Broad Detection Ruleset: Includes built-in patterns for AWS credentials, GitHub personal access tokens, Google Cloud keys, Slack webhooks, Stripe secret keys, and private SSH keys.
- Entropy Analysis: Flags high-entropy alphanumeric strings that often indicate obfuscated API keys or generated secrets.
- Flexible Output Formats: Generates structured reports in JSON, CSV, SARIF (for GitHub Code Scanning), and standard terminal summaries.
- Git Integration: Supports pre-commit hooks, CI/CD pipeline enforcement, and baseline files to ignore existing historical findings.
Installing Gitleaks on Linux
Gitleaks is distributed as a standalone Go binary, making installation straightforward on any modern Linux distribution, including Ubuntu, Debian, Fedora, Arch Linux, and Rocky Linux.
Method 1: Installing via Official Binary Release (Universal)
Downloading the pre-compiled binary is the most reliable method across all distributions. Run the following terminal commands to retrieve and install the latest release:
# Download the latest Gitleaks tarball for 64-bit Linux
curl -sSL https://github.com/gitleaks/gitleaks/releases/latest/download/gitleaks_linux_x64.tar.gz -o gitleaks.tar.gz
# Extract the archive
tar -xzf gitleaks.tar.gz
# Move the binary into your system executable path
sudo mv gitleaks /usr/local/bin/
# Clean up leftover archive files
rm -f gitleaks.tar.gz README.md LICENSE
# Verify successful installation
gitleaks version
Method 2: Installing via Homebrew on Linux
If you use Linuxbrew, install Gitleaks directly through brew:
brew install gitleaks
Method 3: Running via Docker
If you prefer not to install standalone binaries, you can run Gitleaks inside an isolated container:
docker run --rm -v $(pwd):/repo zricethezav/gitleaks:latest detect --source=/repo -v
Scanning a Git Repository for Secrets
Once installed, navigate to the root directory of any Git repository you wish to inspect.
Scanning Entire Commit History
To audit every commit across all branches and history:
gitleaks detect --source=. --verbose
The --verbose (or -v) flag prints detailed findings directly in the terminal, including the offending file path, commit hash, author email, matched rule, and redacted secret string.
Scanning Only Uncommitted Changes
Before executing a commit or push, scan your current staged and unstaged working directory changes:
gitleaks detect --source=. --no-git=false --log-opts="HEAD..HEAD"
Alternatively, to inspect uncommitted staged files specifically:
gitleaks protect --staged --verbose
Exporting Scan Reports
For audits and compliance reporting, export Gitleaks results to structured formats using the --report-path and --report-format flags:
# Export findings to a JSON file
gitleaks detect --source=. --report-path=gitleaks-report.json --report-format=json
# Export findings to SARIF format for CI/CD dashboards
gitleaks detect --source=. --report-path=gitleaks-report.sarif --report-format=sarif
Configuring Custom Rules and Baselines
Repositories frequently contain mock tokens, dummy API keys in unit tests, or proprietary internal credential formats that require custom configuration.
Ignoring Known False Positives with a Baseline
If an existing repository has historical findings that cannot be immediately rewritten, generate a baseline file so future scans only flag newly introduced secrets:
# Generate an ignore file containing current findings
gitleaks detect --source=. --report-path=.gitleaksignore
When .gitleaksignore is present in the repository root, subsequent executions of gitleaks detect will automatically suppress matched fingerprinted items.
Defining Custom Rules with a Config File
Create a custom configuration file named .gitleaks.toml in your repository root to define project-specific regex patterns or extend default rules:
[extend]
useDefault = true
[[rules]]
id = "internal-api-token"
description = "Detected Internal Company API Token"
regex = '''(?i)(internal_token|corp_secret)\s*[:=]\s*['\"][a-z0-9]{32}['\"]'''
keywords = ["internal_token", "corp_secret"]
[rules.allowlist]
paths = ['''tests/mocks/.*''']
Execute the scan referencing your custom configuration:
gitleaks detect --config=.gitleaks.toml --verbose
Setting Up Pre-Commit Git Hooks
The most effective defence against credential leaks is blocking commits before they leave the developer’s workstation. Gitleaks includes native support for Git hooks.
Native Git Hook Setup
Add a lightweight pre-commit hook script inside your repository’s .git/hooks/ directory:
cat << 'EOF' > .git/hooks/pre-commit
#!/bin/bash
gitleaks protect --staged --verbose
if [ $? -ne 0 ]; then
echo "Gitleaks detected sensitive tokens in your staged changes."
echo "Commit aborted. Please remove or mask secrets before proceeding."
exit 1
fi
EOF
chmod +x .git/hooks/pre-commit
Using the Python pre-commit Framework
If your team uses the popular pre-commit framework, add Gitleaks to your .pre-commit-config.yaml file:
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.18.2
hooks:
- id: gitleaks
Install the hook by running:
pre-commit install
Remediating Leaked Secrets
If Gitleaks detects a genuine credential in your repository history, follow these critical remediation steps:
- Revoke Immediately: Treat any exposed secret as compromised. Immediately invalidate the token, password, or key in the relevant service console (e.g., AWS IAM, GitHub Developer Settings, or Stripe Dashboard).
- Purge Git History: Merely deleting the file in a new commit leaves the secret accessible in historical commit snapshots. Use tools like
git-filter-repoor BFG Repo-Cleaner to permanently scrub the sensitive string across all branch trees. - Force Push with Caution: Coordinate with all team members before force-pushing rewritten histories to shared remote repositories.