Skip to main content

vtcode_safety/command_safety/dangerous_commands/
mod.rs

1#![expect(
2    clippy::indexing_slicing,
3    reason = "Dangerous-command matching uses validated token lengths and fixed ASCII option prefixes."
4)]
5
6//! Detection of dangerous commands that should never be executed.
7//!
8//! This module implements hardcoded detection for commands that are inherently
9//! destructive or dangerous, regardless of their options.
10//!
11//! Examples:
12//! - `rm -rf /` (destructive)
13//! - `git reset --hard` (destructive)
14//! - `dd if=/dev/zero of=/dev/sda` (very destructive)
15//! - `sudo rm` (privilege escalation + destruction)
16
17/// Checks if a command appears dangerous to execute.
18/// Returns true if the command should be blocked before execution.
19pub 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    // PowerShell's encoded-command form hides the script from every
31    // platform-neutral parser. Treat it as dangerous before policy or shell
32    // evaluation can classify the base64 payload as an ordinary argument.
33    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    // Support bash -lc "..." parsing for chained commands
49    // If the command is bash -c "..." or similar, parse the script and check each command
50    if let Some(script) = nested_shell_script(command) {
51        let script = strip_nested_script_quotes(script);
52        // Command substitution is resolved by the *inner* shell, after the
53        // outer single quotes have already made it inert for the top-level
54        // scan (`sh -c 'echo $(touch /tmp/probe)'`). Nothing in the nested
55        // text is statically known until the substitution runs, so the script
56        // cannot be admitted as safe.
57        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
74/// Shell options that make the next argument an inline script.
75const NESTED_SCRIPT_FLAGS: &[&str] = &["-c", "-lc", "-ilc"];
76
77/// Return the inline script of a `bash`/`sh`/`zsh -c` style command.
78///
79/// The returned slice is raw argument text, so it may still carry the shell
80/// quotes around the script; run it through [`strip_nested_script_quotes`]
81/// before analyzing its contents.
82pub(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
94/// Strip one matching pair of shell quotes from a nested `-c` script.
95///
96/// `parse_shell_commands` preserves raw argument text, so a nested script
97/// arrives as `'…'` or `"…"`. The shell removes those quotes before running the
98/// script, so analyzing the quoted blob would both miss the real commands and
99/// mistake quoted glob characters for a dynamic executable.
100pub(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
109/// Returns whether the command crosses an inline-code boundary that must be
110/// admitted by an enforceable sandbox or explicit human approval.
111///
112/// This is deliberately separate from [`command_might_be_dangerous`]: inline
113/// interpreter programs are not forbidden outright, but their source text can
114/// perform arbitrary effects that argv-level command classification cannot
115/// prove safe.
116pub 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    // `[` is the POSIX test builtin, not a glob; `[ -f path ]` must stay a
136    // literal executable. Any other bracket usage is still dynamic.
137    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
161/// Programs that run another program given as their next argument.
162///
163/// Unwrapping them keeps a destructive command visible to the dangerous
164/// detector and to the mounted-target approval, which would otherwise only
165/// see the runner (`nohup rm -rf …`).
166const PROGRAM_RUNNERS: &[&str] = &["builtin", "command", "exec", "nohup", "setsid", "time"];
167
168/// Options that make `command`/`builtin` print a path instead of running it.
169const 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                    // `command -v prog` prints the path instead of running it.
233                    return Some(UnwrappedCommand { command, changes_directory });
234                }
235                command = program;
236            }
237            _ => return Some(UnwrappedCommand { command, changes_directory }),
238        }
239    }
240}
241
242/// Split a runner's leading options from the program it runs.
243fn 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
287/// Git global options that take a value (skip these and their values when finding subcommand)
288fn 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
295/// Git global options with inline values (e.g., --git-dir=/path)
296fn 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
308/// Returns whether a git global option can redirect repository, config, or
309/// helper lookup and therefore must not be treated as an inspection flag.
310pub 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
327/// Find the first matching git subcommand, skipping known global options that
328/// may appear before it (e.g., `-C`, `-c`, `--git-dir`).
329///
330/// Shared with `is_safe_command` to avoid git-global-option bypasses.
331pub(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        // In git, the first non-option token is the subcommand. If it isn't
364        // one of the subcommands we're looking for, we must stop scanning to
365        // avoid misclassifying later positional args (e.g., branch names).
366        return None;
367    }
368
369    None
370}
371
372/// Check if a short flag group contains a specific character (e.g., -fdx contains 'f')
373fn 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
377/// Check if git push command is dangerous (force, delete, or dangerous refspec)
378fn 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
390/// Check if a refspec is dangerous (+refspec forces updates, :refspec deletes)
391fn git_push_refspec_is_dangerous(arg: &str) -> bool {
392    // `+<refspec>` forces updates and `:<dst>` deletes remote refs.
393    (arg.starts_with('+') || arg.starts_with(':')) && arg.len() > 1
394}
395
396/// Check if git clean command uses force flag
397fn 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
403/// Git subcommands whose destructive modes are hard-blocked at preflight.
404/// Recoverable invocations of these subcommands (`git reset --soft`,
405/// `git rm --cached`, `git branch -d`) pass preflight and proceed through
406/// normal policy/approval routing, matching `exec_policy`'s `validate_git_reset`.
407const GIT_GUARDED_SUBCOMMANDS: &[&str] = &["reset", "rm", "branch", "push", "clean"];
408
409/// Only the hard reset modes lose uncommitted changes. `--soft`/`--mixed`
410/// (and a bare reset) move HEAD or the index, which the reflog restores.
411fn 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
417/// `git rm --cached` only unstages paths (the working tree is untouched);
418/// every other `git rm` deletes working-tree files.
419fn git_rm_is_destructive(rm_args: &[String]) -> bool {
420    !rm_args.iter().any(|arg| arg == "--cached")
421}
422
423/// `git branch -d`/`--delete` alone refuses unmerged branches; `-D` (or
424/// `--delete` combined with `-f`/`--force`, including stacked short flags
425/// like `-dD`) overrides that guard. Delete plus force is the destructive
426/// combination.
427fn 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
461/// Single home for the guarded git subcommand decision. Returns the matched
462/// destructive pattern (for actionable preflight messages), or `None` when
463/// the invocation is recoverable and must proceed through normal policy and
464/// approval routing instead of dying at preflight.
465fn classify_git_subcommand(subcommand: &str, args: &[String]) -> Option<&'static str> {
466    // `--` ends option parsing: for the option-only subcommands every later
467    // token is a path or ref name, never a flag (`git rm -- --cached f`
468    // deletes working-tree files). Classify only the pre-`--` option
469    // arguments there; destructive flags before `--` still classify, and a
470    // post-`--` token can only turn a block into a pass when it is genuinely
471    // a name. `push` is excluded: its dangerous payloads are refspecs, which
472    // legitimately occupy the post-`--` positional slot
473    // (`git push origin -- :refs/heads/x` deletes a remote branch).
474    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
498/// Reason a command tripped [`command_might_be_dangerous`], used for
499/// actionable preflight messages. Mirrors the git arm of
500/// `is_dangerous_to_call_with_exec` including env/sudo prefix unwrapping;
501/// non-git patterns keep the generic rejection text.
502pub 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        // Without the git executable in front, `rm` is ambiguous with the
509        // plain Unix command — `rm -f`/`sudo rm -rf` must not receive the
510        // `git rm --cached` remedy.
511        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
520/// Check if a command is a dangerous git subcommand (without the "git" prefix)
521/// This handles commands parsed from shell scripts where the binary name may be omitted
522fn 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
528/// Find git subcommand from a list of args (without the "git" binary name)
529fn 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        // First non-option token that isn't a subcommand we're looking for
557        return None;
558    }
559
560    None
561}
562
563/// Core dangerous command detection for Unix/Linux/macOS
564fn 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 ────
574        "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 ────
583        "rm" => matches!(command.get(1).map(String::as_str), Some("-f" | "-rf" | "-fr" | "-r")),
584
585        // ──── Destructive system commands ────
586        _ if base_cmd == "mkfs" || base_cmd.starts_with("mkfs.") => true,
587        "dd" | "shutdown" | "reboot" | "init" => true,
588
589        // ──── Fork bomb ────
590        _ if base_cmd.ends_with(':') && command.len() >= 2 => command[1] == "(){:|:&};:",
591
592        // ──── Sudo: check the wrapped command ────
593        "sudo" => {
594            if command.len() > 1 {
595                is_dangerous_to_call_with_exec(&command[1..])
596            } else {
597                false
598            }
599        }
600
601        // ──── Git subcommands without "git" prefix (from shell parsing) ────
602        _ => is_dangerous_git_subcommand(command),
603    }
604}
605
606/// Extract base command name from full path
607fn 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;