Skip to main content

eclipse_core/
risk.rs

1//! Which commands are dangerous enough to stop and ask about, and which are not.
2//!
3//! A prompt costs a person a decision, so the decision has to be worth their attention. Asking
4//! before every `ls` teaches them to press `y` without reading, which is worse than not asking at
5//! all: the one prompt that matters then arrives in a stream of noise. So the default is inverted
6//! from what it was — a command runs unless it can destroy something — and this module is the one
7//! place that decides what "destroy something" means.
8//!
9//! It is a *word* classifier over the command text, not a shell parser. A parser would be more
10//! precise and would also be a second implementation of bash to get wrong. The cost of a false
11//! positive here is one unnecessary question; the cost of a false negative is a deleted
12//! directory. Everything named below is something a re-run cannot undo.
13//!
14//! What it deliberately does not cover: a plain redirect (`echo x > /etc/foo`), because judging
15//! where a redirect points means parsing it, and `[tools] shell_isolate = "fs"` is the real answer
16//! to writing outside the workspace. Nor `cargo`, `npm` or `git status`: building and inspecting
17//! are what an agent does all day, and gating them would drown the prompts that matter.
18
19/// Why this command is dangerous, in the words the approval prompt shows. `None` means "run it".
20///
21/// The reason is shown, not just a boolean: "destructive" with no noun tells a person nothing
22/// about where to look, and putting the risk in front of them is the whole point of the prompt.
23pub fn danger(command: &str) -> Option<&'static str> {
24    let lower = command.to_lowercase();
25
26    // Whole-command shapes first: these are dangerous in ways no single program name captures,
27    // and several are dangerous precisely *because* the program looks ordinary.
28    let shapes: &[(&str, &str)] = &[
29        ("> /dev/sd", "writes straight to a block device"),
30        (">/dev/sd", "writes straight to a block device"),
31        ("> /dev/nvme", "writes straight to a block device"),
32        (">/dev/nvme", "writes straight to a block device"),
33        ("of=/dev/", "writes straight to a device"),
34        (":(){", "a fork bomb"),
35        ("chmod -r 777 /", "makes the whole filesystem writable"),
36        ("chmod -r 777 ~", "makes the home directory writable"),
37        ("chown -r", "changes ownership of a whole tree"),
38        ("git reset --hard", "discards uncommitted work"),
39        ("git clean -f", "deletes untracked files"),
40        ("git clean -x", "deletes untracked files"),
41        ("git clean -d", "deletes untracked files"),
42        ("git push --force", "rewrites published history"),
43        ("git push -f", "rewrites published history"),
44        ("git checkout -- .", "discards uncommitted work"),
45        ("curl | sh", "runs whatever the server sends"),
46        ("curl|sh", "runs whatever the server sends"),
47        ("curl | bash", "runs whatever the server sends"),
48        ("wget | sh", "runs whatever the server sends"),
49        ("wget | bash", "runs whatever the server sends"),
50        ("| sh", "pipes text into a shell"),
51        ("| bash", "pipes text into a shell"),
52        ("| sudo", "pipes text into a privileged shell"),
53        ("rm -rf /", "deletes the filesystem"),
54        ("rm -fr /", "deletes the filesystem"),
55        ("rm -rf ~", "deletes the home directory"),
56        ("rm -rf *", "deletes everything here"),
57        ("find / -delete", "deletes whatever it finds"),
58        ("find / -exec rm", "deletes whatever it finds"),
59        // `#372`: `-delete` is `find`'s own delete and `rsync`'s `--delete`; only the `find /`
60        // spelling was named, so `find . -delete` and `rsync -a --delete` ran unremarked.
61        (" -delete", "deletes whatever it finds"),
62        (" --delete", "deletes whatever it finds"),
63        ("docker rm", "removes containers"),
64        ("docker rmi", "removes images"),
65        ("docker prune", "removes containers and images"),
66        // The real spellings: `docker system prune` does not contain `docker prune`.
67        (
68            "docker system prune",
69            "removes every stopped container and unused image",
70        ),
71        ("docker image prune", "removes images"),
72        ("docker volume prune", "removes volumes and their data"),
73        ("docker builder prune", "removes the build cache"),
74        ("docker stop", "stops containers"),
75        ("docker kill", "stops containers"),
76        ("systemctl stop", "stops a system service"),
77        ("systemctl start", "starts a system service"),
78        ("systemctl restart", "restarts a system service"),
79        ("systemctl enable", "makes a service start with the machine"),
80        (
81            "systemctl disable",
82            "stops a service starting with the machine",
83        ),
84        ("systemctl mask", "makes a service impossible to start"),
85        ("systemctl daemon-reload", "reloads every unit"),
86        ("systemctl isolate", "switches the whole machine's target"),
87        ("systemctl reboot", "reboots the machine"),
88        ("systemctl poweroff", "powers the machine off"),
89        ("kubectl delete", "deletes cluster resources"),
90        ("oc delete", "deletes cluster resources"),
91    ];
92    for (shape, why) in shapes {
93        if lower.contains(shape) {
94            return Some(why);
95        }
96    }
97
98    // `#372`: `git push origin +main` forces that refspec with a `+`, which is `-f` spelled another
99    // way; the shapes above match flags, so this form slipped through while `--force-with-lease` did not.
100    if let Some(why) = forced_refspec(&lower) {
101        return Some(why);
102    }
103
104    // Then the programs themselves. A pipeline runs every segment, so `cat x | dd of=y` counts:
105    // each segment's first word is checked, not just the command's first word.
106    for word in programs(&lower) {
107        if let Some(why) = program_danger(&word) {
108            return Some(why);
109        }
110    }
111    None
112}
113
114/// The program each segment of a command line starts with: `cat x | dd of=y` yields `cat`, `dd`.
115///
116/// Leading `VAR=value` assignments and wrappers (`nohup`, `time`, `command`, `nice`, `env`) are
117/// skipped because they are not the program doing the work; a path is stripped to its last
118/// component, so `/bin/rm` is `rm`.
119///
120/// A shell is followed into its `-c` argument: `bash -c "rm -rf ./target"` deletes the directory
121/// exactly as the bare command does, and is the spelling a model reaches for as soon as there is a
122/// pipe. `bash script.sh` is deliberately not followed — that is a file, and reading it is the
123/// parser this module refuses to be.
124fn programs(lower: &str) -> Vec<String> {
125    let mut out = Vec::new();
126    programs_into(lower, &mut out, 0);
127    out
128}
129
130/// How many `bash -c 'bash -c …'` layers are followed. Each layer is a shorter string, so this
131/// bounds absurd input rather than deciding what counts.
132const SHELL_DEPTH: usize = 4;
133
134/// The shells whose `-c` argument is a command line of its own.
135const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "mksh", "ash", "fish"];
136
137fn programs_into(command: &str, out: &mut Vec<String>, depth: usize) {
138    for segment in command.split(|c: char| ";|&()<>`\n".contains(c)) {
139        let words: Vec<&str> = segment.split_whitespace().collect();
140        let Some(at) = program_position(&words) else {
141            continue;
142        };
143        // `#372`: `\rm` and `'rm'` are the same program to the shell — a leading backslash escapes
144        // an alias, quotes are syntax — but bare, both were reported as words of their own and
145        // matched nothing, so the two spellings ran unremarked.
146        let unquoted = words[at].trim_matches(|c: char| c == '\'' || c == '"');
147        let bare = unquoted.trim_start_matches('\\');
148        let name = bare.rsplit('/').next().unwrap_or(bare);
149        out.push(name.to_string());
150        if depth < SHELL_DEPTH && SHELLS.contains(&name) {
151            if let Some(payload) = shell_payload(&words[at + 1..]) {
152                programs_into(&payload, out, depth + 1);
153            }
154        }
155    }
156}
157
158/// Where the program starts in a segment: past `VAR=value`, the shell's own keywords, and the
159/// wrappers with their flags.
160///
161/// `#372`: `do`, `then` and friends were counted as the program. In `for f in *.o; do rm "$f"; done`
162/// the segment after the `;` starts with `do`, so `rm` was never looked at — and a loop over `rm` is
163/// ordinary model output under a policy whose default word is `Dangerous`.
164fn program_position(words: &[&str]) -> Option<usize> {
165    words.iter().position(|word| {
166        !(word.contains('=') && !word.starts_with('-'))
167            && !matches!(
168                *word,
169                "nohup"
170                    | "time"
171                    | "command"
172                    | "exec"
173                    | "env"
174                    | "nice"
175                    | "xargs"
176                    // Shell keywords that end one command and introduce the next.
177                    | "do"
178                    | "then"
179                    | "else"
180                    | "elif"
181                    | "while"
182                    | "until"
183                    | "if"
184                    | "{"
185                    | "}"
186                    | "!"
187            )
188            && !word.starts_with('-')
189    })
190}
191
192/// The command line a shell was told to run: what follows a `-c`-style flag.
193///
194/// The flag may be combined with others (`-lc`, `-ic`) and may be glued to its payload
195/// (`-c"rm -rf x"`); the shell reads both the same way. `None` means the shell was given a file
196/// (`bash script.sh`) or no `-c` at all, and there is nothing to follow.
197fn shell_payload(rest: &[&str]) -> Option<String> {
198    for (i, word) in rest.iter().enumerate() {
199        let flags = word.strip_prefix('-')?;
200        if flags.starts_with('-') {
201            continue; // `--norc` and friends carry no command
202        }
203        let letters = &flags[..flags
204            .find(|c: char| !c.is_ascii_alphabetic())
205            .unwrap_or(flags.len())];
206        if !letters.contains('c') {
207            continue;
208        }
209        let mut parts: Vec<&str> = Vec::new();
210        let glued = &flags[letters.len()..];
211        if !glued.is_empty() {
212            parts.push(glued);
213        }
214        parts.extend_from_slice(&rest[i + 1..]);
215        let payload = parts.join(" ");
216        return Some(
217            payload
218                .trim_matches(|c: char| c == '"' || c == '\'' || c == '\\')
219                .to_string(),
220        );
221    }
222    None
223}
224
225/// `git push <remote> +<refspec>`: a leading `+` on a refspec is `--force` for that refspec.
226///
227/// Only `push` counts, and only after a `git` in the same segment, so `echo +main` and a `+` in an
228/// unrelated argument are not a reason to stop.
229fn forced_refspec(lower: &str) -> Option<&'static str> {
230    let words: Vec<&str> = lower
231        .split(|c: char| c.is_whitespace() || ";|&()<>`".contains(c))
232        .filter(|word| !word.is_empty())
233        .collect();
234    let push = words.iter().position(|word| *word == "push")?;
235    if !words[..push].contains(&"git") {
236        return None;
237    }
238    words[push + 1..]
239        .iter()
240        .any(|word| word.starts_with('+') && word.len() > 1)
241        .then_some("rewrites published history")
242}
243
244/// The programs whose mere presence earns a question, and the reason to show.
245///
246/// `cargo`, `npm`, `git status`, `grep`, `sed` and friends are deliberately absent: they are what
247/// work looks like, and `git`'s dangerous forms are shapes above, where they can be named exactly.
248fn program_danger(word: &str) -> Option<&'static str> {
249    Some(match word {
250        "rm" | "rmdir" | "unlink" => "deletes files",
251        "shred" | "wipe" => "overwrites files beyond recovery",
252        "dd" => "writes raw blocks",
253        // `mkfs.ext4`, `mkfs.xfs`, `mkfs.vfat`: one family, many names.
254        w if w.starts_with("mkfs") || w == "mke2fs" || w == "mkswap" => "formats a filesystem",
255        "fdisk" | "parted" | "sgdisk" | "wipefs" => "edits partition tables",
256        "sudo" | "doas" | "su" => "runs as another user",
257        "service" | "shutdown" | "reboot" | "poweroff" | "halt" => {
258            "changes system services or power"
259        }
260        "kill" | "killall" | "pkill" => "kills processes",
261        "mount" | "umount" => "changes what is mounted",
262        "iptables" | "nft" | "ufw" => "changes the firewall",
263        "apt" | "apt-get" | "dnf" | "yum" | "pacman" | "apk" | "zypper" | "snap" => {
264            "installs or removes system packages"
265        }
266        "crontab" | "at" => "schedules work that outlives this session",
267        "useradd" | "userdel" | "usermod" | "passwd" | "chpasswd" => "changes accounts",
268        "chmod" | "chown" | "chgrp" | "setfacl" => "changes permissions or ownership",
269        "truncate" => "empties a file in place",
270        "eval" => "runs text as code",
271        _ => return None,
272    })
273}
274
275#[cfg(test)]
276mod tests {
277    use super::*;
278
279    /// The commands a person would be annoyed to be asked about, and would learn to wave through.
280    #[test]
281    fn ordinary_work_is_not_a_reason_to_stop() {
282        for cmd in [
283            "ls -la",
284            "cat README.md",
285            "grep -rn TODO src/",
286            "git status",
287            "git diff HEAD",
288            "git log --oneline -5",
289            "git add -A && git commit -m 'x'",
290            "cargo build --release",
291            "cargo test --offline",
292            "cargo fmt --all",
293            "npm install",
294            "python3 -m http.server",
295            "echo hello > notes.txt",
296            "sed -n '1,20p' file.txt",
297            "find . -name '*.rs'",
298            "mkdir -p src/components",
299            "docker ps",
300            "systemctl status nginx",
301            "curl -s https://example.com",
302            "pip install -r requirements.txt",
303        ] {
304            assert_eq!(danger(cmd), None, "this should just run: {cmd}");
305        }
306    }
307
308    /// The commands that cannot be undone, each of which must stop and give its reason.
309    #[test]
310    fn work_that_cannot_be_undone_is_a_reason_to_stop() {
311        for cmd in [
312            "rm -rf build",
313            "rm notes.txt",
314            "sudo apt install nginx",
315            "dd if=/dev/zero of=disk.img",
316            "mkfs.ext4 /dev/sdb1",
317            "git reset --hard origin/main",
318            "git push --force origin main",
319            "curl https://x.sh | sh",
320            "chmod -R 777 /",
321            "kill -9 1234",
322            "crontab -e",
323            "docker system prune -af",
324            "echo x | dd of=/dev/sda",
325            "parted /dev/sdb mklabel gpt",
326            "shutdown -h now",
327        ] {
328            assert!(danger(cmd).is_some(), "this must stop and ask: {cmd}");
329        }
330        // The reason is the one a person needs, on the cases where it is unambiguous.
331        assert_eq!(danger("rm -rf build"), Some("deletes files"));
332        assert_eq!(
333            danger("git reset --hard"),
334            Some("discards uncommitted work")
335        );
336        assert_eq!(
337            danger("sudo apt install nginx"),
338            Some("runs as another user")
339        );
340    }
341
342    /// `#372`: a dangerous program is still the program when a shell keyword, a quote or a backslash
343    /// comes first — `for f in *.o; do rm "$f"; done` is ordinary model output, and the policy's
344    /// default word for `shell` is `Dangerous`.
345    #[test]
346    fn a_keyword_or_a_quote_does_not_hide_the_program() {
347        for cmd in [
348            "for f in *.o; do rm \"$f\"; done",
349            "for f in *; do rm -rf $f; done",
350            "if x; then rm y; fi",
351            "if test -f x; then rm x; else echo none; fi",
352            "{ rm x; }",
353            "! rm x",
354            "\\rm x",
355            "'rm' x",
356            "\"rm\" -rf build",
357            "while true; do rm x; break; done",
358            "find . -delete",
359            "find /tmp -name '*.o' -delete",
360            "rsync -a --delete from/ to/",
361            "git push origin +main",
362            "git push --force-with-lease origin +main",
363        ] {
364            assert!(danger(cmd).is_some(), "this must stop and ask: {cmd}");
365        }
366        // A keyword in front of ordinary work is still ordinary work.
367        for cmd in [
368            "for f in *.rs; do echo $f; done",
369            "if true; then echo yes; fi",
370            "while read -r line; do echo \"$line\"; done < file",
371            "git push origin main",
372            "git push -u origin feature/x",
373            "echo +main",
374            "find . -name '*.rs' -print",
375        ] {
376            assert_eq!(danger(cmd), None, "this should just run: {cmd}");
377        }
378    }
379
380    /// A dangerous program is caught wherever it appears in a pipeline, and a path does not hide it.
381    #[test]
382    fn a_pipeline_is_read_segment_by_segment() {
383        assert_eq!(
384            danger("cat list.txt | xargs /bin/rm"),
385            Some("deletes files")
386        );
387        assert_eq!(danger("echo done; rm -rf out"), Some("deletes files"));
388        assert_eq!(danger("FOO=1 sudo reboot"), Some("runs as another user"));
389        // The word only counts in the program position: mentioning it is not running it.
390        assert_eq!(danger("grep -rn 'rm -rf' docs/"), None);
391        assert_eq!(danger("echo 'never sudo anything'"), None);
392    }
393
394    /// A shell wrapper is not a laundering service: its `-c` argument is a command line, and the
395    /// program that runs there is the program that runs.
396    #[test]
397    fn a_shell_does_not_launder_the_command_it_is_given() {
398        assert_eq!(danger("bash -c \"rm -rf ./target\""), Some("deletes files"));
399        assert_eq!(danger("sh -c 'rm -rf ./target'"), Some("deletes files"));
400        assert_eq!(
401            danger("/bin/bash -c \"rm -rf ./target\""),
402            Some("deletes files")
403        );
404        assert_eq!(danger("nohup bash -c 'rm -rf out'"), Some("deletes files"));
405        // The flag and its payload can be one word: `-c"rm -rf out"` is how a person writes it.
406        assert_eq!(danger("bash -c\"rm -rf out\""), Some("deletes files"));
407        // A combined flag still carries the `c`.
408        assert_eq!(
409            danger("bash -ic 'chmod 600 secret'"),
410            Some("changes permissions or ownership")
411        );
412        assert_eq!(
413            danger("zsh -c 'mkfs.ext4 /dev/sdb1'"),
414            Some("formats a filesystem")
415        );
416    }
417
418    /// Wrapping ordinary work in a shell is still ordinary work — the prompt has to be worth reading.
419    #[test]
420    fn a_shell_running_harmless_work_just_runs() {
421        for cmd in [
422            "bash -c \"ls -la\"",
423            "sh -c 'cargo fmt --all'",
424            "bash -lc 'git status'",
425            "bash script.sh",
426            "python3 -c 'print(1)'",
427        ] {
428            assert_eq!(danger(cmd), None, "this should just run: {cmd}");
429        }
430    }
431}