fix(security): harden worker approval, hook traversal, MCP exec, install scripts, git hooks

- orchestrate-codex-worker: drop yolo, default never approval, worktree containment
- run-with-flags-shell: add path traversal containment mirroring JS guard
- mcp-health-check: gate workspace probe, denylist dangerous env, shell-free reconnect with opt-in
- install.sh/ps1: add --ignore-scripts to block postinstall RCE
- git hooks: refuse global hooksPath clobber, remove file disable bypass, gate pre-push repo script execution
- claw.js: remove Windows shell:true, validate model token
- tests: opt into new secure defaults, quote-aware reconnect parsing
This commit is contained in:
Geronimo
2026-09-14 13:24:58 +05:30
parent 8321021c54
commit 27667bc746
10 changed files with 231 additions and 32 deletions
+105 -3
View File
@@ -182,6 +182,12 @@ function extractMcpTargetFromRaw(raw) {
}
function resolveServerConfig(serverName) {
// SECURITY: serverName flows into env-var lookup and shell-adjacent paths.
// Reject anything outside a strict token so config-controlled names cannot
// inject shell metachars ($(..), backticks, ;) downstream.
if (!/^[A-Za-z0-9_-]{1,64}$/.test(String(serverName || ''))) {
return null;
}
for (const filePath of configPaths()) {
const data = readJsonFile(filePath);
const server = data?.mcpServers?.[serverName]
@@ -306,9 +312,21 @@ function probeCommandServer(serverName, config) {
const command = config.command;
const args = Array.isArray(config.args) ? config.args.map(arg => String(arg)) : [];
const timeoutMs = envNumber('ECC_MCP_HEALTH_TIMEOUT_MS', DEFAULT_TIMEOUT_MS);
// SECURITY: config.env comes from repo-committed MCP configs. Never let it
// override process-critical loader vars that turn into code execution
// (LD_PRELOAD, DYLD_*, NODE_OPTIONS, PATH tampering, etc.).
const BLOCKED_ENV_PREFIXES = ['LD_', 'DYLD_', 'NODE_OPTIONS', 'NODE_PATH', 'PATH', 'PYTHONPATH', 'RUBYLIB', 'PERL5LIB'];
const rawEnv = (config.env && typeof config.env === 'object' && !Array.isArray(config.env) ? config.env : {});
const safeConfigEnv = {};
for (const [k, v] of Object.entries(rawEnv)) {
if (BLOCKED_ENV_PREFIXES.some(p => String(k).toUpperCase().startsWith(p))) {
continue;
}
safeConfigEnv[k] = String(v);
}
const mergedEnv = {
...process.env,
...(config.env && typeof config.env === 'object' && !Array.isArray(config.env) ? config.env : {})
...safeConfigEnv
};
let done = false;
@@ -515,6 +533,29 @@ function probeCommandServer(serverName, config) {
async function probeServer(serverName, resolvedConfig) {
const config = resolvedConfig.config;
// SECURITY: cloning a malicious repo must not auto-execute its MCP servers.
// Workspace configs (cwd .claude.json / .claude/settings.json) are untrusted
// by default; only probe them with explicit operator opt-in.
// Home configs (~/.claude.json) and explicit ECC_MCP_CONFIG_PATH remain allowed.
try {
const src = String(resolvedConfig.source || '');
const cwd = process.cwd();
const isWorkspaceSource = src === require('path').join(cwd, '.claude.json')
|| src === require('path').join(cwd, '.claude', 'settings.json')
|| src.startsWith(cwd + require('path').sep + '.claude' + require('path').sep);
if (isWorkspaceSource && !/^(1|true|yes)$/i.test(String(process.env.ECC_MCP_ALLOW_WORKSPACE_PROBE || ''))) {
return {
ok: false,
failureCode: null,
reason: 'untrusted workspace MCP config skipped (set ECC_MCP_ALLOW_WORKSPACE_PROBE=1 to probe)',
source: resolvedConfig.source
};
}
} catch {
// Fail closed on path errors for workspace sources is handled below;
// continue to normal probing for non-workspace sources.
}
if (config.type === 'http' || config.url) {
const result = await requestHttp(config.url, config.headers || {}, envNumber('ECC_MCP_HEALTH_TIMEOUT_MS', DEFAULT_TIMEOUT_MS));
@@ -546,6 +587,15 @@ async function probeServer(serverName, resolvedConfig) {
}
function reconnectCommand(serverName) {
// SECURITY: reconnect commands are shell strings from env. Disabled by
// default; require explicit opt-in so a malicious .env/direnv cannot gain
// shell execution through this hook.
if (!/^(1|true|yes)$/i.test(String(process.env.ECC_MCP_RECONNECT_ALLOW || ''))) {
return null;
}
if (!/^[A-Za-z0-9_-]{1,64}$/.test(String(serverName || ''))) {
return null;
}
const key = `ECC_MCP_RECONNECT_${String(serverName).toUpperCase().replace(/[^A-Z0-9]/g, '_')}`;
const command = process.env[key] || process.env.ECC_MCP_RECONNECT_COMMAND || '';
if (!command.trim()) {
@@ -563,8 +613,60 @@ function attemptReconnect(serverName) {
return { attempted: false, success: false, reason: 'no reconnect command configured' };
}
const result = spawnSync(command, {
shell: true,
// SECURITY: never run reconnect strings through a shell. Split on
// whitespace (no glob/expansion/substitution) and spawn directly.
// Supports single/double quotes for paths with spaces (e.g. node
// "/tmp/dir with space/reconnect.js"). No variable, command, tilde, or
// glob expansion is performed. {server} was already validated above.
function splitReconnectCommand(s) {
const parts = [];
let cur = '';
let quote = null;
let inToken = false;
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (quote) {
if (ch === quote) {
quote = null;
} else if (ch === '\\' && quote === '"' && i + 1 < s.length && (s[i + 1] === '"' || s[i + 1] === '\\')) {
cur += s[i + 1];
i++;
} else {
cur += ch;
}
} else if (ch === '"' || ch === "'") {
quote = ch;
inToken = true;
} else if (/\s/.test(ch)) {
if (inToken) {
parts.push(cur);
cur = '';
inToken = false;
}
} else {
cur += ch;
inToken = true;
}
}
if (quote) {
return null; // unbalanced quote
}
if (inToken) {
parts.push(cur);
}
return parts;
}
const parts = splitReconnectCommand(String(command).trim());
if (!parts || parts.length === 0) {
return { attempted: false, success: false, reason: 'invalid reconnect command' };
}
const [bin, ...argv] = parts;
if (/[&|<>^%!`$();]/.test(bin) || argv.some(a => /[`$]/.test(a))) {
return { attempted: false, success: false, reason: 'reconnect command contains unsafe characters' };
}
const result = spawnSync(bin, argv, {
shell: false,
env: process.env,
cwd: process.cwd(),
encoding: 'utf8',
+26 -4
View File
@@ -22,9 +22,31 @@ if [[ "$ENABLED" != "yes" ]]; then
exit 0
fi
SCRIPT_PATH="${PLUGIN_ROOT}/${REL_SCRIPT_PATH}"
if [[ ! -f "$SCRIPT_PATH" ]]; then
echo "[Hook] Script not found for ${HOOK_ID}: ${SCRIPT_PATH}" >&2
# Reject traversal / absolute / env-escape paths before touching the filesystem.
# Mirrors the containment check in run-with-flags.js (resolvedRoot prefix).
case "$REL_SCRIPT_PATH" in
/*|\\*|~*|*..*|*\$*|*\`*|*\|*|*\;*|*\&*|*\<*|*\>*|*\"*|*\'*|*\ *|*" "*)
echo "[Hook] Path traversal rejected for ${HOOK_ID}: ${REL_SCRIPT_PATH}" >&2
printf '%s' "$INPUT"
exit 0
;;
esac
# Canonicalize PLUGIN_ROOT (CLAUDE_PLUGIN_ROOT is env-controlled) and the
# candidate script path, then enforce containment inside the plugin root.
PLUGIN_ROOT_CANON="$(realpath -m "$PLUGIN_ROOT" 2>/dev/null || readlink -f "$PLUGIN_ROOT" 2>/dev/null || printf '%s' "$PLUGIN_ROOT")"
SCRIPT_PATH="${PLUGIN_ROOT_CANON}/${REL_SCRIPT_PATH}"
SCRIPT_CANON="$(realpath -m "$SCRIPT_PATH" 2>/dev/null || readlink -f "$SCRIPT_PATH" 2>/dev/null || printf '%s' "$SCRIPT_PATH")"
case "$SCRIPT_CANON" in
"$PLUGIN_ROOT_CANON"/*) ;;
*)
echo "[Hook] Path traversal rejected for ${HOOK_ID}: ${REL_SCRIPT_PATH}" >&2
printf '%s' "$INPUT"
exit 0
;;
esac
if [[ ! -f "$SCRIPT_CANON" ]]; then
echo "[Hook] Script not found for ${HOOK_ID}: ${SCRIPT_CANON}" >&2
printf '%s' "$INPUT"
exit 0
fi
@@ -33,4 +55,4 @@ fi
# This is needed by scripts like observe.sh that behave differently for PreToolUse vs PostToolUse
HOOK_PHASE="${HOOK_ID%%:*}"
printf '%s' "$INPUT" | "$SCRIPT_PATH" "$HOOK_PHASE"
printf '%s' "$INPUT" | "$SCRIPT_CANON" "$HOOK_PHASE"