跳轉到

Claude Code 安全防護完整指南

適用情境:使用 Claude Code 處理含有密碼、API key、網路設備憑證等敏感資訊的工作環境。 最後更新:2026-06


核心觀念

❌ 錯誤思路:讓 Claude 看到密碼 → 靠規則叫它不要說出來
✅ 正確思路:讓 Claude 根本看不到密碼(防線往前推)

CLAUDE.md 的安全規則是「最後一道防線」,無法取代根本的 context 隔離。 必須從檔案系統層級開始封鎖。


一次性設定清單

[ ] 1. 在每個常用專案建立 .clodeignore
[ ] 2. 建立 ~/.claude/.clodeignore 作為全域保護
[ ] 3. 建立 ~/.my.cnf 和 ~/.pgpass(如果你有用 MySQL/PostgreSQL)
[ ] 4. 在 ~/.bashrc 加入 mask-secrets alias
[ ] 5. 更新 CLAUDE.md 為完整的安全規則格式
[ ] 6. 用 grep 審計一次工作目錄,把危險檔案加入 ignore

Step 1:在每個常用專案建立 .clodeignore

在專案根目錄建立此檔案,Claude Code 啟動時會自動排除這些路徑,不讀入 context。

cat > .clodeignore << 'EOF'
# Secrets & Credentials
.env
.env.*
.env.local
.env.production
.env.staging
*.secret
*.key
*.pem
*.p12
*.pfx

# Database credential files
.my.cnf
.pgpass
.netrc

# Config files with hardcoded credentials
config/database.yml
config/secrets.yml
config/credentials.yml
docker-compose.override.yml

# Credential directories
credentials/
secrets/
.secrets/
private/

# SSH keys
.ssh/
id_rsa
id_ed25519
*.pub

# Application specific
*.token
auth.json
service-account.json
EOF

Step 2:建立全域 .clodeignore

保護所有專案,不需要每個專案重複設定。

mkdir -p ~/.claude

cat > ~/.claude/.clodeignore << 'EOF'
# Global secret exclusions — applies to all projects
.env
.env.*
*.secret
*.key
*.pem
*.p12
.netrc
.pgpass
.my.cnf
credentials/
secrets/
.ssh/
*.token
auth.json
service-account.json
EOF

驗證方式:在 Claude Code 裡輸入「請列出你能看到的檔案」,確認 .env 不在清單中。


Step 3:建立資料庫 Credential 檔案

避免在指令列明文輸入密碼,改由系統檔案自動讀取。

MySQL:~/.my.cnf

cat > ~/.my.cnf << 'EOF'
[client]
user=your_db_user
password=your_db_password
host=localhost
EOF

chmod 600 ~/.my.cnf

設定後連線方式(不需要 -p 參數):

# 密碼不會出現在指令列
mysql -h localhost mydb
mysqldump mydb > backup.sql

PostgreSQL:~/.pgpass

格式:hostname:port:database:username:password

cat > ~/.pgpass << 'EOF'
localhost:5432:*:your_pg_user:your_pg_password
*:5432:mydb:myuser:mypassword
EOF

chmod 600 ~/.pgpass

設定後連線方式:

# 密碼不會出現在指令列或環境變數
psql -h localhost -U myuser mydb

Step 4:在 ~/.bashrc 加入 mask-secrets alias

貼 log 或 config 內容給 Claude 前,先透過此指令遮罩敏感值。

# 加入 ~/.bashrc 或 ~/.zshrc
cat >> ~/.bashrc << 'EOF'

# === Security: mask sensitive values before sharing ===
alias mask-secrets="sed -E 's/(password|passwd|secret|token|api_key|apikey|Authorization|credential|private_key)([[:space:]]*[:=][[:space:]]*)[^\s\"]*/\1\2[REDACTED]/gi'"

# 延伸版:同時處理 JSON 格式
alias mask-secrets-json="sed -E 's/(\"(password|passwd|secret|token|api_key|apikey|Authorization|credential)\")[[:space:]]*:[[:space:]]*\"[^\"]*\"/\1: \"[REDACTED]\"/gi'"
EOF

source ~/.bashrc

使用方式:

# 遮罩後再貼給 Claude
cat docker-compose.yml | mask-secrets

# 遮罩 JSON 格式
cat config.json | mask-secrets-json

# 多層過濾
cat .env | grep -v "^#" | mask-secrets

Step 5:更新 CLAUDE.md 安全規則

將以下內容加入到 CLAUDE.md最上方

## 🔴 Security — Non-Negotiable Rules (Apply to Entire Session)

### Secret Detection & Redaction
1. If any value matches the following patterns, output `[REDACTED]` instead — no exceptions:
   - `password=`, `passwd=`, `secret=`, `token=`, `api_key=`, `Authorization:`
   - Strings longer than 20 chars that look like hashes, base64, or random keys
   - IP addresses combined with port + credential patterns

2. If asked to read `.env`, `.my.cnf`, `.pgpass`, or any config file:
   - Show **keys/structure only**, never output the values
   - Example: `DB_PASSWORD=[REDACTED]` not `DB_PASSWORD=mysecret`

3. If I paste content containing secrets, redact before referencing back.

### Command Generation Rules
4. When writing curl, mysql, psql, ssh, or any CLI command requiring credentials:
   - Always use `$ENV_VAR` placeholders, never literal values
   - Always add a comment showing which variable to set
   ```bash
   # Set before running: export DB_PASS="your_password"
   mysql -u "$DB_USER" -p"$DB_PASS" -h "$DB_HOST" mydb
   ```

5. Never use `-p<password>` inline syntax for mysql — always use `$VAR` or `~/.my.cnf`.

### Confirmation Gate
6. Before executing any command that appears to contain a credential-looking string:
   - STOP and display the command with values masked
   - Ask me to confirm before proceeding

### File Read Policy
7. Do NOT proactively read, cat, or grep files matching: `.env`, `*.key`, `*.pem`, `*.secret`
8. If a task requires reading such files, ask me explicitly first.

Step 6:審計工作目錄,補充 .clodeignore

執行以下指令找出潛在的危險檔案,逐一加入 .clodeignore

# 找出含有敏感關鍵字的檔案
grep -r -l "password\|secret\|token\|passwd\|api_key" . \
  --include="*.yml" \
  --include="*.yaml" \
  --include="*.env" \
  --include="*.conf" \
  --include="*.ini" \
  --include="*.json" \
  --include="*.toml" \
  2>/dev/null | grep -v ".git"

# 找出可能是 key 或憑證的檔案
find . -name "*.pem" -o -name "*.key" -o -name "*.p12" \
       -o -name "*.secret" -o -name "id_rsa" -o -name "id_ed25519" \
  2>/dev/null | grep -v ".git"

將找到的路徑加入 .clodeignore

# 範例:批次加入
echo "config/app_secrets.yml" >> .clodeignore
echo "deploy/credentials.json" >> .clodeignore

開啟新 Session 的手動 Prompt(建議每次貼入)

遇到需要處理敏感設定的工作時,在對話第一則訊息貼入:

# Security Initialization — Apply for This Entire Session

Before we start, apply these rules permanently for this session:

## Secret Protection
1. Do NOT read, display, or repeat contents of `.env`, `.env.*`, `*.key`, `*.pem`,
   or any file with "secret" / "credential" in its name.
2. If you encounter any value that looks like a password, token, API key,
   or hash (random string >20 chars), output `[REDACTED]` instead.
3. If I accidentally paste content containing secrets,
   redact the sensitive values before referencing them.

## Command Generation
4. When writing curl, mysql, psql, ssh, or any CLI command that needs credentials:
   - Always use `$VARIABLE` placeholders, never literal values.
   - Add a comment showing which env var to set.
   Example: `# export DB_PASS="your_password"` then `mysql -u "$DB_USER" -p"$DB_PASS"`

## File Read Policy
5. For config files (.yml, .yaml, .ini, .conf, .env):
   Show structure and keys only, never output the values.
6. Do not proactively read files matching *.key, *.pem, *.secret, .env without asking me.

## Confirmation Gate
7. Before running any command that appears to contain a credential,
   pause, display the masked version, and ask me to confirm.

---
Acknowledge with: "✅ Security rules applied. Ready to start."
Then we can begin.

指令洩漏情境的逐一解法

curl / wget 含密碼

# ❌ 錯誤
curl -u admin:mysecret123 https://api.example.com/v1/data

# ✅ 正確
export API_USER="admin"
export API_PASS="mysecret123"
curl -u "$API_USER:$API_PASS" https://api.example.com/v1/data

SSH 跳板或自動化腳本

# ❌ 錯誤:密碼在指令裡
sshpass -p 'mysecret' ssh [email protected]

# ✅ 正確:使用 SSH key 或環境變數
export SSH_PASS="mysecret"
sshpass -e ssh [email protected]   # -e 從 SSHPASS 環境變數讀取

FortiGate / DrayTek API 呼叫

# ❌ 錯誤
curl -k "https://192.168.1.1/api/v2/monitor/system/status?access_token=abc123xyz"

# ✅ 正確
export FGT_TOKEN="abc123xyz"
curl -k "https://192.168.1.1/api/v2/monitor/system/status?access_token=$FGT_TOKEN"

本機安全性檢查(發現攻擊後追加)

如果懷疑本機已被監控或入侵,請執行以下確認步驟。

Windows 異常連線檢查

# 列出所有對外 ESTABLISHED 連線
netstat -ano | findstr ESTABLISHED

# 找對應程式名稱(替換 PID)
tasklist /FI "PID eq <PID>"

# 檢查異常的開機自啟動排程
Get-ScheduledTask | Where-Object {$_.State -eq "Ready"} | Select TaskName, TaskPath

WSL2 / Linux 異常連線檢查

# 對外連線總覽
ss -tnp | grep ESTABLISHED

# CPU 佔用前 20 的程式
ps aux | grep -v "^\[" | sort -k3 -rn | head -20

# 最近 24 小時內被修改的系統檔案
find /etc /usr/bin /usr/sbin -newer /tmp -type f 2>/dev/null

本機遭入侵時的應變步驟

1. 暫時不要在這台機器上輸入任何新密碼
2. 從另一台「確認乾淨」的設備更換所有設備密碼
3. 更換後,不要在舊機器上使用新密碼(驗證是否為本機洩漏)
4. 若更換密碼後攻擊停止 → 確認為本機洩漏
5. 若攻擊繼續 → 代表攻擊者有其他管道,需要進一步調查

防護層次總覽

Layer 1:.clodeignore(檔案層級隔離)
  └─ Claude Code 根本看不到 .env 等敏感檔案

Layer 2:~/.my.cnf / ~/.pgpass(指令層級保護)
  └─ 密碼不出現在 CLI 指令或 process list

Layer 3:mask-secrets alias(貼上前遮罩)
  └─ 人工貼入的 log/config 先過濾再給 Claude

Layer 4:CLAUDE.md 安全規則(行為約束)
  └─ 萬一前三層失效,還有一道行為層防線

Layer 5:Session Prompt(高敏感任務強制確認)
  └─ 部署、設備設定等任務時額外加強

重要提醒: 以上五層防護針對的是 Claude Code 的 context 洩漏問題。 若設備在密碼洩漏後迅速被攻擊,且攻擊者會清除 log、隱蔽 IP, 威脅來源很可能是本機已被長期監控的惡意程式,而非 Claude Code 本身。 建議同時進行本機安全性稽核,從另一台乾淨設備更換所有憑證。