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
74pub(super) fn nested_shell_script(command: &[String]) -> Option<&str> {
82 crate::command_safety::shell_parser::shell_inline_script(command)
83}
84
85pub(super) fn strip_nested_script_quotes(script: &str) -> &str {
92 for quote in ['\'', '"'] {
93 if let Some(inner) = script.strip_prefix(quote).and_then(|rest| rest.strip_suffix(quote)) {
94 return inner;
95 }
96 }
97 script
98}
99
100pub fn command_requires_approval(command: &[String]) -> bool {
108 let Some(command) = unwrap_command_prefix(command) else {
109 return false;
110 };
111 if is_inline_code_execution(command) {
112 return true;
113 }
114
115 if let Some(script) = nested_shell_script(command)
116 && let Ok(commands) =
117 crate::command_safety::shell_parser::parse_shell_commands(strip_nested_script_quotes(script))
118 {
119 return commands.iter().any(|nested| command_requires_approval(nested));
120 }
121
122 false
123}
124
125fn executable_is_dynamic(executable: &str) -> bool {
126 if executable == "[" {
129 return false;
130 }
131 executable
132 .chars()
133 .any(|character| matches!(character, '$' | '`' | '*' | '?' | '[' | ']' | '{' | '}'))
134}
135
136fn is_environment_assignment(argument: &str) -> bool {
137 let Some((name, _value)) = argument.split_once('=') else {
138 return false;
139 };
140 let mut characters = name.chars();
141 characters
142 .next()
143 .is_some_and(|character| character == '_' || character.is_ascii_alphabetic())
144 && characters.all(|character| character == '_' || character.is_ascii_alphanumeric())
145}
146
147pub(super) struct UnwrappedCommand<'a> {
148 pub(super) command: &'a [String],
149 pub(super) changes_directory: bool,
150}
151
152const PROGRAM_RUNNERS: &[&str] = &["builtin", "command", "exec", "nohup", "setsid", "time"];
158
159const LOOKUP_ONLY_OPTIONS: &[&str] = &["-p", "-v", "-V"];
161
162pub(super) fn unwrap_command_prefix(command: &[String]) -> Option<&[String]> {
163 unwrap_command_prefix_with_context(command).map(|unwrapped| unwrapped.command)
164}
165
166pub(super) fn unwrap_command_prefix_with_context(mut command: &[String]) -> Option<UnwrappedCommand<'_>> {
167 let mut changes_directory = false;
168 loop {
169 while command.first().is_some_and(|argument| is_environment_assignment(argument)) {
170 command = &command[1..];
171 }
172 let executable = command.first()?;
173 match extract_command_name(executable) {
174 "env" => {
175 command = &command[1..];
176 while let Some(argument) = command.first().map(String::as_str) {
177 if is_environment_assignment(argument) || matches!(argument, "-i" | "--ignore-environment") {
178 command = &command[1..];
179 } else if matches!(argument, "-u" | "--unset") {
180 command = command.get(2..)?;
181 } else if argument.starts_with("--unset=") {
182 command = &command[1..];
183 } else if argument == "--" {
184 command = &command[1..];
185 break;
186 } else if argument.starts_with('-') {
187 return None;
188 } else {
189 break;
190 }
191 }
192 }
193 "sudo" => {
194 command = &command[1..];
195 while let Some(argument) = command.first().map(String::as_str) {
196 if argument == "--" {
197 command = &command[1..];
198 break;
199 }
200 if matches!(argument, "-u" | "--user" | "-g" | "--group" | "-h" | "--host" | "-C" | "--chdir") {
201 changes_directory |= argument == "--chdir";
202 command = command.get(2..)?;
203 } else if matches!(argument, "-E" | "-H" | "-n" | "-S" | "-k" | "-K" | "-b")
204 || argument.starts_with("--user=")
205 || argument.starts_with("--group=")
206 || argument.starts_with("--host=")
207 || argument.starts_with("--chdir=")
208 {
209 changes_directory |= argument.starts_with("--chdir=");
210 command = &command[1..];
211 } else if argument.starts_with('-') {
212 return None;
213 } else {
214 break;
215 }
216 }
217 }
218 name if PROGRAM_RUNNERS.contains(&name) => {
219 let (options, program) = split_runner_options(command.get(1..)?);
220 if matches!(name, "builtin" | "command")
221 && options.iter().any(|option| LOOKUP_ONLY_OPTIONS.contains(&option.as_str()))
222 {
223 return Some(UnwrappedCommand { command, changes_directory });
225 }
226 command = program;
227 }
228 _ => return Some(UnwrappedCommand { command, changes_directory }),
229 }
230 }
231}
232
233fn split_runner_options(arguments: &[String]) -> (&[String], &[String]) {
235 let mut index = 0;
236 while index < arguments.len() && arguments[index].starts_with('-') {
237 index += 1;
238 }
239 arguments.split_at(index)
240}
241
242fn is_inline_code_execution(command: &[String]) -> bool {
243 let Some(executable) = command.first().map(|value| extract_command_name(value).to_ascii_lowercase()) else {
244 return false;
245 };
246 let arguments = &command[1..];
247 match executable.as_str() {
248 "python" | "python3" | "python.exe" | "python3.exe" => arguments.iter().any(|argument| argument == "-c"),
249 "node" | "node.exe" | "ruby" | "ruby.exe" | "perl" | "perl.exe" | "osascript" => {
250 arguments.iter().any(|argument| argument == "-e")
251 }
252 "php" | "php.exe" => arguments.iter().any(|argument| argument == "-r"),
253 "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe" => arguments.iter().any(|argument| {
254 ["-command", "-c", "-encodedcommand", "-encoded", "-enc", "-e"]
255 .iter()
256 .any(|option| argument.eq_ignore_ascii_case(option))
257 }),
258 _ => false,
259 }
260}
261
262fn is_encoded_powershell_invocation(command: &[String]) -> bool {
263 let Some(executable) = command.first() else {
264 return false;
265 };
266 let executable = extract_command_name(executable).to_ascii_lowercase();
267 if !matches!(executable.as_str(), "powershell" | "powershell.exe" | "pwsh" | "pwsh.exe") {
268 return false;
269 }
270
271 command.iter().skip(1).any(|argument| {
272 ["-encodedcommand", "-encoded", "-enc", "-e"]
273 .iter()
274 .any(|option| argument.eq_ignore_ascii_case(option))
275 })
276}
277
278fn is_git_global_option_with_value(arg: &str) -> bool {
280 matches!(
281 arg,
282 "-C" | "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" | "--super-prefix" | "--work-tree"
283 )
284}
285
286fn is_git_global_option_with_inline_value(arg: &str) -> bool {
288 matches!(
289 arg,
290 s if s.starts_with("--config-env=")
291 || s.starts_with("--exec-path=")
292 || s.starts_with("--git-dir=")
293 || s.starts_with("--namespace=")
294 || s.starts_with("--super-prefix=")
295 || s.starts_with("--work-tree=")
296 ) || ((arg.starts_with("-C") || arg.starts_with("-c")) && arg.len() > 2)
297}
298
299pub fn git_global_option_requires_prompt(arg: &str) -> bool {
302 matches!(
303 arg,
304 "-C" | "-c" | "--config-env" | "--exec-path" | "--git-dir" | "--namespace" | "--super-prefix" | "--work-tree"
305 ) || matches!(
306 arg,
307 s if (s.starts_with("-C") && s.len() > 2)
308 || (s.starts_with("-c") && s.len() > 2)
309 || s.starts_with("--config-env=")
310 || s.starts_with("--exec-path=")
311 || s.starts_with("--git-dir=")
312 || s.starts_with("--namespace=")
313 || s.starts_with("--super-prefix=")
314 || s.starts_with("--work-tree=")
315 )
316}
317
318pub(crate) fn find_git_subcommand<'a>(command: &'a [String], subcommands: &[&str]) -> Option<(usize, &'a str)> {
323 let cmd0 = command.first().map(String::as_str)?;
324 if !cmd0.ends_with("git") {
325 return None;
326 }
327
328 let mut skip_next = false;
329 for (idx, arg) in command.iter().enumerate().skip(1) {
330 if skip_next {
331 skip_next = false;
332 continue;
333 }
334
335 let arg = arg.as_str();
336
337 if is_git_global_option_with_inline_value(arg) {
338 continue;
339 }
340
341 if is_git_global_option_with_value(arg) {
342 skip_next = true;
343 continue;
344 }
345
346 if arg == "--" || arg.starts_with('-') {
347 continue;
348 }
349
350 if subcommands.contains(&arg) {
351 return Some((idx, arg));
352 }
353
354 return None;
358 }
359
360 None
361}
362
363fn short_flag_group_contains(arg: &str, target: char) -> bool {
365 arg.starts_with('-') && !arg.starts_with("--") && arg.chars().skip(1).any(|c| c == target)
366}
367
368fn git_push_is_dangerous(push_args: &[String]) -> bool {
370 push_args.iter().map(String::as_str).any(|arg| {
371 matches!(arg, "--force" | "--force-with-lease" | "--force-if-includes" | "--delete" | "-f" | "-d")
372 || arg.starts_with("--force-with-lease=")
373 || arg.starts_with("--force-if-includes=")
374 || arg.starts_with("--delete=")
375 || short_flag_group_contains(arg, 'f')
376 || short_flag_group_contains(arg, 'd')
377 || git_push_refspec_is_dangerous(arg)
378 })
379}
380
381fn git_push_refspec_is_dangerous(arg: &str) -> bool {
383 (arg.starts_with('+') || arg.starts_with(':')) && arg.len() > 1
385}
386
387fn git_clean_is_force(clean_args: &[String]) -> bool {
389 clean_args.iter().map(String::as_str).any(|arg| {
390 matches!(arg, "--force" | "-f") || arg.starts_with("--force=") || short_flag_group_contains(arg, 'f')
391 })
392}
393
394const GIT_GUARDED_SUBCOMMANDS: &[&str] = &["reset", "rm", "branch", "push", "clean"];
399
400fn git_reset_is_destructive(reset_args: &[String]) -> bool {
403 reset_args
404 .iter()
405 .any(|arg| matches!(arg.as_str(), "--hard" | "--merge" | "--keep"))
406}
407
408fn git_rm_is_destructive(rm_args: &[String]) -> bool {
411 !rm_args.iter().any(|arg| arg == "--cached")
412}
413
414fn git_branch_is_force_delete(branch_args: &[String]) -> bool {
419 let mut deletes = false;
420 let mut forces = false;
421 for arg in branch_args {
422 match arg.as_str() {
423 "-D" => {
424 deletes = true;
425 forces = true;
426 }
427 "-d" | "--delete" => deletes = true,
428 "-f" | "--force" => forces = true,
429 _ => {
430 if arg.starts_with("--delete=") {
431 deletes = true;
432 }
433 if arg.starts_with("--force=") {
434 forces = true;
435 }
436 if short_flag_group_contains(arg, 'd') {
437 deletes = true;
438 }
439 if short_flag_group_contains(arg, 'D') {
440 deletes = true;
441 forces = true;
442 }
443 if short_flag_group_contains(arg, 'f') {
444 forces = true;
445 }
446 }
447 }
448 }
449 deletes && forces
450}
451
452fn classify_git_subcommand(subcommand: &str, args: &[String]) -> Option<&'static str> {
457 let scan_args = if subcommand == "push" {
466 args
467 } else {
468 match args.iter().position(|arg| arg == "--") {
469 Some(end) => &args[..end],
470 None => args,
471 }
472 };
473 match subcommand {
474 "reset" if git_reset_is_destructive(scan_args) => {
475 Some("git reset --hard/--merge/--keep discards uncommitted changes; use `git stash` or `git reset --soft`")
476 }
477 "rm" if git_rm_is_destructive(scan_args) => {
478 Some("git rm deletes working-tree files; unstage with `git rm --cached` instead")
479 }
480 "branch" if git_branch_is_force_delete(scan_args) => {
481 Some("git branch -D/--delete --force skips the unmerged-branch guard; use `-d` for merged branches")
482 }
483 "push" if git_push_is_dangerous(scan_args) => Some("git push force-updates or deletes remote refs"),
484 "clean" if git_clean_is_force(scan_args) => Some("git clean --force deletes untracked files"),
485 _ => None,
486 }
487}
488
489pub fn dangerous_command_reason(command: &[String]) -> Option<&'static str> {
494 let command = unwrap_command_prefix(command)?;
495 let cmd0 = command.first().map(String::as_str);
496 let (idx, subcommand) = if extract_command_name(cmd0.unwrap_or("")) == "git" {
497 find_git_subcommand(command, GIT_GUARDED_SUBCOMMANDS)?
498 } else {
499 let (idx, subcommand) = find_git_subcommand_from_args(command, GIT_GUARDED_SUBCOMMANDS)?;
503 if subcommand == "rm" {
504 return None;
505 }
506 (idx, subcommand)
507 };
508 classify_git_subcommand(subcommand, &command[idx + 1..])
509}
510
511fn is_dangerous_git_subcommand(command: &[String]) -> bool {
514 find_git_subcommand_from_args(command, GIT_GUARDED_SUBCOMMANDS)
515 .and_then(|(idx, subcommand)| classify_git_subcommand(subcommand, &command[idx + 1..]))
516 .is_some()
517}
518
519fn find_git_subcommand_from_args<'a>(args: &'a [String], subcommands: &[&str]) -> Option<(usize, &'a str)> {
521 let mut skip_next = false;
522 for (idx, arg) in args.iter().enumerate() {
523 if skip_next {
524 skip_next = false;
525 continue;
526 }
527
528 let arg = arg.as_str();
529
530 if is_git_global_option_with_inline_value(arg) {
531 continue;
532 }
533
534 if is_git_global_option_with_value(arg) {
535 skip_next = true;
536 continue;
537 }
538
539 if arg == "--" || arg.starts_with('-') {
540 continue;
541 }
542
543 if subcommands.contains(&arg) {
544 return Some((idx, arg));
545 }
546
547 return None;
549 }
550
551 None
552}
553
554fn is_dangerous_to_call_with_exec(command: &[String]) -> bool {
556 if command.is_empty() {
557 return false;
558 }
559
560 let cmd0 = command.first().map(String::as_str);
561 let base_cmd = extract_command_name(cmd0.unwrap_or(""));
562
563 match base_cmd {
564 "git" => {
566 let Some((subcommand_idx, subcommand)) = find_git_subcommand(command, GIT_GUARDED_SUBCOMMANDS) else {
567 return false;
568 };
569
570 classify_git_subcommand(subcommand, &command[subcommand_idx + 1..]).is_some()
571 }
572
573 "rm" => matches!(command.get(1).map(String::as_str), Some("-f" | "-rf" | "-fr" | "-r")),
575
576 _ if base_cmd == "mkfs" || base_cmd.starts_with("mkfs.") => true,
578 "dd" | "shutdown" | "reboot" | "init" => true,
579
580 _ if base_cmd.ends_with(':') && command.len() >= 2 => command[1] == "(){:|:&};:",
582
583 "sudo" => {
585 if command.len() > 1 {
586 is_dangerous_to_call_with_exec(&command[1..])
587 } else {
588 false
589 }
590 }
591
592 _ => is_dangerous_git_subcommand(command),
594 }
595}
596
597fn extract_command_name(cmd: &str) -> &str {
599 std::path::Path::new(cmd)
600 .file_name()
601 .and_then(|osstr| osstr.to_str())
602 .unwrap_or(cmd)
603}
604
605#[cfg(test)]
606mod tests;