Git - Gitleaks로 민감정보 탐지하기

Gitleaks란?

Gitleaks는 Git 저장소에서 비밀번호, API 키, 토큰과 같은 민감한 정보(secrets)를 탐지하는 오픈소스 보안 도구입니다. 코드를 커밋하기 전이나 CI/CD 파이프라인에서 실행하여 실수로 민감정보가 코드 저장소에 포함되는 것을 방지할 수 있습니다.

주요 특징

  • 빠른 스캔: Go 언어로 작성되어 빠른 성능 제공
  • 다양한 탐지 규칙: 100개 이상의 내장 규칙으로 주요 서비스의 비밀정보 탐지
  • 커스터마이징 가능: 사용자 정의 규칙 추가 가능
  • Git 통합: pre-commit hook으로 설정 가능
  • CI/CD 통합: GitHub Actions, GitLab CI 등과 쉽게 통합

설치

macOS (Homebrew)

brew install gitleaks

Linux

# Binary 다운로드
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/

Docker

docker pull zricethezav/gitleaks:latest

기본 사용법

현재 저장소 스캔

# 전체 저장소 히스토리 스캔
gitleaks detect

# 현재 변경사항만 스캔
gitleaks protect

# 특정 디렉토리 스캔
gitleaks detect --source /path/to/repo

결과 출력 형식 지정

# JSON 형식으로 출력
gitleaks detect --report-format json --report-path report.json

# SARIF 형식으로 출력 (GitHub Code Scanning용)
gitleaks detect --report-format sarif --report-path report.sarif

# CSV 형식으로 출력
gitleaks detect --report-format csv --report-path report.csv

설정 파일 (gitleaks.toml)

프로젝트 루트에 .gitleaks.toml 파일을 생성하여 커스터마이징할 수 있습니다.

title = "Gitleaks Configuration"

# 전역 allowlist
[allowlist]
description = "Global Allowlist"
regexes = [
'''219-09-\d{5}''', # 주민등록번호 패턴 예외
]
paths = [
'''node_modules/''',
'''vendor/''',
'''.git/''',
]

# 커스텀 규칙 추가
[[rules]]
id = "custom-api-key"
description = "Custom API Key"
regex = '''(?i)custom[_-]?api[_-]?key[_-]?=\s*['"]?([a-z0-9]{32})['"]?'''
tags = ["api", "key"]

# 엔트로피 기반 탐지
[[rules]]
id = "high-entropy-string"
description = "High Entropy String (possible secret)"
regex = '''[a-zA-Z0-9+/]{40,}'''
entropy = 4.5

특정 파일/라인 제외하기

코드에 직접 주석으로 표시:

// gitleaks:allow
const apiKey = "test-api-key-1234567890";

const password = "secret123"; // gitleaks:allow

Pre-commit Hook 설정

Git hook으로 커밋 전 자동 스캔:

# .git/hooks/pre-commit 파일 생성
cat << 'EOF' > .git/hooks/pre-commit
#!/bin/sh

gitleaks protect --verbose --redact --staged

if [ $? -eq 1 ]; then
echo "Warning: Gitleaks detected sensitive information."
echo "Please remove it before committing."
exit 1
fi
EOF

chmod +x .git/hooks/pre-commit

CI/CD 통합

GitHub Actions

name: Gitleaks
on: [push, pull_request]

jobs:
scan:
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

gitleaks:
image: zricethezav/gitleaks:latest
script:
- gitleaks detect --source . --verbose --redact
only:
- merge_requests
- main

주요 옵션

옵션 설명
detect 전체 저장소 히스토리 스캔
protect staged 변경사항만 스캔 (pre-commit용)
--verbose 상세 출력
--redact 탐지된 비밀정보를 마스킹 처리
--no-git Git 저장소가 아닌 일반 디렉토리 스캔
--config 커스텀 설정 파일 경로 지정
--baseline-path 기준선 파일 지정 (이전 스캔 결과 제외)

탐지 예시

Gitleaks가 탐지할 수 있는 주요 비밀정보:

  • AWS Access Key & Secret Key
  • GitHub Token
  • GitLab Token
  • Slack Token
  • Google API Key
  • Private SSH Keys
  • Database 연결 문자열
  • JWT Tokens
  • OAuth Credentials
  • Stripe API Keys
  • Twilio API Keys

이미 커밋된 비밀정보 제거하기

# 1. 비밀정보가 포함된 파일 찾기
gitleaks detect --verbose

# 2. Git 히스토리에서 파일 제거 (BFG Repo-Cleaner 사용)
brew install bfg
bfg --delete-files secret-file.txt

# 3. 또는 git filter-branch 사용
git filter-branch --force --index-filter \
"git rm --cached --ignore-unmatch path/to/secret-file" \
--prune-empty --tag-name-filter cat -- --all

# 4. 강제 푸시
git push origin --force --all

베스트 프랙티스

  1. Pre-commit Hook 사용: 커밋 전 자동으로 스캔하여 사전 예방
  2. CI/CD 파이프라인 통합: 모든 PR에서 자동 검사
  3. 정기적인 전체 스캔: 주기적으로 전체 저장소 스캔
  4. 환경변수 사용: 민감정보는 .env 파일과 환경변수로 관리
  5. .gitignore 설정: .env, credentials.json 등 민감 파일 제외
  6. 팀 교육: 개발자들에게 보안 의식 고취
Share