🔧
Part 2고급⏱ 약 75분 · 3개 섹션
BashTool 심층 분석
가장 강력하고 가장 위험한 도구

✦이 챕터에서 배울 것
전체 아키텍처에서 현재 위치
⚙️코어 엔진
→🔧도구 시스템
→🛡️보안
→🧠컨텍스트
→🤝멀티 에이전트
→🌐생태계
→⚡인프라
1
BashTool 아키텍처
18개 파일의 구조와 역할
명령 분류보안 레이어진행률 추적|
tools/BashTool/BashTool.tsxtools/BashTool/constants.tsBashTool은 Claude Code에서 가장 복잡한 도구입니다. 18개 파일로 구성되며, 131KB Bash 파서를 포함합니다. 이 복잡성은 셸 명령 실행의 보안 위험 때문입니다.
BashTool 디렉토리 구조
1// src/tools/BashTool/ — 18개 파일 구조2 3BashTool/4├── BashTool.tsx # 메인 도구 구현 (실행 로직)5├── bashPermissions.ts # 도구별 권한 로직6├── bashSecurity.ts # 보안 패턴 검증7├── readOnlyValidation.ts # 읽기 전용 모드 검증8├── sedEditParser.ts # sed 편집 명령 파싱9├── shouldUseSandbox.ts # 샌드박스 사용 여부 결정10├── commandSemantics.ts # 명령 의미 해석11├── prompt.ts # 모델용 도구 설명12├── UI.tsx # 렌더링 컴포넌트13├── constants.ts # 상수 정의14├── toolName.ts # 도구 이름 상수15├── utils.ts # 유틸리티 함수16│17└── 의존하는 파서 모듈 (src/utils/bash/):💡18 ├── bashParser.ts # [131KB] 완전한 Bash 파서💡19 ├── ast.ts # [112KB] 추상 구문 트리 정의💡20 ├── commands.ts # [51KB] 명령 분석/조작21 └── heredoc.ts # [31KB] Heredoc 처리src/tools/BashTool/BashTool.tsx:54-82
1// src/tools/BashTool/BashTool.tsx — 명령 분류 시스템2 3// 검색 명령 (축소 표시)4const BASH_SEARCH_COMMANDS = new Set([💡5 'find', 'grep', 'rg', 'ag', 'ack', 'locate', 'which', 'whereis'6])7 8// 읽기/분석 명령 (축소 표시)9const BASH_READ_COMMANDS = new Set([10 'cat', 'head', 'tail', 'less', 'more',11 'wc', 'stat', 'file', 'strings', // 분석💡12 'jq', 'awk', 'cut', 'sort', 'uniq', 'tr' // 데이터 처리13])14 15// 디렉토리 목록 명령16const BASH_LIST_COMMANDS = new Set(['ls', 'tree', 'du'])17 18// 의미 중립 명령 (파이프라인에서 무시)19const BASH_SEMANTIC_NEUTRAL_COMMANDS = new Set([💡20 'echo', 'printf', 'true', 'false', ':'21])22 23// 진행률 표시 임계값24const PROGRESS_THRESHOLD_MS = 2000 // 2초 후 진행률 표시2
Bash 파서와 AST
131KB 파서가 생성하는 추상 구문 트리
토큰화AST 노드파이프라인리다이렉션서브셸|
utils/bash/bashParser.tsutils/bash/ast.ts131KB Bash 파서는 완전한 추상 구문 트리(AST)를 생성합니다. 정규식 기반 분석이 아닌 AST 기반이므로, 파이프라인, 서브셸, 리다이렉션 등 복잡한 구문도 정확히 분석합니다.
src/utils/bash/ast.ts — Bash AST 구조
1// src/utils/bash/ast.ts — AST 노드 타입 (112KB 중 핵심)2 3// 파이프라인: cmd1 | cmd2 | cmd34type Pipeline = {💡5 type: 'pipeline'6 commands: Command[]7 negated: boolean // ! prefix8}9 10// 명령 목록: cmd1 && cmd2 || cmd311type CommandList = {12 type: 'list'13 entries: { operator: '&&' | '||' | ';' | '&', command: Command }[]14}15 16// 단순 명령: git commit -m "msg"17type SimpleCommand = {💡18 type: 'simple'19 name: Word20 args: Word[]21 redirections: Redirection[]22 assignments: Assignment[] // VAR=value prefix23}24 25// 리다이렉션: > file, >> file, 2>&126type Redirection = {27 type: 'redirection'💡28 operator: '>' | '>>' | '<' | '2>' | '2>&1' | '&>' | ...29 target: Word30}31 32// 서브셸: ( cmd1; cmd2 )33type Subshell = { type: 'subshell', body: CompoundList }34 35// 명령 치환: $(cmd) 또는 `cmd`36type CommandSubstitution = { type: 'command_sub', body: CompoundList }37 38// ─── parseForSecurity() 진입점 ───💡39import { parseForSecurity } from './ast.js'40 41const result = parseForSecurity('git status && rm -rf /tmp')42// result.commands = [43// { type: 'simple', name: 'git', args: ['status'] },44// { type: 'simple', name: 'rm', args: ['-rf', '/tmp'] }45// ]46// → 'rm -rf' 감지 가능!3
Bash 보안 검증
위험 패턴 감지와 읽기 전용 검증
위험 패턴AST 기반 분석읽기 전용 모드명령 주입 방지|
tools/BashTool/bashSecurity.tsutils/bash/readOnlyCommandValidation.tsBash 보안 검증은 AST 기반 분석으로 위험한 명령을 감지합니다. 정규식이 아닌 구문 분석이므로, echo "rm -rf /"(문자열 내 rm)와 실제 rm -rf /를 구분할 수 있습니다.
Bash 보안 검증 흐름
1// 보안 검증 흐름 (BashTool → bashSecurity → AST)2 💡3// 1. 명령 파싱 → AST 생성4const ast = parseForSecurity(command)5 6// 2. AST에서 실제 실행되는 명령 추출7const executedCommands = extractCommands(ast)💡8 9// 3. 각 명령에 대해 위험 패턴 확인10for (const cmd of executedCommands) {11 // rm -rf 감지12 if (cmd.name === 'rm' && cmd.args.includes('-rf')) {💡13 return { dangerous: true, reason: 'rm -rf detected' }14 }15 16 // 리다이렉션으로 파일 덮어쓰기 감지17 for (const redir of cmd.redirections) {💡18 if (redir.operator === '>' || redir.operator === '>>') {19 // 읽기 전용 모드에서 파일 쓰기 시도20 if (isReadOnlyMode) {21 return { dangerous: true, reason: 'write in read-only mode' }22 }23 }24 }25 26 // curl | sh 패턴 감지 (원격 코드 실행)💡27 if (isPipedToShell(cmd, pipeline)) {28 return { dangerous: true, reason: 'piped to shell execution' }29 }30}31 32// 4. 읽기 전용 모드 검증 (68KB, readOnlyCommandValidation.ts)33// - 글로브 패턴 확장 분석34// - 출력 리다이렉션 추출35// - 환경 변수 할당 감지💡 왜 정규식이 아닌 AST인가
echo "rm -rf /"는 실제로 파일을 삭제하지 않지만, 정규식 기반 분석은 이를 위험한 명령으로 오탐합니다. AST 기반 분석은 "rm"이 SimpleCommand의 name 위치에 있는지, 아니면 Word(문자열) 내부에 있는지를 구분합니다. 이것이 131KB 파서가 존재하는 이유입니다.
?
이해도 확인 퀴즈
echo "rm -rf /" 명령에 대해 AST 기반 분석과 정규식 기반 분석은 각각 어떻게 판단할까요?
✅ 학습 체크리스트
이해한 항목을 체크하고 학습 진도를 확인하세요
0/4 완료0%
📋 BashTool 심층 분석 요약
이 챕터에서 배운 핵심 개념을 정리합니다
1
가장 복잡한 도구
18개 파일, 131KB 파서 포함. 셸 명령의 보안 위험 때문에 이 복잡성이 필요합니다.
2
명령 분류 시스템
search/read/list/neutral로 명령을 분류하여 UI 표시를 최적화합니다.
3
AST 기반 보안
정규식이 아닌 완전한 AST로 파이프라인, 서브셸, 리다이렉션을 정확히 분석합니다.
4
fail-closed 원칙
확인할 수 없으면 위험하다고 가정합니다. 안전 우선의 보안 철학입니다.
다음 챕터 미리보기: 다음은 이 보안 분석 결과를 사용하는 '다계층 권한 시스템'을 학습합니다.