168 lines
8.6 KiB
Bash
Executable File
168 lines
8.6 KiB
Bash
Executable File
#!/usr/bin/env bash
|
|
set -uo pipefail
|
|
|
|
# CASAN Track C-MVP — Runtime sandbox scaffold (C6, V22).
|
|
#
|
|
# Generated code/tests must not read secrets, reach the network, fork-bomb, write
|
|
# outside the workspace, or fill the disk. Full isolation needs a container with
|
|
# namespaces/seccomp/network-off (documented below as the production target).
|
|
# This scaffold provides two enforceable layers WITHOUT root/Docker:
|
|
# 1. Static policy pre-check — refuse to launch a command that matches a known
|
|
# dangerous operation (BLOCK before anything runs). This is the deterministic
|
|
# gate the tests assert on.
|
|
# 2. Runtime rlimits (ulimit) — file-size, CPU, and process caps as a backstop,
|
|
# plus the existing wall-clock timeout (tool-exec.sh).
|
|
#
|
|
# HONEST SCOPE — this is NOT kernel isolation. A determined payload using a
|
|
# syscall the static check doesn't model can still act within the rlimits. The
|
|
# production requirement is: run inside `docker run --network=none --read-only
|
|
# --pids-limit ... --memory ... -v <workspace>:/work:rw`. Do not present this as
|
|
# a full sandbox. See TODO(C6-prod) below.
|
|
#
|
|
# Usage:
|
|
# sandbox-run.sh --workspace <dir> [--max-file-kb N] [--cpu-seconds N]
|
|
# [--max-procs N] [--timeout N] -- <command...>
|
|
# Exit: 2 policy-blocked, 124 timeout, else the command's own exit code.
|
|
|
|
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
|
# shellcheck source=casan-log.sh
|
|
source "$SCRIPT_DIR/casan-log.sh"
|
|
|
|
WORKSPACE="$PWD"
|
|
MAX_FILE_KB="${CASAN_SANDBOX_MAX_FILE_KB:-51200}" # 50 MB default
|
|
CPU_SECONDS="${CASAN_SANDBOX_CPU_SECONDS:-30}"
|
|
# Process cap is OPT-IN: `ulimit -u` is a per-USER limit, so forcing a low value
|
|
# on a busy host makes legitimate commands fail to fork. The fork-bomb static
|
|
# check is the real gate; a container --pids-limit is the production backstop.
|
|
MAX_PROCS="${CASAN_SANDBOX_MAX_PROCS:-}"
|
|
TIMEOUT="${CASAN_SANDBOX_TIMEOUT:-30}"
|
|
SANDBOX_MODE="${CASAN_SANDBOX_MODE:-}"
|
|
STRICT_SANDBOX=0
|
|
if [[ "${CASAN_PROFILE:-}" == "prod" || "${CASAN_PROFILE:-}" == "production" || "${CASAN_PROFILE:-}" == "strict" \
|
|
|| "${CASAN_ENFORCEMENT_MODE:-}" == "enforce" || "${CASAN_SANDBOX_STRICT:-0}" == "1" ]]; then
|
|
STRICT_SANDBOX=1
|
|
fi
|
|
[[ -n "$SANDBOX_MODE" ]] || { if [[ "$STRICT_SANDBOX" == "1" ]]; then SANDBOX_MODE="container"; else SANDBOX_MODE="static"; fi; }
|
|
|
|
record_sandbox() { # decision reason backend capability-json
|
|
local decision="$1" reason="$2" backend="$3" capabilities="$4"
|
|
local log="$CASAN_STATE_ROOT/logs/sandbox/decisions.jsonl"
|
|
mkdir -p "$(dirname "$log")"
|
|
CASAN_SANDBOX_CAPABILITIES="$capabilities" python3 - "$log" "$decision" "$reason" "$backend" "${CASAN_EXECUTION_ID:-sandbox-$$}" <<'PY'
|
|
import json, os, sys
|
|
path, decision, reason, backend, execution_id = sys.argv[1:]
|
|
try:
|
|
capabilities = json.loads(os.environ.get("CASAN_SANDBOX_CAPABILITIES", "{}"))
|
|
except ValueError:
|
|
capabilities = {}
|
|
record = {
|
|
"schema_version": "1.0.0", "category": "runtime_control",
|
|
"policy_id": "casan.sandbox.backend", "decision": decision,
|
|
"reason_code": reason, "backend": backend, "execution_id": execution_id,
|
|
"capabilities": capabilities,
|
|
}
|
|
with open(path, "a", encoding="utf-8") as handle:
|
|
handle.write(json.dumps(record, sort_keys=True, separators=(",", ":")) + "\n")
|
|
handle.flush()
|
|
os.fsync(handle.fileno())
|
|
PY
|
|
}
|
|
|
|
while [[ "$#" -gt 0 ]]; do
|
|
case "$1" in
|
|
--workspace) WORKSPACE="${2:-}"; shift 2 ;;
|
|
--max-file-kb) MAX_FILE_KB="${2:-}"; shift 2 ;;
|
|
--cpu-seconds) CPU_SECONDS="${2:-}"; shift 2 ;;
|
|
--max-procs) MAX_PROCS="${2:-}"; shift 2 ;;
|
|
--timeout) TIMEOUT="${2:-}"; shift 2 ;;
|
|
--) shift; break ;;
|
|
*) echo "sandbox-run.sh: unknown arg $1" >&2; exit 64 ;;
|
|
esac
|
|
done
|
|
|
|
if [[ "$#" -eq 0 ]]; then
|
|
echo "Usage: sandbox-run.sh --workspace <dir> -- <command...>" >&2
|
|
exit 64
|
|
fi
|
|
|
|
# C6 production form: CASAN_SANDBOX_MODE=container runs under kernel-backed
|
|
# isolation (sandbox-container.sh: --network=none --read-only --pids-limit …).
|
|
# A requested/required container backend never silently falls back.
|
|
if [[ "$SANDBOX_MODE" == "container" ]]; then
|
|
if [[ "${CASAN_SANDBOX_TEST_FORCE_UNAVAILABLE:-0}" != "1" ]] \
|
|
&& command -v docker >/dev/null 2>&1 && docker info >/dev/null 2>&1; then
|
|
record_sandbox "allow" "sandbox_container_selected" "docker" '{"network_disabled":true,"read_only_root":true,"workspace_write_restricted":true,"environment_filtered":true,"non_root":true,"resource_limits":true}'
|
|
exec "$SCRIPT_DIR/sandbox-container.sh" --workspace "$WORKSPACE" --timeout "$TIMEOUT" -- "$@"
|
|
fi
|
|
if [[ "$STRICT_SANDBOX" == "1" ]]; then
|
|
record_sandbox "deny" "sandbox_isolation_backend_unavailable" "none" '{"timeout_only":false}'
|
|
echo "SANDBOX_ISOLATION_REQUIRED backend=container reason=unavailable" >&2
|
|
exit 2
|
|
fi
|
|
if [[ "${CASAN_SANDBOX_ALLOW_STATIC_FALLBACK:-0}" != "1" ]]; then
|
|
record_sandbox "deny" "sandbox_fallback_not_approved" "none" '{}'
|
|
echo "SANDBOX_FALLBACK_REQUIRES_EXPLICIT_DEVELOPMENT_APPROVAL" >&2
|
|
exit 2
|
|
fi
|
|
record_sandbox "observe_only" "sandbox_static_fallback_development_only" "static_rlimit" '{"network_disabled":false,"read_only_root":false,"workspace_write_restricted":false,"environment_filtered":false,"non_root":false,"resource_limits":true}'
|
|
echo "HIGH: container sandbox unavailable; explicit development static fallback is not production isolation" >&2
|
|
elif [[ "$SANDBOX_MODE" != "static" ]]; then
|
|
record_sandbox "deny" "sandbox_backend_unknown" "$SANDBOX_MODE" '{}'
|
|
echo "SANDBOX_BACKEND_UNKNOWN mode=$SANDBOX_MODE" >&2
|
|
exit 2
|
|
elif [[ "$STRICT_SANDBOX" == "1" ]]; then
|
|
record_sandbox "deny" "sandbox_static_forbidden_in_enforce_mode" "static_rlimit" '{"network_disabled":false,"read_only_root":false}'
|
|
echo "SANDBOX_STATIC_FORBIDDEN_IN_ENFORCE_MODE" >&2
|
|
exit 2
|
|
fi
|
|
|
|
CMD_STR="$*"
|
|
low="$(printf '%s' "$CMD_STR" | tr '[:upper:]' '[:lower:]')"
|
|
|
|
# ── 1. Static policy pre-check ──────────────────────────────────────────────
|
|
block() {
|
|
casan_log error sandbox "SANDBOX_BLOCKED reason=$1 cmd=${CMD_STR:0:120}"
|
|
echo "SANDBOX_BLOCKED reason=$1" >&2
|
|
exit 2
|
|
}
|
|
|
|
# Read of SSH / credential material.
|
|
printf '%s' "$low" | grep -Eq '(\.ssh/|id_rsa|id_ed25519|authorized_keys|known_hosts|/etc/shadow|/etc/passwd|\.aws/credentials|\.netrc)' \
|
|
&& block "read_sensitive_credentials"
|
|
# Network egress of any kind (sandboxed code should be offline).
|
|
printf '%s' "$low" | grep -Eq '(\bcurl\b|\bwget\b|\bnc\b|\bncat\b|\bscp\b|\bsftp\b|\bssh\b|\btelnet\b|\bftp\b|/dev/tcp/|\bnslookup\b|\bdig\b)' \
|
|
&& block "network_egress"
|
|
# Fork bomb / uncontrolled process spawning.
|
|
printf '%s' "$CMD_STR" | grep -Eq ':\(\)\s*\{\s*:?\s*\|?\s*:?\s*&?\s*\}|\bfork\s*\(\)\s*while|while\s*\(\s*true\s*\)\s*\{\s*fork' \
|
|
&& block "fork_bomb"
|
|
# Huge-file / disk-fill.
|
|
printf '%s' "$low" | grep -Eq '\bdd\b[^\n]*of=|truncate\s+-s\s*[0-9]+\s*[gt]|fallocate\s+-l\s*[0-9]+\s*[gt]|head\s+-c\s*[0-9]+\s*[gt]|\byes\b[^\n]*>' \
|
|
&& block "huge_file_or_disk_fill"
|
|
# Writes outside the workspace: redirection to an absolute path not under $WORKSPACE, or path traversal.
|
|
WS_ABS="$(cd "$WORKSPACE" 2>/dev/null && pwd || echo "$WORKSPACE")"
|
|
while read -r target; do
|
|
[[ -z "$target" ]] && continue
|
|
case "$target" in
|
|
/*) [[ "$target" == "$WS_ABS"* || "$target" == /tmp/* || "$target" == /var/folders/* || "$target" == /dev/null ]] || block "write_outside_workspace:$target" ;;
|
|
*"../"*) block "path_traversal_write:$target" ;;
|
|
esac
|
|
done < <(printf '%s\n' "$CMD_STR" | grep -oE '>>?[[:space:]]*[^[:space:];|&]+' | sed -E 's/^>>?[[:space:]]*//')
|
|
|
|
# ── 2. Runtime rlimits + wall-clock timeout ─────────────────────────────────
|
|
casan_log debug sandbox "SANDBOX_RUN workspace=$WS_ABS file_kb=$MAX_FILE_KB cpu=$CPU_SECONDS procs=$MAX_PROCS timeout=$TIMEOUT"
|
|
record_sandbox "allow" "sandbox_static_policy_selected" "static_rlimit" '{"network_disabled":false,"read_only_root":false,"workspace_write_restricted":false,"environment_filtered":false,"non_root":false,"resource_limits":true}'
|
|
(
|
|
ulimit -f "$((MAX_FILE_KB * 2))" 2>/dev/null || true # ulimit -f is in 512-byte blocks
|
|
ulimit -t "$CPU_SECONDS" 2>/dev/null || true
|
|
[[ -n "$MAX_PROCS" ]] && { ulimit -u "$MAX_PROCS" 2>/dev/null || true; }
|
|
cd "$WS_ABS" 2>/dev/null || true
|
|
exec "$SCRIPT_DIR/tool-exec.sh" "$TIMEOUT" -- "$@"
|
|
)
|
|
rc=$?
|
|
exit "$rc"
|
|
|
|
# TODO(C6-prod): replace the rlimit backstop with true isolation:
|
|
# docker run --rm --network=none --read-only --pids-limit=$MAX_PROCS \
|
|
# --memory=512m --cpus=1 -v "$WORKSPACE":/work:rw -w /work <image> <cmd>
|
|
# and/or bubblewrap/nsjail on Linux CI. Track as a Track-C production task.
|