// 설명 문서: docs/specs/host-command-guard.md (v1.0.0) // Bash AST의 모든 실행 노드를 검사한다. 스크립트/인터프리터의 실제 효과는 OS 격리가 담당한다. const path = require('node:path'); const os = require('node:os'); const { parseShell, failure } = require('./host-shell-parser'); const DENIED = new Set(('sudo su doas pkexec launchctl systemctl service sc sc.exe kill killall pkill taskkill taskkill.exe csrutil spctl setenforce modprobe rmmod security ' + 'ifconfig ip route networksetup scutil nmcli pfctl iptables ip6tables nft ufw netsh netsh.exe openvpn wg wg-quick tailscale ngrok cloudflared socat proxychains proxychains4 ' + 'ssh scp sftp sshpass expect telnet ftp nc ncat netcat kubectl helm terraform ansible ansible-playbook').split(' ')); const INDIRECT = new Set(['eval', 'source', '.', 'exec', 'xargs', 'parallel', 'nohup', 'setsid', 'chroot', 'nsenter', 'unshare', 'alias', 'unalias', 'hash', 'enable']); const SHELLS = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']); const OPAQUE = /^(?:node|bun|deno|python(?:\d+(?:\.\d+)?)?|ruby|perl|php|lua)$/; const PROTECTED = ['.ssh', '.aws', '.gnupg', '.docker', '.kube', 'Library/Keychains', '.netrc', '.npmrc', '.pgpass', '.my.cnf', '.git-credentials', '.zshrc', '.bashrc', '.profile', 'Library/LaunchAgents']; const CONTAINERS = new Set(['Script', 'Pipeline', 'LogicalExpression', 'CompoundList', 'Subshell', 'If', 'While', 'Until', 'For', 'Case', 'CaseItem']); const MUTATING = new Set(['tee', 'sed', 'perl', 'cp', 'mv', 'install', 'dd', 'truncate', 'touch', 'chmod', 'chown', 'chgrp', 'ln', 'rm']); function blocked() { return Object.assign(new Error('호스트·사내 보안 정책에서 허용하지 않는 실행입니다.'), { code: 'HOST_COMMAND_BLOCKED' }); } function literal(word) { if (!word || word.type !== 'Word' || word.expansion?.length || typeof word.text !== 'string') throw failure(); return word.text; } function executable(word) { const text = literal(word); if (!text || Array.from('$`*?[]{}\\').some(character => text.includes(character))) throw failure(); return path.posix.basename(text).toLowerCase(); } function protectedPath(text, cwd, home, writing = false) { if (typeof text !== 'string') return false; const value = text.startsWith('~/') ? path.join(home, text.slice(2)) : path.resolve(cwd, text); const roots = PROTECTED.map(item => path.join(home, item)); if (writing) roots.push('/etc', '/private/etc', '/System', '/Library', '/usr', '/bin', '/sbin', '/proc/sys', '/sys'); return roots.some(root => value === root || value.startsWith(root + path.sep)); } async function checkHostCommand(source, { platform = process.platform, cwd = process.cwd(), home = os.homedir(), requireContainment = false } = {}) { if (platform === 'win32') throw failure('HOST_COMMAND_PLATFORM_UNSUPPORTED'); if (!['darwin', 'linux', 'freebsd'].includes(platform)) throw failure('HOST_COMMAND_PLATFORM_UNSUPPORTED'); let visited = 0, opaque = false; const inspectCommand = async (nameWord, words, depth) => { const name = executable(nameWord); if (DENIED.has(name)) throw blocked(); if (INDIRECT.has(name) || ['powershell', 'powershell.exe', 'pwsh', 'cmd', 'cmd.exe'].includes(name)) throw failure(); if (depth > 32) throw failure(); if (['env', 'command', 'builtin', 'time', 'nice', 'timeout', 'busybox', 'toybox'].includes(name)) { const args = words.map(literal); let i = 0; if (name === 'env') { if (args.some(arg => /^(?:PATH|BASH_ENV|ENV|SHELLOPTS|BASHOPTS|LD_[A-Z_]+|DYLD_[A-Z_]+)=/.test(arg))) throw failure(); while (i < args.length && (/^[A-Za-z_][A-Za-z0-9_]*=/.test(args[i]) || ['-i', '--ignore-environment', '--'].includes(args[i]))) i++; } else if (['command', 'builtin', 'time'].includes(name)) { while (i < args.length && ['-p', '--'].includes(args[i])) i++; } else if (name === 'nice') { if (args[i] === '-n' && /^-?\d+$/.test(args[i + 1] || '')) i += 2; } else if (name === 'timeout' && /^\d+(?:\.\d+)?[smhd]?$/.test(args[i] || '')) i++; if (!words[i] || args[i].startsWith('-')) throw failure(); return inspectCommand(words[i], words.slice(i + 1), depth + 1); } if (SHELLS.has(name)) { const args = words.map(literal); let i = 0; while (i < args.length && ['--noprofile', '--norc', '-l'].includes(args[i])) i++; if (/^-[a-z]*c[a-z]*$/.test(args[i] || '')) { if (typeof args[i + 1] !== 'string') throw failure(); return walk(await parseShell(args[i + 1]), depth + 1); } if (!args[i] || args[i].startsWith('-')) throw failure(); // 저장된 스크립트는 Bash AST만으로 내용을 보장하지 않는다. opaque = true; } if (name === 'find' && words.some(word => ['-exec', '-execdir', '-ok', '-okdir'].includes(word.text))) throw failure(); if (['mysql', 'psql', 'redis-cli', 'mongosh', 'mongo'].includes(name)) { const args = words.map(literal); if (args.some(arg => /^-h|^--host(?:=|$)|^--uri(?:=|$)|^[a-z][a-z0-9+.-]*:\/\//i.test(arg))) throw blocked(); } for (const word of words) { if (protectedPath(word.text, cwd, home, MUTATING.has(name))) throw blocked(); } if (OPAQUE.test(name)) opaque = true; }; const walk = async (node, depth = 0) => { if (!node || typeof node !== 'object') return; if (++visited > 2048 || depth > 32) throw failure(); if (Array.isArray(node)) { for (const child of node) await walk(child, depth + 1); return; } if (node.type === 'Command') { if (node.name) await inspectCommand(node.name, (node.suffix || []).filter(item => item.type === 'Word'), depth); await walk(node.prefix || [], depth + 1); await walk(node.suffix || [], depth + 1); return; } if (node.type === 'Redirect') { const target = literal(node.file); if (protectedPath(target, cwd, home, node.op?.text !== '<')) throw blocked(); return; } if (node.type === 'CommandExpansion') { if (!node.commandAST) throw failure(); await walk(node.commandAST, depth + 1); return; } if (node.type === 'ArithmeticExpansion' || node.type === 'Function') throw failure(); if (node.type === 'Word' || node.type === 'AssignmentWord') { if (node.type === 'AssignmentWord' && /^(?:PATH|BASH_ENV|ENV|SHELLOPTS|BASHOPTS|LD_[A-Z_]+|DYLD_[A-Z_]+)=/.test(node.text || '')) throw failure(); await walk(node.expansion || [], depth + 1); return; } if (node.type === 'ParameterExpansion') { if (!/^(?:[A-Za-z_][A-Za-z0-9_]*|[0-9]+|[@*?#$!_-])$/.test(node.parameter || '')) throw failure(); // 기본값/대체값 안에도 명령 치환이 올 수 있으므로 단순 변수 노드로 건너뛰지 않는다. for (const [key, child] of Object.entries(node)) if (key !== 'loc' && typeof child === 'object') await walk(child, depth + 1); return; } if (!CONTAINERS.has(node.type)) throw failure(); for (const [key, child] of Object.entries(node)) if (key !== 'loc' && typeof child === 'object') await walk(child, depth + 1); }; await walk(await parseShell(source)); if (opaque && requireContainment) throw failure('HOST_COMMAND_REQUIRES_CONTAINMENT'); return { allowed: true, language: 'bash', opaqueExecution: opaque, kernelIsolationVerified: false }; } module.exports = { checkHostCommand };