1575 từ
8 phút đọc
Gitleaks - Công cụ phát hiện secret và thông tin nhạy cảm trong Git

Gitleaks - Bảo vệ mã nguồn khỏi rò rỉ thông tin nhạy cảm#

Trong thời đại DevOps và CI/CD, việc bảo mật thông tin nhạy cảm trong mã nguồn là một thách thức lớn. Gitleaks là một công cụ mã nguồn mở được viết bằng Go, chuyên dụng để phát hiện các secrets như passwords, API keys, tokens và các thông tin nhạy cảm khác trong Git repositories.

Giới thiệu về Gitleaks#

Gitleaks sử dụng các biểu thức chính quy (regex) để quét và phát hiện các patterns của secrets trong:

  • Git repositories (history và commits)
  • Directories và files
  • Data từ stdin

Với hơn 23.6k stars trên GitHub và được tin dùng bởi nhiều tổ chức lớn, Gitleaks đã trở thành một trong những công cụ security scanning phổ biến nhất trong cộng đồng DevSecOps.

Kiến trúc hoạt động của Gitleaks#

graph TD
A[Source Input] --> B{Input Type}
B -->|Git Repository| C[Git Log Scanner]
B -->|Directory/Files| D[File System Scanner]
B -->|Stdin| E[Stream Scanner]
C --> F[Content Processor]
D --> F
E --> F
F --> G[Regex Engine]
G --> H[Pattern Matching]
H --> I{Match Found?}
I -->|Yes| J[Entropy Check]
I -->|No| K[Continue Scanning]
J --> L{High Entropy?}
L -->|Yes| M[Secret Detected]
L -->|No| K
M --> N[Apply Allowlists]
N --> O{In Allowlist?}
O -->|Yes| K
O -->|No| P[Report Finding]
K --> Q[Scan Complete]
P --> Q
style M fill:#ff6b6b
style P fill:#ff6b6b
style G fill:#4ecdc4
style H fill:#4ecdc4

Tại sao cần Gitleaks?#

Vấn đề thường gặp#

Terminal window
# Những ví dụ về secrets bị rò rỉ
export DATABASE_PASSWORD="super_secret_password123"
const API_KEY = "sk-1234567890abcdef"
AWS_SECRET_ACCESS_KEY=AKIAIOSFODNN7EXAMPLE

Hệ quả của việc rò rỉ secrets#

  • Tấn công bảo mật: Kẻ tấn công có thể truy cập vào hệ thống
  • Mất dữ liệu: Thông tin khách hàng có thể bị đánh cắp
  • Chi phí tài chính: Phí phạt, chi phí khắc phục sự cố
  • Uy tín công ty: Mất lòng tin từ khách hàng và đối tác

Timeline của một security incident#

gantt
title Quá trình từ Secret Leak đến Security Incident
dateFormat YYYY-MM-DD
axisFormat %m/%d
section Development
Dev commit secret :done, dev1, 2025-01-01, 1d
Code review bỏ qua :done, dev2, after dev1, 1d
Merge vào main branch :done, dev3, after dev2, 1d
section Discovery
Automated scan phát hiện :crit, disc1, after dev3, 2d
Manual review :disc2, after disc1, 1d
section Attack
Attacker tìm thấy secret :crit, attack1, after dev3, 5d
Reconnaissance :attack2, after attack1, 2d
Initial compromise :crit, attack3, after attack2, 1d
Data exfiltration :crit, attack4, after attack3, 3d
section Response
Incident detected :resp1, after attack4, 1d
Emergency response :crit, resp2, after resp1, 2d
Forensic investigation :resp3, after resp2, 5d
Recovery & hardening :resp4, after resp3, 7d

So sánh: Với và không có Gitleaks#

graph LR
subgraph "Không có Gitleaks"
A1[Developer] --> B1[Commit Secret]
B1 --> C1[Push to Repo]
C1 --> D1[Deploy to Production]
D1 --> E1[Secret Exposed]
E1 --> F1[Security Breach]
F1 --> G1[Incident Response]
G1 --> H1[Business Impact]
end
subgraph "Có Gitleaks"
A2[Developer] --> B2[Commit Secret]
B2 --> C2[Pre-commit Hook]
C2 --> D2{Gitleaks Scan}
D2 -->|Secret Found| E2[Block Commit]
D2 -->|Clean| F2[Allow Commit]
E2 --> G2[Developer Fix]
G2 --> B2
F2 --> H2[Safe Deployment]
end
style E1 fill:#ff6b6b
style F1 fill:#ff6b6b
style H1 fill:#ff6b6b
style E2 fill:#ffa726
style H2 fill:#66bb6a

Cài đặt Gitleaks#

MacOS (Homebrew)#

Terminal window
brew install gitleaks

Docker#

Terminal window
# Docker Hub
docker pull zricethezav/gitleaks:latest
# GitHub Container Registry
docker pull ghcr.io/gitleaks/gitleaks:latest

Build từ source#

Terminal window
git clone https://github.com/gitleaks/gitleaks.git
cd gitleaks
make build

GitHub Action#

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

Cách sử dụng Gitleaks#

1. Quét Git Repository#

Terminal window
# Quét repository hiện tại
gitleaks git
# Quét repository cụ thể với verbose output
gitleaks git -v /path/to/repo
# Quét trong khoảng commits cụ thể
gitleaks git --log-opts="--all commitA..commitB" /path/to/repo

2. Quét Directories và Files#

Terminal window
# Quét thư mục hiện tại
gitleaks dir
# Quét thư mục cụ thể
gitleaks dir -v /path/to/directory
# Quét file cụ thể
gitleaks dir -v /path/to/file.js

3. Quét từ stdin#

Terminal window
# Pipe content vào gitleaks
cat some_file.env | gitleaks stdin
# Kết hợp với các command khác
echo "password=secret123" | gitleaks stdin -v

Cấu hình nâng cao#

Tạo file cấu hình tùy chỉnh#

.gitleaks.toml
title = "Custom Gitleaks Configuration"
[extend]
useDefault = true
disabledRules = ["generic-api-key"]
[[rules]]
id = "custom-secret"
description = "Custom secret pattern"
regex = '''custom-pattern-[a-zA-Z0-9]{20}'''
secretGroup = 0
entropy = 3.5
keywords = ["custom", "secret"]
tags = ["custom"]
[[rules.allowlists]]
description = "ignore test files"
paths = ['''test/.*\.js$''']

Sử dụng baseline để ignore các findings cũ#

Terminal window
# Tạo baseline
gitleaks git --report-path baseline.json
# Sử dụng baseline để chỉ phát hiện findings mới
gitleaks git --baseline-path baseline.json --report-path new-findings.json

Pre-commit Hook#

Cài đặt pre-commit hook#

.pre-commit-config.yaml
repos:
- repo: https://github.com/gitleaks/gitleaks
rev: v8.28.0
hooks:
- id: gitleaks
Terminal window
# Cài đặt
pre-commit install
# Test commit
git commit -m "this commit contains a secret"
# Output: Detect hardcoded secrets.................................................Failed

Bỏ qua gitleaks cho commit cụ thể#

Terminal window
SKIP=gitleaks git commit -m "skip gitleaks check"

Các tính năng nâng cao#

1. Composite Rules (Multi-part Rules)#

[[rules]]
id = "primary-rule"
description = "Primary rule requiring auxiliary matches"
regex = '''password\s*=\s*['"]([^'"]+)['"]'''
secretGroup = 1
# Required auxiliary rule
[[rules.required]]
id = "database-context"
withinLines = 5
withinColumns = 50

2. Decoding tự động#

Terminal window
# Bật tính năng decode cho base64, hex, percent encoding
gitleaks git --max-decode-depth 3

3. Archive scanning#

Terminal window
# Quét bên trong các file archive (zip, tar, etc.)
gitleaks git --max-archive-depth 2

4. Custom reporting#

Terminal window
# Export ra JSON
gitleaks git --report-format json --report-path report.json
# Export ra CSV
gitleaks git --report-format csv --report-path report.csv
# Export ra SARIF (cho GitHub Security tab)
gitleaks git --report-format sarif --report-path report.sarif
# Custom template
gitleaks git --report-format template --report-template custom.tmpl

Bỏ qua false positives#

1. Sử dụng comment inline#

const fakeApiKey = "fake-key-for-testing"; // gitleaks:allow

2. Tạo file .gitleaksignore#

.gitleaksignore
# Thêm fingerprint của findings cần bỏ qua
8d3f3d7a1c2b4e5f6789abcdef:src/test/fixtures.js:generic-api-key:15

3. Cấu hình allowlists trong config#

[[allowlists]]
description = "ignore test files"
paths = ['''test/.*''', '''spec/.*''']
regexes = ['''fake-.*''', '''test-.*''']

Tích hợp vào CI/CD Pipeline#

Workflow tích hợp Gitleaks vào CI/CD#

sequenceDiagram
participant Dev as Developer
participant Git as Git Repository
participant CI as CI/CD Pipeline
participant GL as Gitleaks Scanner
participant Rep as Report System
participant Sec as Security Team
Dev->>Git: Push code
Git->>CI: Trigger pipeline
CI->>GL: Run Gitleaks scan
alt Secrets found
GL->>Rep: Generate security report
Rep->>Sec: Alert security team
GL->>CI: Fail pipeline
CI->>Dev: Block deployment
Dev->>Dev: Fix secrets
Dev->>Git: Push fixed code
else No secrets
GL->>CI: Pass scan
CI->>CI: Continue deployment
end

Multi-stage security pipeline#

graph TB
subgraph "Security Gates"
A[Code Commit] --> B[Pre-commit Hook]
B --> C{Gitleaks Check}
C -->|Pass| D[Push to Repository]
C -->|Fail| E[Block Commit]
E --> F[Developer Fix]
F --> B
D --> G[CI/CD Trigger]
G --> H[Gitleaks Full Scan]
H --> I{Comprehensive Check}
I -->|Pass| J[SAST/DAST Tests]
I -->|Fail| K[Pipeline Failure]
J --> L{All Tests Pass?}
L -->|Yes| M[Deploy to Staging]
L -->|No| N[Security Review]
M --> O[Production Gitleaks Scan]
O --> P{Final Security Check}
P -->|Pass| Q[Deploy to Production]
P -->|Fail| R[Emergency Stop]
end
style C fill:#ffa726
style I fill:#ffa726
style P fill:#ffa726
style E fill:#ff6b6b
style K fill:#ff6b6b
style R fill:#ff6b6b
style Q fill:#66bb6a

GitHub Actions#

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

GitLab CI#

.gitlab-ci.yml
gitleaks:
stage: security
image:
name: zricethezav/gitleaks:latest
entrypoint: [""]
script:
- gitleaks git -v --source . --report-format json --report-path gitleaks-report.json
artifacts:
reports:
security:
- gitleaks-report.json
when: always

Jenkins Pipeline#

pipeline {
agent any
stages {
stage('Security Scan') {
steps {
script {
docker.image('zricethezav/gitleaks:latest').inside {
sh 'gitleaks git -v --source . --report-format json --report-path gitleaks-report.json'
}
}
}
post {
always {
archiveArtifacts artifacts: 'gitleaks-report.json', fingerprint: true
}
}
}
}
}

Best Practices#

Types of Secrets được Gitleaks phát hiện#

mindmap
root((Gitleaks Detection))
API Keys
AWS Access Key
Google API Key
GitHub Token
OpenAI API Key
Stripe API Key
Database Credentials
MySQL Password
PostgreSQL Connection
MongoDB URI
Redis Password
SQLite Database
Cloud Services
Azure Client Secret
GCP Service Account
Docker Registry
Kubernetes Secrets
Terraform Tokens
Third-party Services
Slack Webhook
Twilio Auth Token
SendGrid API Key
Mailgun API Key
Discord Bot Token
Cryptographic Keys
RSA Private Key
SSH Private Key
GPG Private Key
JWT Secret
Encryption Keys
Generic Patterns
Password Fields
Secret Variables
Auth Headers
Bearer Tokens
Basic Auth

Security maturity levels với Gitleaks#

graph TD
A[Level 0: Reactive] --> B[Level 1: Basic Protection]
B --> C[Level 2: Integrated Security]
C --> D[Level 3: Advanced Monitoring]
D --> E[Level 4: Automated Response]
A1[Manual secret cleanup<br/>Post-incident discovery<br/>No automated scanning] --> A
B1[Pre-commit hooks<br/>Basic CI/CD integration<br/>Default rules] --> B
C1[Custom rules<br/>Multiple scan points<br/>Team training] --> C
D1[Real-time monitoring<br/>Comprehensive reporting<br/>Trend analysis] --> D
E1[Auto-remediation<br/>Zero-trust pipeline<br/>ML-enhanced detection] --> E
style A fill:#ff6b6b
style B fill:#ffa726
style C fill:#ffeb3b
style D fill:#8bc34a
style E fill:#4caf50

1. Integrate sớm trong development cycle#

  • Sử dụng pre-commit hooks
  • Thêm vào CI/CD pipeline
  • Train developers về security awareness

2. Cấu hình phù hợp#

  • Tùy chỉnh rules theo nhu cầu dự án
  • Sử dụng allowlists để giảm false positives
  • Thường xuyên cập nhật configuration

3. Monitoring và reporting#

  • Set up alerts cho findings mới
  • Regular security reviews
  • Track metrics về secret detection

4. Incident response#

  • Có plan để handle khi phát hiện secrets
  • Rotate keys/passwords ngay lập tức
  • Audit logs để xem ai đã access

Kết luận#

Gitleaks là một công cụ thiết yếu trong bộ công cụ DevSecOps hiện đại. Với khả năng phát hiện secrets mạnh mẽ, dễ sử dụng và tích hợp linh hoạt, nó giúp teams bảo vệ thông tin nhạy cảm một cách hiệu quả.

Ưu điểm chính:#

  • Mã nguồn mở và miễn phí
  • Performance cao với Go
  • Dễ tích hợp vào existing workflows
  • Cấu hình linh hoạt với TOML
  • Community active với frequent updates
  • Multiple output formats cho reporting
  • Archive scanning cho comprehensive coverage

Bắt đầu bảo vệ mã nguồn của bạn ngay hôm nay với Gitleaks! 🔐

Gitleaks - Công cụ phát hiện secret và thông tin nhạy cảm trong Git
https://githay.com/posts/gitleaks-opensource/
Tác giả
Githay
Đăng vào lúc
2025-01-15
Giấy phép bản quyền
CC BY-NC-SA 4.0