Skip to main content

safe_chains/cst/
mod.rs

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