Skip to main content

safe_chains/cst/
mod.rs

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