1pub fn danger(command: &str) -> Option<&'static str> {
24 let lower = command.to_lowercase();
25
26 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 (" -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 (
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 if let Some(why) = forced_refspec(&lower) {
101 return Some(why);
102 }
103
104 for word in programs(&lower) {
107 if let Some(why) = program_danger(&word) {
108 return Some(why);
109 }
110 }
111 None
112}
113
114fn programs(lower: &str) -> Vec<String> {
125 let mut out = Vec::new();
126 programs_into(lower, &mut out, 0);
127 out
128}
129
130const SHELL_DEPTH: usize = 4;
133
134const 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 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
158fn 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 | "do"
178 | "then"
179 | "else"
180 | "elif"
181 | "while"
182 | "until"
183 | "if"
184 | "{"
185 | "}"
186 | "!"
187 )
188 && !word.starts_with('-')
189 })
190}
191
192fn 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; }
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
225fn 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
244fn 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 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 #[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 #[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 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 #[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 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 #[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 assert_eq!(danger("grep -rn 'rm -rf' docs/"), None);
391 assert_eq!(danger("echo 'never sudo anything'"), None);
392 }
393
394 #[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 assert_eq!(danger("bash -c\"rm -rf out\""), Some("deletes files"));
407 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 #[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}