vtcode_safety/command_safety/dangerous_commands/
mod.rs1#![expect(
2 clippy::indexing_slicing,
3 reason = "Dangerous-command matching uses validated token lengths and fixed ASCII option prefixes."
4)]
5
6pub fn command_might_be_dangerous(command: &[String]) -> bool {
20 let Some(command) = unwrap_command_prefix(command) else {
21 return !command.is_empty();
22 };
23 let Some(executable) = command.first() else {
24 return false;
25 };
26 if executable_is_dynamic(executable) {
27 return true;
28 }
29
30 if is_encoded_powershell_invocation(command) {
34 return true;
35 }
36
37 #[cfg(windows)]
38 {
39 if crate::command_safety::windows::is_dangerous_command_windows(command) {
40 return true;
41 }
42 }
43
44 if is_dangerous_to_call_with_exec(command) {
45 return true;
46 }
47
48 if let Some(script) = nested_shell_script(command) {
51 let script = strip_nested_script_quotes(script);
52 if super::contains_command_substitution(script) {
58 return true;
59 }
60 if let Ok(sub_commands) = crate::command_safety::shell_parser::parse_shell_commands(script) {
61 for sub_cmd in sub_commands {
62 if command_might_be_dangerous(&sub_cmd) {
63 return true;
64 }
65 }
66 } else {
67 return true;
68 }
69 }
70
71 false
72}
73
74const NESTED_SCRIPT_FLAGS: &[&str] = &["-c", "-lc", "-ilc"];
76
77pub(super) fn nested_shell_script(command: &[String]) -> Option<&str> {
83 match command {
84 [executable, flag, script, ..]
85 if matches!(extract_command_name(executable), "bash" | "sh" | "zsh")
86 && NESTED_SCRIPT_FLAGS.contains(&flag.as_str()) =>
87 {
88 Some(script)
89 }
90 _ => None,
91 }
92}
93
94pub(super) fn strip_nested_script_quotes(script: &str) -> &str {
101 for quote in ['\'', '"'] {
102 if let Some(inner) = script.strip_prefix(quote).and_then(|rest| rest.strip_suffix(quote)) {
103 return inner;
104 }
105 }
106 script
107}
108
109pub fn command_requires_approval(command: &[String]) -> bool {
117 let Some(command) = unwrap_command_prefix(command) else {
118 return false;
119 };
120 if is_inline_code_execution(command) {
121 return true;
122 }
123
124 if let Some(script) = nested_shell_script(command)
125 && let Ok(commands) =
126 crate::command_safety::shell_parser::parse_shell_commands(strip_nested_script_quotes(script))
127 {
128 return commands.iter().any(|nested| command_requires_approval(nested));
129 }
130
131 false
132}
133
134fn executable_is_dynamic(executable: &str) -> bool {
135 if executable == "[" {
138 return false;
139 }
140 executable
141 .chars()
142 .any(|character| matches!(character, '$' | '`' | '*' | '?' | '[' | ']' | '{' | '}'))
143}
144
145fn is_environment_assignment(argument: &str) -> bool {
146 let Some((name, _value)) = argument.split_once('=') else {
147 return false;
148 };
149 let mut characters = name.chars();
150 characters
151 .next()
152 .is_some_and(|character| character == '_' || character.is_ascii_alphabetic())
153 && characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
154}
155
156pub(super) struct UnwrappedCommand<'a> {
157 pub(super) command: &'a [String],
158 pub(super) changes_directory: bool,
159}
160
161const PROGRAM_RUNNERS: &[&str] = &["builtin", "command", "exec", "nohup", "setsid", "time"];
167
168const LOOKUP_ONLY_OPTIONS: &[&str] = &["-p", "-v", "-V"];
170
171pub(super) fn unwrap_command_prefix(command: &[String]) -> Option<&[String]> {
172 unwrap_command_prefix_with_context(command).map(|unwrapped| unwrapped.command)
173}
174
175pub(super) fn unwrap_command_prefix_with_context(mut command: &[String]) -> Option<UnwrappedCommand<'_>> {
176 let mut changes_directory = false;
177 loop {
178 while command.first().is_some_and(|argument| is_environment_assignment(argument)) {
179 command = &command[1..];
180 }
181 let executable = command.first()?;
182 match extract_command_name(executable) {
183 "env" => {
184 command = &command[1..];
185 while let Some(argument) = command.first().map(String::as_str) {
186 if is_environment_assignment(argument) || matches!(argument, "-i" | "--ignore-environment") {
187 command = &command[1..];
188 } else if matches!(argument, "-u" | "--unset") {
189 command = command.get(2..)?;
190 } else if argument.starts_with("--unset=") {
191 command = &command[1..];
192 } else if argument == "--" {
193 command = &command[1..];
194 break;
195 } else if argument.starts_with('-') {
196 return None;
197 } else {
198 break;
199 }
200 }
201 }
202 "sudo" => {
203 command = &command[1..];
204 while let Some(argument) = command.first().map(String::as_str) {
205 if argument == "--" {
206 command = &command[1..];
207 break;
208 }
209 if matches!(argument, "-u" | "--user" | "-g" | "--group" | "-h" | "--host" | "-C" | "--chdir") {
210 changes_directory |= argument == "--chdir";
211 command = command.get(2..)?;
212 } else if matches!(argument, "-E" | "-H" | "-n" | "-S" | "-k" | "-K" | "-b")
213 || argument.starts_with("--user=")
214 || argument.starts_with("--group=")
215 || argument.starts_with("--host=")
216 || argument.starts_with("--chdir=")
217 {
218 changes_directory |= argument.starts_with("--chdir=");
219 command = &command[1..];
220 } else if argument.starts_with('-') {
221 return None;
222 } else {
223 break;
224 }
225 }
226 }
227 name if PROGRAM_RUNNERS.contains(&name) => {
228 let (options, program) = split_runner_options(command.get(1..)?);
229 if matches!(name, "builtin" | "command")
230 && options.iter().any(|option| LOOKUP_ONLY_OPTIONS.contains(&option.as_str()))
231 {
232 return Some(UnwrappedCommand { command, changes_directory });
234 }
235 command = program;
236 }
237 _ => return Some(UnwrappedCommand { command, changes_directory }),
238 }
239 }
240}
241
242fn split_runner_options(arguments: &[String]) -> (&[String], &[String]) {
244 let mut index = 0;
245 while index < arguments.len() && arguments[index].starts_with('-') {
246 index += 1;
247 }
248 arguments.split_at(index)
249}
250
251fn is_inline_code_execution(command: &[String]) -> bool {
252 let Some(executable) = command.first().map(|value| extract_command_name(value).to_ascii_lowercase()) else {
253 return false;
254 };
255 let arguments = &command[1..];
256 match executable.as_str() {
257 "python" | "python3" | "python.exe" | "python3.exe" => arguments.iter().any(|argument| argument == "-c"),
258 "node" | "node.exe" | "ruby" | "ruby.exe" | "perl" | "perl.exe" | "osascript" => {
259 arguments.iter().any(|argument| argument == "-e")
260 }
261 "php" | "php.exe" => arguments.iter().any(|argument| argument == "-r"),
262 "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => arguments.iter().any(|argument| {
263 ["-command", "-c", "-encodedcommand", "-encoded", "-enc", "-e"]
264 .iter()
265 .any(|option| argument.eq_ignore_ascii_case(option))
266 }),
267 _ => false,
268 }
269}
270
271fn is_encoded_powershell_invocation(command: &[String]) -> bool {
272 let Some(executable) = command.first() else {
273 return false;
274 };
275 let executable = extract_command_name(executable).to_ascii_lowercase();
276 if !matches!(executable.as_str(), "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe") {
277 return false;
278 }
279
280 command.iter().skip(1).any(|argument| {
281 ["-encodedcommand", "-encoded", "-enc", "-e"]
282 .iter()
283 .any(|option| argument.eq_ignore_ascii_case(option))
284 })
285}
286
287fn is_git_global_option_with_value(arg: &str) -> bool {
289 matches!(
290 arg,
291 "-C" | "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" | "--super-prefix" | "--work-tree"
292 )
293}
294
295fn is_git_global_option_with_inline_value(arg: &str) -> bool {
297 matches!(
298 arg,
299 s if s.starts_with("--config-env=")
300 || s.starts_with("--exec-path=")
301 || s.starts_with("--git-dir=")
302 || s.starts_with("--namespace=")
303 || s.starts_with("--super-prefix=")
304 || s.starts_with("--work-tree=")
305 ) || ((arg.starts_with("-C") || arg.starts_with("-c")) && arg.len() > 2)
306}
307
308pub fn git_global_option_requires_prompt(arg: &str) -> bool {
311 matches!(
312 arg,
313 "-C" | "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" | "--super-prefix" | "--work-tree"
314 ) || matches!(
315 arg,
316 s if (s.starts_with("-C") && s.len() > 2)
317 || (s.starts_with("-c") && s.len() > 2)
318 || s.starts_with("--config-env=")
319 || s.starts_with("--exec-path=")
320 || s.starts_with("--git-dir=")
321 || s.starts_with("--namespace=")
322 || s.starts_with("--super-prefix=")
323 || s.starts_with("--work-tree=")
324 )
325}
326
327pub(crate) fn find_git_subcommand<'a>(command: &'a [String], subcommands: &[&str]) -> Option<(usize, &'a str)> {
332 let cmd0 = command.first().map(String::as_str)?;
333 if !cmd0.ends_with("git") {
334 return None;
335 }
336
337 let mut skip_next = false;
338 for (idx, arg) in command.iter().enumerate().skip(1) {
339 if skip_next {
340 skip_next = false;
341 continue;
342 }
343
344 let arg = arg.as_str();
345
346 if is_git_global_option_with_inline_value(arg) {
347 continue;
348 }
349
350 if is_git_global_option_with_value(arg) {
351 skip_next = true;
352 continue;
353 }
354
355 if arg == "--" || arg.starts_with('-') {
356 continue;
357 }
358
359 if subcommands.contains(&arg) {
360 return Some((idx, arg));
361 }
362
363 return None;
367 }
368
369 None
370}
371
372fn short_flag_group_contains(arg: &str, target: char) -> bool {
374 arg.starts_with('-') && !arg.starts_with("--") && arg.chars().skip(1).any(|c| c == target)
375}
376
377fn git_push_is_dangerous(push_args: &[String]) -> bool {
379 push_args.iter().map(String::as_str).any(|arg| {
380 matches!(arg, "--force" | "--force-with-lease" | "--force-if-includes" | "--delete" | "-f" | "-d")
381 || arg.starts_with("--force-with-lease=")
382 || arg.starts_with("--force-if-includes=")
383 || arg.starts_with("--delete=")
384 || short_flag_group_contains(arg, 'f')
385 || short_flag_group_contains(arg, 'd')
386 || git_push_refspec_is_dangerous(arg)
387 })
388}
389
390fn git_push_refspec_is_dangerous(arg: &str) -> bool {
392 (arg.starts_with('+') || arg.starts_with(':')) && arg.len() > 1
394}
395
396fn git_clean_is_force(clean_args: &[String]) -> bool {
398 clean_args.iter().map(String::as_str).any(|arg| {
399 matches!(arg, "--force" | "-f") || arg.starts_with("--force=") || short_flag_group_contains(arg, 'f')
400 })
401}
402
403const GIT_GUARDED_SUBCOMMANDS: &[&str] = &["reset", "rm", "branch", "push", "clean"];
408
409fn git_reset_is_destructive(reset_args: &[String]) -> bool {
412 reset_args
413 .iter()
414 .any(|arg| matches!(arg.as_str(), "--hard" | "--merge" | "--keep"))
415}
416
417fn git_rm_is_destructive(rm_args: &[String]) -> bool {
420 !rm_args.iter().any(|arg| arg == "--cached")
421}
422
423fn git_branch_is_force_delete(branch_args: &[String]) -> bool {
428 let mut deletes = false;
429 let mut forces = false;
430 for arg in branch_args {
431 match arg.as_str() {
432 "-D" => {
433 deletes = true;
434 forces = true;
435 }
436 "-d" | "--delete" => deletes = true,
437 "-f" | "--force" => forces = true,
438 _ => {
439 if arg.starts_with("--delete=") {
440 deletes = true;
441 }
442 if arg.starts_with("--force=") {
443 forces = true;
444 }
445 if short_flag_group_contains(arg, 'd') {
446 deletes = true;
447 }
448 if short_flag_group_contains(arg, 'D') {
449 deletes = true;
450 forces = true;
451 }
452 if short_flag_group_contains(arg, 'f') {
453 forces = true;
454 }
455 }
456 }
457 }
458 deletes && forces
459}
460
461fn classify_git_subcommand(subcommand: &str, args: &[String]) -> Option<&'static str> {
466 let scan_args = if subcommand == "push" {
475 args
476 } else {
477 match args.iter().position(|arg| arg == "--") {
478 Some(end) => &args[..end],
479 None => args,
480 }
481 };
482 match subcommand {
483 "reset" if git_reset_is_destructive(scan_args) => {
484 Some("git reset --hard/--merge/--keep discards uncommitted changes; use `git stash` or `git reset --soft`")
485 }
486 "rm" if git_rm_is_destructive(scan_args) => {
487 Some("git rm deletes working-tree files; unstage with `git rm --cached` instead")
488 }
489 "branch" if git_branch_is_force_delete(scan_args) => {
490 Some("git branch -D/--delete --force skips the unmerged-branch guard; use `-d` for merged branches")
491 }
492 "push" if git_push_is_dangerous(scan_args) => Some("git push force-updates or deletes remote refs"),
493 "clean" if git_clean_is_force(scan_args) => Some("git clean --force deletes untracked files"),
494 _ => None,
495 }
496}
497
498pub fn dangerous_command_reason(command: &[String]) -> Option<&'static str> {
503 let command = unwrap_command_prefix(command)?;
504 let cmd0 = command.first().map(String::as_str);
505 let (idx, subcommand) = if extract_command_name(cmd0.unwrap_or("")) == "git" {
506 find_git_subcommand(command, GIT_GUARDED_SUBCOMMANDS)?
507 } else {
508 let (idx, subcommand) = find_git_subcommand_from_args(command, GIT_GUARDED_SUBCOMMANDS)?;
512 if subcommand == "rm" {
513 return None;
514 }
515 (idx, subcommand)
516 };
517 classify_git_subcommand(subcommand, &command[idx + 1..])
518}
519
520fn is_dangerous_git_subcommand(command: &[String]) -> bool {
523 find_git_subcommand_from_args(command, GIT_GUARDED_SUBCOMMANDS)
524 .and_then(|(idx, subcommand)| classify_git_subcommand(subcommand, &command[idx + 1..]))
525 .is_some()
526}
527
528fn find_git_subcommand_from_args<'a>(args: &'a [String], subcommands: &[&str]) -> Option<(usize, &'a str)> {
530 let mut skip_next = false;
531 for (idx, arg) in args.iter().enumerate() {
532 if skip_next {
533 skip_next = false;
534 continue;
535 }
536
537 let arg = arg.as_str();
538
539 if is_git_global_option_with_inline_value(arg) {
540 continue;
541 }
542
543 if is_git_global_option_with_value(arg) {
544 skip_next = true;
545 continue;
546 }
547
548 if arg == "--" || arg.starts_with('-') {
549 continue;
550 }
551
552 if subcommands.contains(&arg) {
553 return Some((idx, arg));
554 }
555
556 return None;
558 }
559
560 None
561}
562
563fn is_dangerous_to_call_with_exec(command: &[String]) -> bool {
565 if command.is_empty() {
566 return false;
567 }
568
569 let cmd0 = command.first().map(String::as_str);
570 let base_cmd = extract_command_name(cmd0.unwrap_or(""));
571
572 match base_cmd {
573 "git" => {
575 let Some((subcommand_idx, subcommand)) = find_git_subcommand(command, GIT_GUARDED_SUBCOMMANDS) else {
576 return false;
577 };
578
579 classify_git_subcommand(subcommand, &command[subcommand_idx + 1..]).is_some()
580 }
581
582 "rm" => matches!(command.get(1).map(String::as_str), Some("-f" | "-rf" | "-fr" | "-r")),
584
585 _ if base_cmd == "mkfs" || base_cmd.starts_with("mkfs.") => true,
587 "dd" | "shutdown" | "reboot" | "init" => true,
588
589 _ if base_cmd.ends_with(':') && command.len() >= 2 => command[1] == "(){:|:&};:",
591
592 "sudo" => {
594 if command.len() > 1 {
595 is_dangerous_to_call_with_exec(&command[1..])
596 } else {
597 false
598 }
599 }
600
601 _ => is_dangerous_git_subcommand(command),
603 }
604}
605
606fn extract_command_name(cmd: &str) -> &str {
608 std::path::Path::new(cmd)
609 .file_name()
610 .and_then(|osstr| osstr.to_str())
611 .unwrap_or(cmd)
612}
613
614#[cfg(test)]
615mod tests;