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