보안은 절대 타협하면 안 돼요. Rules 시스템 적극 활용하세요.
CLAUDE.md에 "API 키 절대 하드코딩 금지, 환경 변수 무조건 사용" 이렇게 박아두면 Claude Code가 지켜줘요.
Security Reviewer Agent도 돌려보세요. SQL 인젝션, XSS, CSRF 같은 취약점 자동으로 찾아내요. 배포 전에 꼭 한 번 체크하는 습관 들이세요.
TL;DR
- 기본 원칙: Claude를 "똑똑하지만 신뢰할 수 없는 인턴"으로 대하기
- Permission 시스템: allow/deny/ask 규칙으로 세밀하게 제어
- Sandbox: /sandbox로 파일시스템 + 네트워크 격리 (84% 권한 요청 감소)
- 민감 파일 차단: .env, ~/.ssh/, ~/.aws/ 접근 deny
- CLAUDE.md: 보안 규칙 명시 (API 키 하드코딩 금지 등)
- PreToolUse Hooks: 가장 강력한 보안 경계 (파일/명령 차단)
- Trail of Bits Skills: 전문 보안 감사 도구 활용
- 절대 root로 실행 금지
핵심 보안 철학
Claude = "똑똑하지만 신뢰할 수 없는 인턴"
"Organizations must treat Claude Code as a 'brilliant but untrusted intern'—capable of excellent work but requiring human review of all security-critical changes." — MintMCP Blog
Claude Code는 강력하지만, 다음을 기억하세요:
Claude가 할 수 있는 것 위험
| .env 파일 읽기 | API 키 노출 |
| SSH 키 접근 | 서버 침투 |
| bash 명령 실행 | 시스템 손상 |
| 네트워크 요청 | 데이터 유출 |
| MCP 서버 연결 | 외부 서비스 접근 |
Zero Trust 원칙
"To enhance security, treat Claude Code as an assistant requiring supervision. Implement external SAST/DAST tools, run it in sandboxed environments, and establish strict, 'deny-by-default' configurations for permissions." — eesel.ai
기본 = 거부, 필요한 것만 허용하세요.
1. Permission 시스템 설정
공식 Permission 구조
"Claude Code uses strict read-only permissions by default. When additional actions are needed (editing files, running tests, executing commands), Claude Code requests explicit permission." — Anthropic Security Docs
3가지 규칙 타입
{
"permissions": {
"allow": [...], // 자동 승인 (안전한 작업)
"ask": [...], // 매번 확인
"deny": [...] // 완전 차단 (deny가 allow보다 우선)
}
}
실전 보안 설정
// .claude/settings.json
{
"permissions": {
"allow": [
"Bash(npm run:*)",
"Bash(npm test:*)",
"Bash(git status)",
"Bash(git diff:*)",
"Bash(git log:*)",
"Bash(ls:*)",
"Bash(cat:*)",
"Bash(head:*)",
"Bash(tail:*)"
],
"ask": [
"Bash(git push:*)",
"Bash(git merge:*)",
"Bash(npm install:*)",
"Bash(npm publish:*)"
],
"deny": [
"Read(./.env)",
"Read(./.env.*)",
"Read(./secrets/**)",
"Read(./**/*credential*)",
"Read(./**/*secret*)",
"Read(~/.ssh/**)",
"Read(~/.aws/**)",
"Bash(rm -rf:*)",
"Bash(sudo:*)",
"Bash(chmod 777:*)",
"Bash(curl:*)",
"Bash(wget:*)",
"WebFetch"
]
}
}
⚠️ 중요: Bash deny 규칙의 한계
"Bash permission rules use pattern matching and can be bypassed using shell features like command flags, variables, or redirects. For example, Bash(curl:*) can be bypassed with curl -X GET reordered to curl http://example.com -X GET. Do not rely on Bash deny rules as a security boundary." — Claude Code Settings Docs
해결책: PreToolUse Hooks 또는 Sandbox 사용
2. Sandbox: 진정한 격리
Sandbox란?
"In our internal usage, we've found that sandboxing safely reduces permission prompts by 84%. By defining set boundaries within which Claude can work freely, they increase security and agency." — Anthropic Engineering
2중 격리 시스템
"Effective sandboxing requires both filesystem and network isolation. Without network isolation, a compromised agent could exfiltrate sensitive files like SSH keys. Without filesystem isolation, a compromised agent could backdoor system resources to gain network access." — Claude Code Sandboxing Docs
┌─────────────────────────────────────────────────────────────┐
│ Sandbox Architecture │
│ │
│ ┌─────────────────┐ ┌─────────────────┐ │
│ │ Filesystem │ │ Network │ │
│ │ Isolation │ │ Isolation │ │
│ │ │ │ │ │
│ │ • CWD만 쓰기 │ │ • 기본 전체 차단 │ │
│ │ • 상위 폴더 X │ │ • 허용 도메인만 │ │
│ │ • ~/.ssh 차단 │ │ • 프록시 경유 │ │
│ └─────────────────┘ └─────────────────┘ │
│ │
│ OS-Level Enforcement: │
│ • Linux: Bubblewrap + seccomp BPF │
│ • macOS: Seatbelt (sandbox-exec) │
└─────────────────────────────────────────────────────────────┘
Sandbox 활성화
# Claude Code 내에서
/sandbox
Sandbox 설정
{
"sandbox": {
"enabled": true,
"autoAllowBashIfSandboxed": true,
"allowedDirectories": [
"${workspaceFolder}",
"~/.npm",
"/tmp"
],
"deniedDirectories": [
"~/.ssh",
"~/.aws",
"~/.config",
"/etc",
"/var"
],
"allowedDomains": [
"registry.npmjs.org",
"api.github.com"
]
}
}
High Security 템플릿 (신뢰할 수 없는 코드용)
{
"sandbox": {
"enabled": true,
"allowedDirectories": [
"${workspaceFolder}/sandbox-only"
],
"deniedDirectories": [
"~/.ssh",
"~/.aws",
"~/.config",
"/etc",
"/var",
"/usr",
"/System"
],
"allowedDomains": []
}
}
Prompt Injection 방어
"Sandboxing ensures that even a successful prompt injection is fully isolated, and cannot impact overall user security. This way, a compromised Claude Code can't steal your SSH keys, or phone home to an attacker's server." — Anthropic Engineering
3. PreToolUse Hooks: 가장 강력한 방어선
Hooks가 필요한 이유
"Until the core deny functionality is fixed, the only reliable way to protect sensitive files is by using a PreToolUse hook." — GitHub Issue #6699
Permission deny 규칙에 버그가 있을 수 있어요. Hooks는 OS 레벨에서 차단하므로 더 안전합니다.
민감 파일 보호 Hook
#!/usr/bin/env python3
# .claude/hooks/protect_sensitive_files.py
import sys
import json
from pathlib import Path
# 민감한 파일 패턴
SENSITIVE_PATTERNS = [
'.env',
'.env.*',
'*.pem',
'*.key',
'*credential*',
'*secret*',
'id_rsa',
'id_ed25519',
'.aws/credentials',
'.ssh/config',
]
def is_sensitive(filepath: str) -> bool:
path = Path(filepath)
for pattern in SENSITIVE_PATTERNS:
if path.match(pattern):
return True
return False
def main():
# Hook input 읽기
input_data = json.loads(sys.stdin.read())
tool_name = input_data.get('tool_name', '')
tool_input = input_data.get('tool_input', {})
# Read/Edit 도구 체크
if tool_name in ['Read', 'Edit', 'Write']:
file_path = tool_input.get('file_path', '')
if is_sensitive(file_path):
print(f"BLOCKED: Access to sensitive file '{file_path}' is denied.",
file=sys.stderr)
sys.exit(2) # exit(2) = 차단
sys.exit(0) # exit(0) = 허용
if __name__ == '__main__':
main()
Hook 등록
// .claude/settings.json
{
"hooks": {
"PreToolUse": [
{
"matcher": "Read|Edit|Write",
"command": "python3 .claude/hooks/protect_sensitive_files.py"
}
]
}
}
위험 명령 차단 Hook
#!/bin/bash
# .claude/hooks/block_dangerous_commands.sh
# stdin에서 JSON 읽기
INPUT=$(cat)
TOOL_NAME=$(echo "$INPUT" | jq -r '.tool_name')
COMMAND=$(echo "$INPUT" | jq -r '.tool_input.command // ""')
if [ "$TOOL_NAME" = "Bash" ]; then
# 위험한 패턴 체크
DANGEROUS_PATTERNS=(
"rm -rf"
"chmod 777"
"curl.*|.*sh"
"wget.*|.*sh"
"> /etc/"
"sudo"
"dd if="
)
for pattern in "${DANGEROUS_PATTERNS[@]}"; do
if echo "$COMMAND" | grep -qE "$pattern"; then
echo "BLOCKED: Dangerous command pattern detected: $pattern" >&2
exit 2
fi
done
fi
exit 0
4. CLAUDE.md 보안 규칙
보안 가이드라인 템플릿
# Security Rules
## 절대 금지 사항
- **API 키, 시크릿 하드코딩 금지** - 반드시 환경 변수 사용
- **민감 파일 접근 금지**: .env, ~/.ssh/, ~/.aws/, secrets/
- **위험한 명령 실행 금지**: rm -rf, sudo, chmod 777
- **외부 URL에서 스크립트 다운로드 후 실행 금지**
## 필수 보안 패턴
- 모든 시크릿은 환경 변수로 관리: `process.env.API_KEY`
- 사용자 입력은 항상 검증 및 새니타이즈
- SQL 쿼리는 파라미터화된 쿼리 사용 (절대 문자열 연결 X)
- 파일 경로는 항상 path.join() 사용 (path traversal 방지)
## 코드 리뷰 체크리스트
배포 전 반드시 확인:
- [ ] 하드코딩된 시크릿 없음
- [ ] SQL 인젝션 취약점 없음
- [ ] XSS 취약점 없음
- [ ] CSRF 보호 적용
- [ ] 입력 검증 완료
- [ ] 에러 메시지에 민감 정보 노출 없음
## 환경 변수 패턴
```bash
# ✅ 올바른 방법
DATABASE_URL=postgres://... # .env 파일
const url = process.env.DATABASE_URL;
# ❌ 절대 금지
const url = "postgres://user:password@host/db";
의존성 보안
- 새 패키지 설치 전 npm audit 실행
- 알려진 취약점 있는 패키지 사용 금지
- 버전 고정으로 supply chain 공격 방지
### Security Reviewer Agent 설정
```markdown
<!-- .claude/agents/security-reviewer.md -->
---
name: security-reviewer
description: 보안 취약점 자동 검사
trigger: /security-review, 배포 전, PR 리뷰
---
# Security Reviewer Agent
## 검사 항목
### 1. 인젝션 취약점
- SQL Injection: 문자열 연결 쿼리 탐지
- Command Injection: 사용자 입력이 exec/spawn에 전달되는지
- NoSQL Injection: MongoDB 쿼리 검사
- XPath/LDAP Injection
### 2. 인증/인가 취약점
- 하드코딩된 credentials
- 약한 비밀번호 정책
- 세션 관리 문제
- 권한 상승 가능성
### 3. 데이터 노출
- 민감 정보 로깅
- 에러 메시지 정보 노출
- 안전하지 않은 직렬화
### 4. 설정 문제
- CORS 설정
- 보안 헤더 누락 (CSP, HSTS 등)
- 디버그 모드 활성화
### 5. 의존성 취약점
- npm audit / pip audit 실행
- 알려진 CVE 확인
## 출력 형식
- 심각도: Critical / High / Medium / Low
- 위치: 파일:라인
- 설명: 취약점 상세
- 수정 방안: 구체적인 해결책
5. Trail of Bits Security Skills
전문 보안 도구 활용
"Trail of Bits Claude Code skills for security research, vulnerability detection, and audit workflows." — Trail of Bits Skills
설치
/plugins marketplace add trailofbits/skills
주요 Skills
Skill 용도
| static-analysis | CodeQL, Semgrep으로 정적 분석 |
| variant-analysis | 유사 취약점 패턴 탐지 |
| fix-review | 수정 커밋이 버그 재발 없이 문제 해결하는지 검증 |
| audit-context-building | 코드 심층 분석 및 보안 컨텍스트 구축 |
| differential-review | Git 변경사항 보안 중심 리뷰 |
| semgrep-rule-creator | 커스텀 Semgrep 규칙 생성 |
| footgun-identifier | 에러 유발 API 및 위험한 설정 탐지 |
사용 예시
# 정적 분석 실행
/static-analysis
# 수정 커밋 검증
/fix-review main fix-branch --report ./audit-report.pdf
# 유사 취약점 탐지
/variant-analysis "SQL injection pattern"
스마트 컨트랙트 보안 (Building Secure Contracts)
# 블록체인별 취약점 스캐너
/solana-vulnerability-scanner
/cosmos-vulnerability-scanner
# 개발 가이드라인
/audit-prep-assistant
/code-maturity-assessor
/secure-workflow-guide
6. 민감 데이터 보호
Anthropic 내부 팀 권장사항
"They recommend using MCP servers rather than the BigQuery CLI to maintain better security control over what Claude Code can access, especially for handling sensitive data that requires logging or has potential privacy concerns." — How Anthropic teams use Claude Code
민감 데이터 가이드라인
┌─────────────────────────────────────────────────────────────┐
│ 민감 데이터 보호 전략 │
│ │
│ 절대 포함하지 말 것: │
│ • Production API 키 │
│ • 데이터베이스 credentials │
│ • 고객 PII (개인식별정보) │
│ • 결제 정보 (카드번호 등) │
│ • 독점 알고리즘 (핵심 비즈니스 로직) │
│ │
│ 대안: │
│ • 환경 변수 사용 │
│ • Secrets Manager (AWS, Vault 등) │
│ • Mock 데이터로 개발 │
│ • 민감 정보 마스킹 │
└─────────────────────────────────────────────────────────────┘
데이터 전송 인식
"When you interact with Claude Code, specific types of data are transmitted to Anthropic's servers for processing. Files that Claude Code reads are sent in their entirety for analysis." — ClaudeLog
기억하세요: Claude가 읽는 모든 파일은 Anthropic 서버로 전송됩니다.
7. 엔터프라이즈 보안 설정
managed-settings.json (조직 전체 정책)
// /etc/claude/managed-settings.json (관리자 권한 필요)
{
"permissions": {
"deny": [
"Read(./secrets/**)",
"Read(./**/.env*)",
"Read(~/.ssh/**)",
"Read(~/.aws/**)",
"Bash(curl:*)",
"Bash(wget:*)",
"WebFetch"
]
},
"sandbox": {
"enabled": true,
"allowedDomains": [
"*.company-internal.com",
"registry.npmjs.org"
]
}
}
"Enterprise Policy (highest priority) — These rules cannot be overridden by users." — Permissions and Security
Settings 우선순위
Managed (최우선) → Project → User (최하위)
↓ ↓ ↓
조직 정책 프로젝트용 개인 설정
(강제 적용) (.claude/) (~/.claude/)
GDPR/규제 대응
- Data Residency: AWS EU 리전 또는 Vertex AI 사용
- Zero Data Retention: Enterprise API 고객용 옵션
- Audit Logging: 90일 이상 로그 보관
- Data Minimization: deny 규칙으로 PII 파일 접근 차단
8. 실전 보안 체크리스트
매일 확인
- [ ] Claude Code 최신 버전 사용 중 (/status 확인)
- [ ] .env 파일이 .gitignore에 포함
- [ ] 하드코딩된 시크릿 없음
프로젝트 시작 시
- [ ] CLAUDE.md에 보안 규칙 명시
- [ ] .claude/settings.json에 deny 규칙 설정
- [ ] /sandbox 활성화
- [ ] PreToolUse Hooks 설정
배포 전
- [ ] /security-review 또는 Security Agent 실행
- [ ] npm audit / pip audit 실행
- [ ] 의존성 취약점 확인
- [ ] 환경 변수 설정 검증
- [ ] CORS, CSP 등 보안 헤더 확인
위험 신호
- [ ] Claude가 .env 읽으려 함 → 즉시 거부
- [ ] 알 수 없는 URL로 네트워크 요청 → 확인 후 결정
- [ ] sudo 또는 chmod 777 요청 → 절대 거부
- [ ] 알 수 없는 npm 패키지 설치 → 조사 후 결정
9. CVE 및 알려진 취약점
주요 CVE 히스토리
"So far there have been 9 CVE's published for claude code, many of which allowed for bypasses of permissions dialogs." — Pete Freitag
버전 취약점 날짜
| ≤1.0.119 | Symlink bypass in permission deny rules | 2025-10-03 |
| <1.0.105 | Confirm Prompt Bypass | 2025-09-10 |
교훈:
- 항상 최신 버전 유지
- Permission 시스템만 의존하지 말고 Sandbox + Hooks 사용
- 정기적으로 보안 공지 확인
10. 안전한 YOLO 모드
절대 일반 개발에서 사용 금지
# ⚠️ 위험: 모든 권한 체크 우회
claude --dangerously-skip-permissions
안전하게 사용하려면
"This flag should only be used for well-defined, automated tasks running in a secure, isolated environment like a Docker container." — eesel.ai
# Dockerfile - 격리된 환경에서만 YOLO 모드
FROM node:20-alpine
# 비-root 사용자 생성
RUN adduser -D claude-user
# 작업 디렉토리만 접근 가능
WORKDIR /workspace
RUN chown claude-user:claude-user /workspace
USER claude-user
# Claude Code 설치
RUN npm install -g @anthropic-ai/claude-code
CMD ["claude", "--dangerously-skip-permissions"]
마무리
보안은 선택이 아니라 필수입니다.
"The key takeaway: Treat Claude like you would an untrusted but powerful intern. Give it only the minimum permissions it actually needs, sandbox it, and audit it." — Backslash Security
핵심 원칙:
- 최소 권한: 필요한 것만 허용
- 다층 방어: Permission + Sandbox + Hooks
- 명시적 규칙: CLAUDE.md에 보안 정책 문서화
- 정기 감사: Trail of Bits Skills 등 활용
- 최신 유지: 보안 패치 즉시 적용
- root 절대 금지: AI 에이전트에 관리자 권한 주지 않기
Claude Code는 강력한 도구예요. 하지만 제대로 설정하지 않으면 보안 위협이 될 수 있어요. 이 가이드의 설정을 적용하면, 생산성은 유지하면서 안전하게 AI 코딩을 즐길 수 있습니다.
참고 자료
Anthropic 공식
- Security - Claude Code Docs
- Sandboxing - Claude Code Docs
- Making Claude Code More Secure
- Claude Code Settings
보안 도구
- Trail of Bits Skills — 전문 보안 감사 Skills
- Anthropic sandbox-runtime — 오픈소스 샌드박스
커뮤니티 가이드
- Claude Code Permissions Deep Dive
- Backslash Security Best Practices
- MintMCP Enterprise Security
- Permissions and Security
'Programmer > AI' 카테고리의 다른 글
| Claude Code에서 MCP vs Skills vs CLI - 무엇을 선택해야 할까? (1) | 2026.01.21 |
|---|---|
| Claude Code 생산성 10배 올리기: 키보드부터 자동화까지 (0) | 2026.01.21 |
| Claude Code TDD 워크플로우: RED-GREEN-REFACTOR로 버그 없는 코드 만들기 (1) | 2026.01.21 |
| Claude Code Extended Thinking: 깊은 사고로 퀄리티 높이기 (1) | 2026.01.21 |
| Claude Code 컨테이너 격리와 병렬 개발: devcontainer & git worktree (0) | 2026.01.21 |