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