Skip to main content

safe_chains/cst/
mod.rs

1mod ansi_c;
2mod brace;
3#[cfg(test)]
4mod brace_bash_tests;
5mod budget;
6mod cd;
7pub(crate) mod check;
8mod classify_budget;
9#[cfg(test)]
10mod classify_budget_tests;
11mod display;
12mod echoed;
13pub(crate) mod escape;
14pub(crate) mod eval;
15mod explain;
16#[cfg(test)]
17mod glob_tests;
18pub(crate) mod heredocs;
19mod loops;
20#[cfg(test)]
21mod loops_tests;
22pub(crate) mod netargs;
23#[cfg(test)]
24mod normalize_tests;
25pub(crate) mod opaque;
26#[cfg(test)]
27mod opaque_tests;
28mod parse;
29mod printed;
30#[cfg(test)]
31mod proptests;
32mod reserved;
33mod scope_budget;
34mod sub_close;
35
36#[derive(Debug, Clone, PartialEq, Eq)]
37pub struct Script(pub Vec<Stmt>);
38
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct Stmt {
41    pub pipeline: Pipeline,
42    pub op: Option<ListOp>,
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46pub enum ListOp {
47    And,
48    Or,
49    Semi,
50    Amp,
51}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
54pub struct Pipeline {
55    pub bang: bool,
56    pub commands: Vec<Cmd>,
57}
58
59#[derive(Debug, Clone, PartialEq, Eq)]
60pub enum Cmd {
61    Simple(SimpleCmd),
62    Subshell {
63        body: Script,
64        redirs: Vec<Redir>,
65    },
66    BraceGroup {
67        body: Script,
68        redirs: Vec<Redir>,
69    },
70    For {
71        var: String,
72        items: Vec<Word>,
73        body: Script,
74        redirs: Vec<Redir>,
75    },
76    While {
77        cond: Script,
78        body: Script,
79        redirs: Vec<Redir>,
80    },
81    Until {
82        cond: Script,
83        body: Script,
84        redirs: Vec<Redir>,
85    },
86    If {
87        branches: Vec<Branch>,
88        else_body: Option<Script>,
89        redirs: Vec<Redir>,
90    },
91    DoubleBracket {
92        words: Vec<Word>,
93        redirs: Vec<Redir>,
94    },
95    /// `case WORD in PATTERN) BODY ;; … esac` (POSIX 2.9.4.3). Which arm runs depends on a value
96    /// resolved at runtime, so — like [`Cmd::If`] — every arm body is classified and the command
97    /// is only as safe as its worst arm.
98    Case {
99        subject: Word,
100        arms: Vec<CaseArm>,
101        redirs: Vec<Redir>,
102    },
103    /// `name() { body }` (or `function name { body }`). Defining a function has NO effect — it is
104    /// classified Inert. The body's safety matters only when the function is CALLED (resolved in
105    /// `check`), so it is stored, not flattened.
106    FunctionDef {
107        name: String,
108        body: Script,
109    },
110}
111
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct Branch {
114    pub cond: Script,
115    pub body: Script,
116}
117
118/// One `PATTERN|PATTERN) BODY ;;` arm of a [`Cmd::Case`]. The patterns are glob words matched
119/// against the subject; they are never executed, so only `body` carries risk.
120#[derive(Debug, Clone, PartialEq, Eq)]
121pub struct CaseArm {
122    pub patterns: Vec<Word>,
123    pub body: Script,
124}
125
126#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct SimpleCmd {
128    pub env: Vec<(String, Word)>,
129    pub words: Vec<Word>,
130    pub redirs: Vec<Redir>,
131}
132
133#[derive(Debug, Clone, PartialEq, Eq)]
134pub struct Word(pub Vec<WordPart>);
135
136#[derive(Debug, Clone, PartialEq, Eq)]
137pub enum WordPart {
138    Lit(String),
139    Escape(char),
140    SQuote(String),
141    /// `$'…'`, holding the text between the quotes as typed; [`Word::eval`] decodes it.
142    AnsiC(String),
143    DQuote(Word),
144    CmdSub(Script),
145    ProcSub(Script),
146    Backtick(String),
147    /// `$(( … ))`. Holds a `Word`, not raw text, because the body is not opaque: a `$( )` inside it
148    /// RUNS. The arithmetic itself is inert — it can only produce a number, and bash, zsh and dash
149    /// all evaluate `$((id))` to 0 rather than executing `id` — so the inner command is what
150    /// decides, and storing parts is what lets the ordinary substitution walkers reach it.
151    Arith(Word),
152}
153
154/// How an output redirect opens its target. All three land the same bytes somewhere, so they
155/// classify identically — the distinction is kept so `--explain` can echo the command the user
156/// actually typed rather than a normalized one. Mutually exclusive by construction: `>>|` is not
157/// a redirect, and a bool pair would let a generator build one.
158#[derive(Debug, Clone, Copy, PartialEq, Eq)]
159pub enum WriteMode {
160    /// `>` — truncate.
161    Truncate,
162    /// `>>` — append.
163    Append,
164    /// `&>` (and the equivalent `>&FILE`) — stdout AND stderr to the file, truncating. Both
165    /// streams land on ONE target, so the locus gate has exactly one path to judge, the same as
166    /// `>`; the variant exists so `--explain` echoes the operator that was typed.
167    TruncateBoth,
168    /// `&>>` — stdout AND stderr to the file, appending.
169    AppendBoth,
170    /// `>|` — truncate, overriding `noclobber` (POSIX 2.7.2).
171    Clobber,
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
175pub enum Redir {
176    Write {
177        fd: u32,
178        target: Word,
179        mode: WriteMode,
180    },
181    Read {
182        fd: u32,
183        target: Word,
184    },
185    /// `<>` — the target is opened for reading AND writing (POSIX 2.7.5), so it is gated on both
186    /// faces. Neither alone is sufficient: the write gate would miss the disclosure of reading a
187    /// secret, and the read gate would miss the overwrite.
188    ReadWrite {
189        fd: u32,
190        target: Word,
191    },
192    HereStr(Word),
193    HereDoc {
194        delimiter: String,
195        strip_tabs: bool,
196        /// The body's parsed EXPANSIONS. A heredoc body is data only when the delimiter is quoted
197        /// (`<<'EOF'`, `<<"EOF"`, `<<\EOF`, `<<E"O"F`); with a bare `<<EOF` the shell expands the
198        /// body exactly as it would a double-quoted string, so `$(…)` and backticks in it RUN.
199        /// Empty when the delimiter is quoted, so a quoted body stays pure data.
200        body: Word,
201    },
202    DupFd {
203        src: u32,
204        dst: String,
205    },
206}
207
208pub use check::{command_verdict, is_safe_command, is_safe_pipeline};
209pub(crate) use explain::denied_inner_words;
210pub use explain::{Explanation, SegmentReport, explain, explain_with_coverage};
211pub use parse::parse;
212
213impl Word {
214    pub fn eval(&self) -> String {
215        eval::eval_word(self)
216    }
217
218    /// The set of literal words this word produces under UNQUOTED brace expansion (`{a,b}` → two
219    /// words). Every produced word must be classified, so a braced alternative can't hide a system
220    /// path from the gate (`cat {/etc/shadow,x}`). Non-braced words expand to `[self.eval()]`.
221    pub fn expand(&self) -> Vec<String> {
222        eval::expand_word(self)
223    }
224
225    pub fn literal(s: &str) -> Self {
226        Word(vec![WordPart::Lit(s.to_string())])
227    }
228
229    pub fn normalize(&self) -> Self {
230        let mut parts = Vec::new();
231        for part in &self.0 {
232            let part = match part {
233                WordPart::DQuote(inner) => WordPart::DQuote(inner.normalize()),
234                WordPart::CmdSub(s) => WordPart::CmdSub(s.normalize()),
235                WordPart::ProcSub(s) => WordPart::ProcSub(s.normalize()),
236                other => other.clone(),
237            };
238            if let WordPart::Lit(s) = &part
239                && let Some(WordPart::Lit(prev)) = parts.last_mut()
240            {
241                prev.push_str(s);
242                continue;
243            }
244            parts.push(part);
245        }
246        Word(parts)
247    }
248}
249
250impl Script {
251    pub fn is_empty(&self) -> bool {
252        self.0.is_empty()
253    }
254
255    pub fn normalize(&self) -> Self {
256        Script(self.0.iter().map(|stmt| Stmt { pipeline: stmt.pipeline.normalize(), op: stmt.op }).collect())
257    }
258
259    pub fn normalize_as_body(&self) -> Self {
260        let mut s = self.normalize();
261        if let Some(last) = s.0.last_mut()
262            && last.op.is_none()
263        {
264            last.op = Some(ListOp::Semi);
265        }
266        s
267    }
268}
269
270impl Pipeline {
271    fn normalize(&self) -> Self {
272        Pipeline { bang: self.bang, commands: self.commands.iter().map(|c| c.normalize()).collect() }
273    }
274}
275
276impl Cmd {
277    fn normalize(&self) -> Self {
278        match self {
279            Cmd::Simple(s) => Cmd::Simple(s.normalize()),
280            Cmd::Subshell { body, redirs } => Cmd::Subshell { body: body.normalize(), redirs: normalize_redirs(redirs) },
281            Cmd::BraceGroup { body, redirs } => Cmd::BraceGroup { body: body.normalize_as_body(), redirs: normalize_redirs(redirs) },
282            Cmd::For { var, items, body, redirs } => Cmd::For {
283                var: var.clone(),
284                items: items.iter().map(|w| w.normalize()).collect(),
285                body: body.normalize_as_body(),
286                redirs: normalize_redirs(redirs),
287            },
288            Cmd::While { cond, body, redirs } => {
289                Cmd::While { cond: cond.normalize_as_body(), body: body.normalize_as_body(), redirs: normalize_redirs(redirs) }
290            }
291            Cmd::Until { cond, body, redirs } => {
292                Cmd::Until { cond: cond.normalize_as_body(), body: body.normalize_as_body(), redirs: normalize_redirs(redirs) }
293            }
294            Cmd::If { branches, else_body, redirs } => Cmd::If {
295                branches: branches
296                    .iter()
297                    .map(|b| Branch { cond: b.cond.normalize_as_body(), body: b.body.normalize_as_body() })
298                    .collect(),
299                else_body: else_body.as_ref().map(|e| e.normalize_as_body()),
300                redirs: normalize_redirs(redirs),
301            },
302            Cmd::DoubleBracket { words, redirs } => {
303                Cmd::DoubleBracket { words: words.iter().map(|w| w.normalize()).collect(), redirs: normalize_redirs(redirs) }
304            }
305            Cmd::Case { subject, arms, redirs } => Cmd::Case {
306                subject: subject.normalize(),
307                arms: arms
308                    .iter()
309                    .map(|a| CaseArm { patterns: a.patterns.iter().map(|w| w.normalize()).collect(), body: a.body.normalize_as_body() })
310                    .collect(),
311                redirs: normalize_redirs(redirs),
312            },
313            Cmd::FunctionDef { name, body } => Cmd::FunctionDef { name: name.clone(), body: body.normalize_as_body() },
314        }
315    }
316}
317
318impl SimpleCmd {
319    fn normalize(&self) -> Self {
320        SimpleCmd {
321            env: self.env.iter().map(|(k, v)| (k.clone(), v.normalize())).collect(),
322            words: self.words.iter().map(|w| w.normalize()).collect(),
323            redirs: normalize_redirs(&self.redirs),
324        }
325    }
326}
327
328fn normalize_redirs(redirs: &[Redir]) -> Vec<Redir> {
329    redirs
330        .iter()
331        .map(|r| match r {
332            Redir::Write { fd, target, mode } => Redir::Write { fd: *fd, target: target.normalize(), mode: *mode },
333            Redir::Read { fd, target } => Redir::Read { fd: *fd, target: target.normalize() },
334            Redir::ReadWrite { fd, target } => Redir::ReadWrite { fd: *fd, target: target.normalize() },
335            Redir::HereStr(w) => Redir::HereStr(w.normalize()),
336            Redir::HereDoc { .. } | Redir::DupFd { .. } => r.clone(),
337        })
338        .collect()
339}