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/// Return the inline script of a `bash`/`sh`/`zsh -c` style command.
75///
76/// The returned slice is raw argument text, so it may still carry the shell
77/// quotes around the script; run it through [`strip_nested_script_quotes`]
78/// before analyzing its contents. Delegates to the one canonical recognizer
79/// so the approval layer and the sandbox preflight cannot disagree about which
80/// flags carry a script (`-lic`, `-icl`, `-x -c`, `env bash -c`, …).
81pub(super) fn nested_shell_script(command: &[String]) -> Option<&str> {
82    crate::command_safety::shell_parser::shell_inline_script(command)
83}
84
85/// Strip one matching pair of shell quotes from a nested `-c` script.
86///
87/// `parse_shell_commands` preserves raw argument text, so a nested script
88/// arrives as `'…'` or `"…"`. The shell removes those quotes before running the
89/// script, so analyzing the quoted blob would both miss the real commands and
90/// mistake quoted glob characters for a dynamic executable.
91pub(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
100/// Returns whether the command crosses an inline-code boundary that must be
101/// admitted by an enforceable sandbox or explicit human approval.
102///
103/// This is deliberately separate from [`command_might_be_dangerous`]: inline
104/// interpreter programs are not forbidden outright, but their source text can
105/// perform arbitrary effects that argv-level command classification cannot
106/// prove safe.
107pub 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    // `[` is the POSIX test builtin, not a glob; `[ -f path ]` must stay a
127    // literal executable. Any other bracket usage is still dynamic.
128    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
152/// Programs that run another program given as their next argument.
153///
154/// Unwrapping them keeps a destructive command visible to the dangerous
155/// detector and to the mounted-target approval, which would otherwise only
156/// see the runner (`nohup rm -rf …`).
157const PROGRAM_RUNNERS: &[&str] = &["builtin", "command", "exec", "nohup", "setsid", "time"];
158
159/// Options that make `command`/`builtin` print a path instead of running it.
160const 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                    // `command -v prog` prints the path instead of running it.
224                    return Some(UnwrappedCommand { command, changes_directory });
225                }
226                command = program;
227            }
228            _ => return Some(UnwrappedCommand { command, changes_directory }),
229        }
230    }
231}
232
233/// Split a runner's leading options from the program it runs.
234fn 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
278/// Git global options that take a value (skip these and their values when finding subcommand)
279fn 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
286/// Git global options with inline values (e.g., --git-dir=/path)
287fn 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
299/// Returns whether a git global option can redirect repository, config, or
300/// helper lookup and therefore must not be treated as an inspection flag.
301pub 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
318/// Find the first matching git subcommand, skipping known global options that
319/// may appear before it (e.g., `-C`, `-c`, `--git-dir`).
320///
321/// Shared with `is_safe_command` to avoid git-global-option bypasses.
322pub(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        // In git, the first non-option token is the subcommand. If it isn't
355        // one of the subcommands we're looking for, we must stop scanning to
356        // avoid misclassifying later positional args (e.g., branch names).
357        return None;
358    }
359
360    None
361}
362
363/// Check if a short flag group contains a specific character (e.g., -fdx contains 'f')
364fn 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
368/// Check if git push command is dangerous (force, delete, or dangerous refspec)
369fn 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
381/// Check if a refspec is dangerous (+refspec forces updates, :refspec deletes)
382fn git_push_refspec_is_dangerous(arg: &str) -> bool {
383    // `+<refspec>` forces updates and `:<dst>` deletes remote refs.
384    (arg.starts_with('+') || arg.starts_with(':')) && arg.len() > 1
385}
386
387/// Check if git clean command uses force flag
388fn 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
394/// Git subcommands whose destructive modes are hard-blocked at preflight.
395/// Recoverable invocations of these subcommands (`git reset --soft`,
396/// `git rm --cached`, `git branch -d`) pass preflight and proceed through
397/// normal policy/approval routing, matching `exec_policy`'s `validate_git_reset`.
398const GIT_GUARDED_SUBCOMMANDS: &[&str] = &["reset", "rm", "branch", "push", "clean"];
399
400/// Only the hard reset modes lose uncommitted changes. `--soft`/`--mixed`
401/// (and a bare reset) move HEAD or the index, which the reflog restores.
402fn 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
408/// `git rm --cached` only unstages paths (the working tree is untouched);
409/// every other `git rm` deletes working-tree files.
410fn git_rm_is_destructive(rm_args: &[String]) -> bool {
411    !rm_args.iter().any(|arg| arg == "--cached")
412}
413
414/// `git branch -d`/`--delete` alone refuses unmerged branches; `-D` (or
415/// `--delete` combined with `-f`/`--force`, including stacked short flags
416/// like `-dD`) overrides that guard. Delete plus force is the destructive
417/// combination.
418fn 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
452/// Single home for the guarded git subcommand decision. Returns the matched
453/// destructive pattern (for actionable preflight messages), or `None` when
454/// the invocation is recoverable and must proceed through normal policy and
455/// approval routing instead of dying at preflight.
456fn classify_git_subcommand(subcommand: &str, args: &[String]) -> Option<&'static str> {
457    // `--` ends option parsing: for the option-only subcommands every later
458    // token is a path or ref name, never a flag (`git rm -- --cached f`
459    // deletes working-tree files). Classify only the pre-`--` option
460    // arguments there; destructive flags before `--` still classify, and a
461    // post-`--` token can only turn a block into a pass when it is genuinely
462    // a name. `push` is excluded: its dangerous payloads are refspecs, which
463    // legitimately occupy the post-`--` positional slot
464    // (`git push origin -- :refs/heads/x` deletes a remote branch).
465    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
489/// Reason a command tripped [`command_might_be_dangerous`], used for
490/// actionable preflight messages. Mirrors the git arm of
491/// `is_dangerous_to_call_with_exec` including env/sudo prefix unwrapping;
492/// non-git patterns keep the generic rejection text.
493pub 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        // Without the git executable in front, `rm` is ambiguous with the
500        // plain Unix command — `rm -f`/`sudo rm -rf` must not receive the
501        // `git rm --cached` remedy.
502        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
511/// Check if a command is a dangerous git subcommand (without the "git" prefix)
512/// This handles commands parsed from shell scripts where the binary name may be omitted
513fn 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
519/// Find git subcommand from a list of args (without the "git" binary name)
520fn 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        // First non-option token that isn't a subcommand we're looking for
548        return None;
549    }
550
551    None
552}
553
554/// Core dangerous command detection for Unix/Linux/macOS
555fn 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 ────
565        "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 ────
574        "rm" => matches!(command.get(1).map(String::as_str), Some("-f" | "-rf" | "-fr" | "-r")),
575
576        // ──── Destructive system commands ────
577        _ if base_cmd == "mkfs" || base_cmd.starts_with("mkfs.") => true,
578        "dd" | "shutdown" | "reboot" | "init" => true,
579
580        // ──── Fork bomb ────
581        _ if base_cmd.ends_with(':') && command.len() >= 2 => command[1] == "(){:|:&};:",
582
583        // ──── Sudo: check the wrapped command ────
584        "sudo" => {
585            if command.len() > 1 {
586                is_dangerous_to_call_with_exec(&command[1..])
587            } else {
588                false
589            }
590        }
591
592        // ──── Git subcommands without "git" prefix (from shell parsing) ────
593        _ => is_dangerous_git_subcommand(command),
594    }
595}
596
597/// Extract base command name from full path
598fn 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;