pub fn danger(command: &str) -> Option<&'static str> {
let lower = command.to_lowercase();
let shapes: &[(&str, &str)] = &[
("> /dev/sd", "writes straight to a block device"),
(">/dev/sd", "writes straight to a block device"),
("> /dev/nvme", "writes straight to a block device"),
(">/dev/nvme", "writes straight to a block device"),
("of=/dev/", "writes straight to a device"),
(":(){", "a fork bomb"),
("chmod -r 777 /", "makes the whole filesystem writable"),
("chmod -r 777 ~", "makes the home directory writable"),
("chown -r", "changes ownership of a whole tree"),
("git reset --hard", "discards uncommitted work"),
("git clean -f", "deletes untracked files"),
("git clean -x", "deletes untracked files"),
("git clean -d", "deletes untracked files"),
("git push --force", "rewrites published history"),
("git push -f", "rewrites published history"),
("git checkout -- .", "discards uncommitted work"),
("curl | sh", "runs whatever the server sends"),
("curl|sh", "runs whatever the server sends"),
("curl | bash", "runs whatever the server sends"),
("wget | sh", "runs whatever the server sends"),
("wget | bash", "runs whatever the server sends"),
("| sh", "pipes text into a shell"),
("| bash", "pipes text into a shell"),
("| sudo", "pipes text into a privileged shell"),
("rm -rf /", "deletes the filesystem"),
("rm -fr /", "deletes the filesystem"),
("rm -rf ~", "deletes the home directory"),
("rm -rf *", "deletes everything here"),
("find / -delete", "deletes whatever it finds"),
("find / -exec rm", "deletes whatever it finds"),
(" -delete", "deletes whatever it finds"),
(" --delete", "deletes whatever it finds"),
("docker rm", "removes containers"),
("docker rmi", "removes images"),
("docker prune", "removes containers and images"),
(
"docker system prune",
"removes every stopped container and unused image",
),
("docker image prune", "removes images"),
("docker volume prune", "removes volumes and their data"),
("docker builder prune", "removes the build cache"),
("docker stop", "stops containers"),
("docker kill", "stops containers"),
("systemctl stop", "stops a system service"),
("systemctl start", "starts a system service"),
("systemctl restart", "restarts a system service"),
("systemctl enable", "makes a service start with the machine"),
(
"systemctl disable",
"stops a service starting with the machine",
),
("systemctl mask", "makes a service impossible to start"),
("systemctl daemon-reload", "reloads every unit"),
("systemctl isolate", "switches the whole machine's target"),
("systemctl reboot", "reboots the machine"),
("systemctl poweroff", "powers the machine off"),
("kubectl delete", "deletes cluster resources"),
("oc delete", "deletes cluster resources"),
];
for (shape, why) in shapes {
if lower.contains(shape) {
return Some(why);
}
}
if let Some(why) = forced_refspec(&lower) {
return Some(why);
}
for word in programs(&lower) {
if let Some(why) = program_danger(&word) {
return Some(why);
}
}
None
}
fn programs(lower: &str) -> Vec<String> {
let mut out = Vec::new();
programs_into(lower, &mut out, 0);
out
}
const SHELL_DEPTH: usize = 4;
const SHELLS: &[&str] = &["sh", "bash", "zsh", "dash", "ksh", "mksh", "ash", "fish"];
fn programs_into(command: &str, out: &mut Vec<String>, depth: usize) {
for segment in command.split(|c: char| ";|&()<>`\n".contains(c)) {
let words: Vec<&str> = segment.split_whitespace().collect();
let Some(at) = program_position(&words) else {
continue;
};
let unquoted = words[at].trim_matches(|c: char| c == '\'' || c == '"');
let bare = unquoted.trim_start_matches('\\');
let name = bare.rsplit('/').next().unwrap_or(bare);
out.push(name.to_string());
if depth < SHELL_DEPTH && SHELLS.contains(&name) {
if let Some(payload) = shell_payload(&words[at + 1..]) {
programs_into(&payload, out, depth + 1);
}
}
}
}
fn program_position(words: &[&str]) -> Option<usize> {
words.iter().position(|word| {
!(word.contains('=') && !word.starts_with('-'))
&& !matches!(
*word,
"nohup"
| "time"
| "command"
| "exec"
| "env"
| "nice"
| "xargs"
| "do"
| "then"
| "else"
| "elif"
| "while"
| "until"
| "if"
| "{"
| "}"
| "!"
)
&& !word.starts_with('-')
})
}
fn shell_payload(rest: &[&str]) -> Option<String> {
for (i, word) in rest.iter().enumerate() {
let flags = word.strip_prefix('-')?;
if flags.starts_with('-') {
continue; }
let letters = &flags[..flags
.find(|c: char| !c.is_ascii_alphabetic())
.unwrap_or(flags.len())];
if !letters.contains('c') {
continue;
}
let mut parts: Vec<&str> = Vec::new();
let glued = &flags[letters.len()..];
if !glued.is_empty() {
parts.push(glued);
}
parts.extend_from_slice(&rest[i + 1..]);
let payload = parts.join(" ");
return Some(
payload
.trim_matches(|c: char| c == '"' || c == '\'' || c == '\\')
.to_string(),
);
}
None
}
fn forced_refspec(lower: &str) -> Option<&'static str> {
let words: Vec<&str> = lower
.split(|c: char| c.is_whitespace() || ";|&()<>`".contains(c))
.filter(|word| !word.is_empty())
.collect();
let push = words.iter().position(|word| *word == "push")?;
if !words[..push].contains(&"git") {
return None;
}
words[push + 1..]
.iter()
.any(|word| word.starts_with('+') && word.len() > 1)
.then_some("rewrites published history")
}
fn program_danger(word: &str) -> Option<&'static str> {
Some(match word {
"rm" | "rmdir" | "unlink" => "deletes files",
"shred" | "wipe" => "overwrites files beyond recovery",
"dd" => "writes raw blocks",
w if w.starts_with("mkfs") || w == "mke2fs" || w == "mkswap" => "formats a filesystem",
"fdisk" | "parted" | "sgdisk" | "wipefs" => "edits partition tables",
"sudo" | "doas" | "su" => "runs as another user",
"service" | "shutdown" | "reboot" | "poweroff" | "halt" => {
"changes system services or power"
}
"kill" | "killall" | "pkill" => "kills processes",
"mount" | "umount" => "changes what is mounted",
"iptables" | "nft" | "ufw" => "changes the firewall",
"apt" | "apt-get" | "dnf" | "yum" | "pacman" | "apk" | "zypper" | "snap" => {
"installs or removes system packages"
}
"crontab" | "at" => "schedules work that outlives this session",
"useradd" | "userdel" | "usermod" | "passwd" | "chpasswd" => "changes accounts",
"chmod" | "chown" | "chgrp" | "setfacl" => "changes permissions or ownership",
"truncate" => "empties a file in place",
"eval" => "runs text as code",
_ => return None,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ordinary_work_is_not_a_reason_to_stop() {
for cmd in [
"ls -la",
"cat README.md",
"grep -rn TODO src/",
"git status",
"git diff HEAD",
"git log --oneline -5",
"git add -A && git commit -m 'x'",
"cargo build --release",
"cargo test --offline",
"cargo fmt --all",
"npm install",
"python3 -m http.server",
"echo hello > notes.txt",
"sed -n '1,20p' file.txt",
"find . -name '*.rs'",
"mkdir -p src/components",
"docker ps",
"systemctl status nginx",
"curl -s https://example.com",
"pip install -r requirements.txt",
] {
assert_eq!(danger(cmd), None, "this should just run: {cmd}");
}
}
#[test]
fn work_that_cannot_be_undone_is_a_reason_to_stop() {
for cmd in [
"rm -rf build",
"rm notes.txt",
"sudo apt install nginx",
"dd if=/dev/zero of=disk.img",
"mkfs.ext4 /dev/sdb1",
"git reset --hard origin/main",
"git push --force origin main",
"curl https://x.sh | sh",
"chmod -R 777 /",
"kill -9 1234",
"crontab -e",
"docker system prune -af",
"echo x | dd of=/dev/sda",
"parted /dev/sdb mklabel gpt",
"shutdown -h now",
] {
assert!(danger(cmd).is_some(), "this must stop and ask: {cmd}");
}
assert_eq!(danger("rm -rf build"), Some("deletes files"));
assert_eq!(
danger("git reset --hard"),
Some("discards uncommitted work")
);
assert_eq!(
danger("sudo apt install nginx"),
Some("runs as another user")
);
}
#[test]
fn a_keyword_or_a_quote_does_not_hide_the_program() {
for cmd in [
"for f in *.o; do rm \"$f\"; done",
"for f in *; do rm -rf $f; done",
"if x; then rm y; fi",
"if test -f x; then rm x; else echo none; fi",
"{ rm x; }",
"! rm x",
"\\rm x",
"'rm' x",
"\"rm\" -rf build",
"while true; do rm x; break; done",
"find . -delete",
"find /tmp -name '*.o' -delete",
"rsync -a --delete from/ to/",
"git push origin +main",
"git push --force-with-lease origin +main",
] {
assert!(danger(cmd).is_some(), "this must stop and ask: {cmd}");
}
for cmd in [
"for f in *.rs; do echo $f; done",
"if true; then echo yes; fi",
"while read -r line; do echo \"$line\"; done < file",
"git push origin main",
"git push -u origin feature/x",
"echo +main",
"find . -name '*.rs' -print",
] {
assert_eq!(danger(cmd), None, "this should just run: {cmd}");
}
}
#[test]
fn a_pipeline_is_read_segment_by_segment() {
assert_eq!(
danger("cat list.txt | xargs /bin/rm"),
Some("deletes files")
);
assert_eq!(danger("echo done; rm -rf out"), Some("deletes files"));
assert_eq!(danger("FOO=1 sudo reboot"), Some("runs as another user"));
assert_eq!(danger("grep -rn 'rm -rf' docs/"), None);
assert_eq!(danger("echo 'never sudo anything'"), None);
}
#[test]
fn a_shell_does_not_launder_the_command_it_is_given() {
assert_eq!(danger("bash -c \"rm -rf ./target\""), Some("deletes files"));
assert_eq!(danger("sh -c 'rm -rf ./target'"), Some("deletes files"));
assert_eq!(
danger("/bin/bash -c \"rm -rf ./target\""),
Some("deletes files")
);
assert_eq!(danger("nohup bash -c 'rm -rf out'"), Some("deletes files"));
assert_eq!(danger("bash -c\"rm -rf out\""), Some("deletes files"));
assert_eq!(
danger("bash -ic 'chmod 600 secret'"),
Some("changes permissions or ownership")
);
assert_eq!(
danger("zsh -c 'mkfs.ext4 /dev/sdb1'"),
Some("formats a filesystem")
);
}
#[test]
fn a_shell_running_harmless_work_just_runs() {
for cmd in [
"bash -c \"ls -la\"",
"sh -c 'cargo fmt --all'",
"bash -lc 'git status'",
"bash script.sh",
"python3 -c 'print(1)'",
] {
assert_eq!(danger(cmd), None, "this should just run: {cmd}");
}
}
}