From dac5cae8d8e235cf643cc60874754332169b506c Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Fri, 4 Dec 2026 21:50:53 +0000 Subject: [PATCH 1/8] feat(core): rate more destructive commands red and add secret paths (#1725) Co-Authored-By: Claude Sonnet 5.5 --- ...-risk-more-destructive-and-secret-paths.md | 2 + .../action_exec/tests_red_risk.rs | 46 +++++ crates/core/src/risk/mod.rs | 2 + crates/core/src/risk/patterns.rs | 158 ++++++++++++++++++ .../src/risk/tests_destructive_families.rs | 120 +++++++++++++ docs/specs/0026-command-risk-indicators.md | 11 +- .../0068-security-hardening-prelaunch.md | 5 +- 7 files changed, 341 insertions(+), 3 deletions(-) create mode 100644 changelog.d/issue-1725-risk-more-destructive-and-secret-paths.md create mode 100644 crates/core/src/risk/tests_destructive_families.rs diff --git a/changelog.d/issue-1725-risk-more-destructive-and-secret-paths.md b/changelog.d/issue-1725-risk-more-destructive-and-secret-paths.md new file mode 100644 index 000000000..4c47f0286 --- /dev/null +++ b/changelog.d/issue-1725-risk-more-destructive-and-secret-paths.md @@ -0,0 +1,2 @@ +### Security +- More destructive commands (e.g. `shred`, `wipefs`, `find -delete`, `zfs destroy`, SQL `DROP TABLE`) are now rated red and ask for confirmation, and more credential files (Terraform state, KeePass, Azure and gcloud credentials) count as secret paths. diff --git a/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs b/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs index b9eb0a0ad..e48cb07aa 100644 --- a/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs +++ b/crates/app-logic/src/orchestration/action_exec/tests_red_risk.rs @@ -778,3 +778,49 @@ fn test_red_risk_reason_escalates_even_without_a_pattern_reason() { Some("Server-Risiko rot: rot eingestuft") ); } + +// --- Issue #1725: new destructive families / secret paths --------------- + +async fn decision_code_for(command: &str) -> (Decision, serde_json::Value) { + let session = red_risk_session(MockSshTransport::default().with_response(command, output(""))); + tokio::time::timeout( + std::time::Duration::from_secs(5), + proposed_decision_code( + &session, + AiAction::SuggestCommand { + command: command.to_string(), + }, + ), + ) + .await + .expect("Dialog muss enden") +} + +/// Issue #1725: a newly red destructive command still asks despite an +/// allow-everything rule. +#[tokio::test] +async fn test_new_destructive_family_requires_confirmation_despite_allow_rule() { + let command = "wipefs -a /dev/sdb"; + let (decision, payload) = decision_code_for(command).await; + assert!( + matches!(&decision, Decision::Confirm { code, .. } + if code == "FILTER_RED_RISK_REQUIRES_CONFIRM"), + "{payload}" + ); + assert!( + confirm_reason(&payload).contains("wipefs"), + "{}", + confirm_reason(&payload) + ); +} + +/// Issue #1725: a newly added secret path asks despite an allow rule. +#[tokio::test] +async fn test_new_secret_path_requires_confirmation_despite_allow_rule() { + let (decision, payload) = decision_code_for("cat infra/terraform.tfstate").await; + assert!( + matches!(&decision, Decision::Confirm { code, .. } + if code == "FILTER_SECRET_PATH_READ_REQUIRES_CONFIRM"), + "{payload}" + ); +} diff --git a/crates/core/src/risk/mod.rs b/crates/core/src/risk/mod.rs index fc8246d80..963faad14 100644 --- a/crates/core/src/risk/mod.rs +++ b/crates/core/src/risk/mod.rs @@ -34,6 +34,8 @@ mod sudo_options; #[cfg(test)] mod tests_chaining; #[cfg(test)] +mod tests_destructive_families; +#[cfg(test)] mod tests_sftp_server_args; #[cfg(test)] mod tests_ssh_key_names; diff --git a/crates/core/src/risk/patterns.rs b/crates/core/src/risk/patterns.rs index 740f80430..52d08b3cf 100644 --- a/crates/core/src/risk/patterns.rs +++ b/crates/core/src/risk/patterns.rs @@ -133,6 +133,12 @@ pub(super) const SECRET_FILE_CANDIDATES: &[&str] = &[ "x.p12", "x.pfx", "x.jks", + // Issue #1725 + "x.tfstate", + "x.kdbx", + ".s3cfg", + "application_default_credentials.json", + "credentials.tfrc.json", "ssh_host_ed25519_key", "ssh_host_rsa_key", "ssh_host_ecdsa_key", @@ -149,6 +155,8 @@ pub(super) const SECRET_RELATIVE_PREFIXES: &[&str] = &[ "~/.kube/", "~/.docker/", "~/.config/gh/", + "~/.azure/", + "~/.terraform.d/", "/etc/ssh/", "/etc/ssl/private/", ]; @@ -239,6 +247,29 @@ pub(super) fn secret_path_patterns() -> &'static [(regex::Regex, &'static str)] (r"\.netrc\b", "Liest ~/.netrc (Zugangsdaten)"), (r"\.pgpass\b", "Liest ~/.pgpass (Datenbank-Passwörter)"), (r"\.git-credentials\b", "Liest ~/.git-credentials"), + // Issue #1725 + ( + r"\.tfstate\b", + "Liest einen Terraform-State (.tfstate, enthält Secrets im Klartext)", + ), + (r"\.kdbx\b", "Liest eine KeePass-Datenbank (.kdbx)"), + (r"\.s3cfg\b", "Liest s3cmd-Zugangsdaten (~/.s3cfg)"), + ( + r"\.azure/", + "Liest Azure-CLI-Zugangsdaten/Token (~/.azure/)", + ), + ( + r"application_default_credentials\.json", + "Liest gcloud-Zugangsdaten (application_default_credentials.json)", + ), + ( + r"legacy_credentials/", + "Liest gcloud-Zugangsdaten (legacy_credentials/)", + ), + ( + r"credentials\.tfrc\.json", + "Liest Terraform-Zugangsdaten (credentials.tfrc.json)", + ), ] .into_iter() .map(|(pattern, reason)| { @@ -278,6 +309,14 @@ pub(super) const SECRET_PATH_HINTS: &[&str] = &[ ".p12", ".pfx", ".jks", + // Issue #1725 + "tfstate", + ".kdbx", + "s3cfg", + ".azure", + "application_default_credentials", + "legacy_credentials", + "credentials.tfrc", ]; /// Aufruf von `sftp-server` am Anfang eines Teilkommandos, direkt oder per @@ -292,6 +331,15 @@ pub(super) const SFTP_SERVER_INVOCATION: &str = concat!( r"(?:\S*/)?sftp-server(?:\s|$)" ); +/// Issue #1725: a SQL client word and a data-destroying statement in either +/// order. `\b` keeps `mysqldump` and similar names from counting as clients. +const SQL_DESTRUCTIVE: &str = concat!( + r"(?:\b(?:mysql|mariadb|psql|sqlite3|sqlcmd|sqlplus|usql|mycli|pgcli|litecli|duckdb|cqlsh|clickhouse-client|snowsql)\b.*", + r"\b(?:drop\s+(?:database|schema|table)|truncate\s+table)\b)", + r"|(?:\b(?:drop\s+(?:database|schema|table)|truncate\s+table)\b.*", + r"\b(?:mysql|mariadb|psql|sqlite3|sqlcmd|sqlplus|usql|mycli|pgcli|litecli|duckdb|cqlsh|clickhouse-client|snowsql)\b)" +); + pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static str)] { static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -388,6 +436,87 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static RiskLevel::Red, "Rechte werden rekursiv auf 777 gesetzt", ), + // Issue #1725: further destructive families. Each regex is + // anchored to the command word (optionally path-qualified); the + // classifier tries every segment and its sudo/wrapper-resolved + // form, so `sudo shred x`, `bash -c "shred x"` and chained + // segments are covered. + ( + Regex(r"^(?:\S*/)?shred(?:\s|$)".to_string()), + RiskLevel::Red, + "Überschreibt Dateien/Geräte unwiederbringlich (shred)", + ), + ( + Regex(r"^(?:\S*/)?wipefs(?:\s|$)".to_string()), + RiskLevel::Red, + "Löscht Dateisystem-Signaturen (wipefs)", + ), + ( + Regex( + r"^(?:\S*/)?truncate\s(?:.*\s)?(?:-[a-z]*s|--size)(?:[^a-z-]|$)".to_string(), + ), + RiskLevel::Red, + "Setzt die Dateigröße und verwirft Inhalt (truncate -s)", + ), + ( + Regex(r"^(?:\S*/)?find\s(?:.*\s)?-delete(?:\s|$)".to_string()), + RiskLevel::Red, + "Löscht alle Treffer von find (find -delete)", + ), + ( + Regex(r"^(?:\S*/)?blkdiscard(?:\s|$)".to_string()), + RiskLevel::Red, + "Verwirft Blöcke eines Geräts (blkdiscard)", + ), + ( + Regex( + r"^(?:\S*/)?sgdisk\s(?:.*\s)?(?:--zap(?:-all)?|-z)(?:\s|$)".to_string(), + ), + RiskLevel::Red, + "Zerstört die Partitionstabelle (sgdisk --zap)", + ), + ( + Regex(r"^(?:\S*/)?mke2fs(?:\s|$)".to_string()), + RiskLevel::Red, + "Dateisystem neu erstellen (mke2fs)", + ), + ( + Regex(r"^(?:\S*/)?mkswap(?:\s|$)".to_string()), + RiskLevel::Red, + "Überschreibt ein Gerät mit Swap-Signatur (mkswap)", + ), + ( + Regex(r"^(?:\S*/)?(?:lv|vg|pv)remove(?:\s|$)".to_string()), + RiskLevel::Red, + "Entfernt LVM-Volumes/-Gruppen/-Geräte (lvremove/vgremove/pvremove)", + ), + ( + Regex(r"^(?:\S*/)?zpool\s(?:.*\s)?destroy(?:\s|$)".to_string()), + RiskLevel::Red, + "Zerstört einen ZFS-Pool (zpool destroy)", + ), + ( + Regex(r"^(?:\S*/)?zfs\s(?:.*\s)?destroy(?:\s|$)".to_string()), + RiskLevel::Red, + "Zerstört ein ZFS-Dataset (zfs destroy)", + ), + // `dd` with the target before the source (`dd of=/dev/sdb if=…`); + // the glob above only knows `if=` first. + ( + Regex(r"^(?:\S*/)?dd\s(?:.*\s)?of=/dev/".to_string()), + RiskLevel::Red, + "Direktes Schreiben auf ein Blockgerät (dd of=/dev/...)", + ), + // SQL statements that drop data, anywhere in a command that + // involves a SQL client (`mysql -e "…"`, `psql <<< "…"`, + // `echo "…" | psql`). A client word is required so that merely + // searching for the text (`grep -i "drop table" x.sql`) keeps its + // rating. + ( + Regex(SQL_DESTRUCTIVE.to_string()), + RiskLevel::Red, + "SQL-Anweisung löscht Daten (drop database/schema/table, truncate table)", + ), // --- Gelb: potenziell destruktiv, aber üblicherweise gezielt -- ( Glob("rm *".to_string()), @@ -433,6 +562,7 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static }) } +#[allow(clippy::too_many_lines)] // a flat pattern table pub(super) fn data_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static str)] { static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -554,6 +684,34 @@ pub(super) fn data_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static st RiskLevel::Red, "Zugriff auf ~/.git-credentials", ), + // Issue #1725 + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.tfstate\b")), + RiskLevel::Red, + "Zugriff auf einen Terraform-State (.tfstate)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.kdbx\b")), + RiskLevel::Red, + "Zugriff auf eine KeePass-Datenbank (.kdbx)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.s3cfg\b")), + RiskLevel::Red, + "Zugriff auf ~/.s3cfg", + ), + ( + Regex(format!( + "{READ_COMMAND_PREFIX}application_default_credentials\\.json" + )), + RiskLevel::Red, + "Zugriff auf gcloud-Zugangsdaten", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.azure/")), + RiskLevel::Red, + "Zugriff auf Azure-CLI-Zugangsdaten (~/.azure/)", + ), // --- Gelb: könnte auf Secrets hindeuten, aber nicht sicher ---- ( Glob("find*-name*.key*".to_string()), diff --git a/crates/core/src/risk/tests_destructive_families.rs b/crates/core/src/risk/tests_destructive_families.rs new file mode 100644 index 000000000..c85d85dce --- /dev/null +++ b/crates/core/src/risk/tests_destructive_families.rs @@ -0,0 +1,120 @@ +//! Issue #1725: more destructive command families are red, more credential +//! files count as secret paths. One positive and one near-miss per family. + +use super::classifier::{secret_path_read_reason, RuleBasedRiskClassifier}; +use super::types::RiskLevel; + +fn classify(command: &str) -> super::types::RiskAssessment { + RuleBasedRiskClassifier.classify(command) +} + +const FAMILIES: &[&str] = &[ + "shred -u /var/log/auth.log", + "wipefs -a /dev/sdb", + "truncate -s 0 /var/log/syslog", + "truncate -s0 /var/log/syslog", + "truncate --size=0 /var/log/syslog", + "truncate -c -s 10 /data/db", + "find /x -mtime +7 -delete", + "find . -delete", + "blkdiscard /dev/nvme0n1", + "sgdisk --zap-all /dev/sda", + "sgdisk --zap /dev/sda", + "sgdisk -Z /dev/sda", + "mke2fs /dev/sdb1", + "mkswap /dev/sdb2", + "lvremove -f vg/data", + "vgremove vg", + "pvremove /dev/sdb", + "zpool destroy tank", + "zfs destroy -r tank/data", + "dd of=/dev/sdb if=/tmp/img", + "dd bs=1M of=/dev/sdb if=/tmp/img", + "/usr/sbin/wipefs -a /dev/sdb", + "mysql -e \"DROP DATABASE shop\"", + "psql -c \"truncate table orders\"", + "psql -c 'DROP TABLE users'", + "mysql -e \"drop schema s\"", + "psql <<< \"drop table users;\"", + "echo \"drop table x\" | mysql", + "sqlite3 app.db 'DROP TABLE t'", +]; + +#[test] +fn each_family_is_red_plain_sudo_wrapped_and_chained() { + for base in FAMILIES { + let variants = [ + base.to_string(), + format!("sudo {base}"), + format!("bash -c \"{}\"", base.replace('"', "'")), + format!("ls /tmp && {base}"), + format!("echo done; {base}"), + ]; + for c in variants { + assert_eq!(classify(&c).server_risk, RiskLevel::Red, "{c}"); + } + } +} + +#[test] +fn near_misses_keep_their_rating() { + for (c, level) in [ + ("truncate --help", RiskLevel::None), + ("truncate -c /tmp/file", RiskLevel::None), + ("find . -name '*.log'", RiskLevel::None), + ("grep -- -delete notes.txt", RiskLevel::None), + ("zfs list", RiskLevel::None), + ("zpool status", RiskLevel::None), + ("sgdisk -p /dev/sda", RiskLevel::None), + ("dd if=/dev/sda of=/tmp/img", RiskLevel::None), + ("grep -i \"drop table\" migrations.sql", RiskLevel::None), + ("mysql -e \"select 1\"", RiskLevel::None), + ("mysqldump shop", RiskLevel::None), + ("lvs", RiskLevel::None), + ] { + let a = classify(c); + assert_ne!(a.server_risk, RiskLevel::Red, "{c}"); + assert_eq!(a.server_risk, level, "{c}"); + } +} + +const SECRET_FILES: &[&str] = &[ + "terraform.tfstate", + "terraform.tfstate.backup", + "db.kdbx", + "~/.s3cfg", + "gcloud/application_default_credentials.json", + "~/.azure/msal_token_cache.json", + "~/.config/gcloud/legacy_credentials/me@x.com/adc.json", + "~/.terraform.d/credentials.tfrc.json", +]; + +#[test] +fn new_secret_paths_escalate_on_read() { + for f in SECRET_FILES { + let c = format!("cat {f}"); + assert!(secret_path_read_reason(&c).is_some(), "{c}"); + let c = format!("sudo cat {f}"); + assert!(secret_path_read_reason(&c).is_some(), "{c}"); + } +} + +#[test] +fn listed_secret_files_rate_the_data_axis_red() { + for f in &SECRET_FILES[..6] { + let c = format!("cat {f}"); + assert_eq!(classify(&c).data_risk, RiskLevel::Red, "{c}"); + } +} + +#[test] +fn similar_names_are_not_secret_paths() { + for c in [ + "cat notes.txt", + "ls terraform.tfstate.d", + "cat my.tfstates", + "cat kdbx.md", + ] { + assert!(secret_path_read_reason(c).is_none(), "{c}"); + } +} diff --git a/docs/specs/0026-command-risk-indicators.md b/docs/specs/0026-command-risk-indicators.md index 6b8bf47cc..8ba183058 100644 --- a/docs/specs/0026-command-risk-indicators.md +++ b/docs/specs/0026-command-risk-indicators.md @@ -74,7 +74,13 @@ werden. **Beispiele Server-Risiko.** Rot: `rm -rf *`, `dd if=* of=/dev/*`, `mkfs*`, Fork-Bomb, `shutdown*`/`reboot*`/`poweroff*`, `iptables -F*`, -`chmod -R 777 /*`. Gelb: `rm *` (ohne `-rf`), `systemctl stop/restart *`, +`chmod -R 777 /*`; ebenso `shred`, `wipefs`, `truncate -s`/`--size`, +`find … -delete`, `blkdiscard`, `sgdisk --zap`/`--zap-all`/`-Z`, `mke2fs`, +`mkswap`, `lvremove`/`vgremove`/`pvremove`, `zpool destroy`, `zfs destroy`, +`dd` mit `of=/dev/…` in beliebiger Argument-Reihenfolge und die SQL-Anweisungen +`drop database`/`drop schema`/`drop table`/`truncate table` in einem Kommando +mit SQL-Client (`mysql`, `psql`, `sqlite3`, …; ein bloßes `grep "drop table"` +bleibt unbewertet). Gelb: `rm *` (ohne `-rf`), `systemctl stop/restart *`, `apt/yum remove *`, `git reset --hard*`, `kill *` (ohne PID 1). **Beispiele Daten-Risiko.** Rot: `cat`/`less`/`head`/`tail` auf jeden privaten SSH-Schlüssel @@ -82,7 +88,8 @@ Fork-Bomb, `shutdown*`/`reboot*`/`poweroff*`, `iptables -F*`, nur exakt `.pub` ist ausgenommen und hat kein Daten-Risiko — gleiche Regel wie die Secret-Pfad-Prüfung aus Spec 0068; auch ein Platzhalter, der so einen Namen treffen kann, etwa `id_*`, `backup_id_*`, `*backup_id_*`, `*_id_*` — dafür muss `id_` oder ein Schlüsseltyp wörtlich im -Muster stehen, `*`, `i*` oder `*id*` bleiben ohne Daten-Risiko), `*.pem`, `*.key`, `*.env`, `*credentials*`, `*shadow*`, `*.aws/credentials*`; +Muster stehen, `*`, `i*` oder `*id*` bleiben ohne Daten-Risiko), `*.pem`, `*.key`, `*.env`, `*credentials*`, `*shadow*`, `*.aws/credentials*`, `*.tfstate*`, `*.kdbx`, `*.s3cfg`, +`application_default_credentials.json`, `~/.azure/`; `env`/`printenv`; `mysqldump`/`pg_dump` ohne Ziel-Redaction; SQL mit `SELECT * FROM *user*`/`*password*`. Gelb: `find` mit `-name *.key`-artigen Mustern, `ls` in `~/.ssh` oder `/etc`, `grep` nach `password`/`secret`/`token` diff --git a/docs/specs/0068-security-hardening-prelaunch.md b/docs/specs/0068-security-hardening-prelaunch.md index caf93253b..b0f1eea9a 100644 --- a/docs/specs/0068-security-hardening-prelaunch.md +++ b/docs/specs/0068-security-hardening-prelaunch.md @@ -77,7 +77,10 @@ dass es **immer** eine Bestätigung verlangt. Werte), `/etc/shadow`, `/etc/gshadow`, `~/.aws/credentials`, `~/.docker/config.json`, `~/.kube/config`, `~/.netrc`, `~/.pgpass`, `~/.git-credentials`, `.npmrc`, `.pypirc`, `.my.cnf`, Vault-Token, GnuPG- - Schlüsselbund, private TLS-Schlüssel, Shell-Historien, Prozess-Umgebungen. + Schlüsselbund, Terraform-State (`*.tfstate`, `*.tfstate.backup`), + KeePass-Datenbanken (`*.kdbx`), `~/.s3cfg`, `~/.azure/`, gcloud + (`application_default_credentials.json`, `legacy_credentials/`), + `credentials.tfrc.json`, private TLS-Schlüssel, Shell-Historien, Prozess-Umgebungen. - **Befehle**, die Inhalt in die Ausgabe oder vom Server weg bringen: unter anderem `cat`, `less`, `head`, `tail`, `grep`, `sed`, `awk`, `xxd`, `od`, `strings`, `base64`, `openssl`, Editoren, Interpreter sowie `curl`, `wget`, From 0639fb704154e7571ea0c9967a202ef8ffbc73b9 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:24:37 +0000 Subject: [PATCH 2/8] fix(core): rate destructive SQL anywhere except read tools, close review gaps (#1725) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/risk/classifier.rs | 26 ++++++- crates/core/src/risk/patterns.rs | 72 ++++++++++--------- .../src/risk/tests_destructive_families.rs | 30 ++++++++ ...ructive-sql-rated-anywhere-in-a-command.md | 44 ++++++++++++ docs/adr/INDEX.md | 1 + docs/specs/0026-command-risk-indicators.md | 11 ++- 6 files changed, 145 insertions(+), 39 deletions(-) create mode 100644 docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index 88b7ba16f..d3c3fbd8f 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -7,7 +7,7 @@ use crate::filter::{ use super::patterns::{ data_risk_patterns, secret_path_patterns, server_risk_patterns, SECRET_FILE_CANDIDATES, SECRET_PATH_HINTS, SECRET_READ_COMMANDS, SECRET_RELATIVE_PREFIXES, SFTP_SERVER_INVOCATION, - SSH_KEY_GLOB_CANDIDATES, + SQL_DESTRUCTIVE, SQL_DESTRUCTIVE_REASON, SQL_READ_TOOL, SSH_KEY_GLOB_CANDIDATES, }; use super::sftp_word_check::{quoted_sftp_server_invocation, sftp_server_word_check, WordCheck}; use super::types::{RiskAssessment, RiskLevel}; @@ -170,6 +170,10 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat acc.data_risk_reason = Some(reason); } } + if acc.server_risk < RiskLevel::Red && destructive_sql(&lower) { + acc.server_risk = RiskLevel::Red; + acc.server_risk_reason = Some(SQL_DESTRUCTIVE_REASON); + } if acc.data_risk < RiskLevel::Red && glob_reads_private_key(&lower) { acc.data_risk = RiskLevel::Red; acc.data_risk_reason = @@ -216,6 +220,26 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat } } +/// Issue #1725 (ADR 0167): the segment contains a data-destroying SQL +/// statement and does not start with a search/read tool. The first word is +/// taken from the sudo/wrapper-resolved form, so `sudo grep -i "drop table" +/// x` is exempt like `grep`; a pipe or chain is rated per segment because the +/// caller passes every segment, and the whole command (which may start with +/// `grep`) cannot hide a later `| psql` segment. +fn destructive_sql(lower_segment: &str) -> bool { + static STATEMENT: std::sync::OnceLock = std::sync::OnceLock::new(); + static READ_TOOL: std::sync::OnceLock = std::sync::OnceLock::new(); + let statement = STATEMENT.get_or_init(|| { + regex::Regex::new(SQL_DESTRUCTIVE).expect("SQL_DESTRUCTIVE is a valid regex") + }); + if !statement.is_match(lower_segment) { + return false; + } + let read_tool = READ_TOOL + .get_or_init(|| regex::Regex::new(SQL_READ_TOOL).expect("SQL_READ_TOOL is a valid regex")); + !read_tool.is_match(resolve_effective_command(lower_segment).trim_start()) +} + /// Höchstes unter allen zutreffenden Mustern — ein Teilkommando kann /// gleichzeitig ein Rot- und ein Gelb-Muster treffen (z. B. `rm -rf /// /etc/shadow` träfe sowohl "rm -rf" als auch "shadow"), das strengere diff --git a/crates/core/src/risk/patterns.rs b/crates/core/src/risk/patterns.rs index 52d08b3cf..eccb318a3 100644 --- a/crates/core/src/risk/patterns.rs +++ b/crates/core/src/risk/patterns.rs @@ -209,6 +209,11 @@ pub(super) fn secret_path_patterns() -> &'static [(regex::Regex, &'static str)] "Liest MySQL-Wartungszugangsdaten (debian.cnf)", ), (r"\.aws/credentials", "Liest AWS-Zugangsdaten"), + // Before the generic entry, which would otherwise win the reason. + ( + r"credentials\.tfrc\.json", + "Liest Terraform-Zugangsdaten (credentials.tfrc.json)", + ), ( r"\bcredentials\b", "Liest eine Zugangsdaten-Datei (credentials)", @@ -266,10 +271,6 @@ pub(super) fn secret_path_patterns() -> &'static [(regex::Regex, &'static str)] r"legacy_credentials/", "Liest gcloud-Zugangsdaten (legacy_credentials/)", ), - ( - r"credentials\.tfrc\.json", - "Liest Terraform-Zugangsdaten (credentials.tfrc.json)", - ), ] .into_iter() .map(|(pattern, reason)| { @@ -309,14 +310,11 @@ pub(super) const SECRET_PATH_HINTS: &[&str] = &[ ".p12", ".pfx", ".jks", - // Issue #1725 + // Issue #1725 (the credential names are covered by "credentials") "tfstate", ".kdbx", "s3cfg", ".azure", - "application_default_credentials", - "legacy_credentials", - "credentials.tfrc", ]; /// Aufruf von `sftp-server` am Anfang eines Teilkommandos, direkt oder per @@ -331,15 +329,27 @@ pub(super) const SFTP_SERVER_INVOCATION: &str = concat!( r"(?:\S*/)?sftp-server(?:\s|$)" ); -/// Issue #1725: a SQL client word and a data-destroying statement in either -/// order. `\b` keeps `mysqldump` and similar names from counting as clients. -const SQL_DESTRUCTIVE: &str = concat!( - r"(?:\b(?:mysql|mariadb|psql|sqlite3|sqlcmd|sqlplus|usql|mycli|pgcli|litecli|duckdb|cqlsh|clickhouse-client|snowsql)\b.*", - r"\b(?:drop\s+(?:database|schema|table)|truncate\s+table)\b)", - r"|(?:\b(?:drop\s+(?:database|schema|table)|truncate\s+table)\b.*", - r"\b(?:mysql|mariadb|psql|sqlite3|sqlcmd|sqlplus|usql|mycli|pgcli|litecli|duckdb|cqlsh|clickhouse-client|snowsql)\b)" +/// Issue #1725 (ADR 0167): a data-destroying SQL statement anywhere in a +/// command. SQL comments may stand in for whitespace (`DROP/**/DATABASE`). +/// The statement is matched without regard to a SQL client, so unknown +/// clients are covered too; `SQL_READ_TOOL` is the only exemption. +pub(super) const SQL_DESTRUCTIVE: &str = concat!( + r"(?s)\b(?:drop(?:\s|/\*.*?\*/)+(?:database|schema|table)", + r"|truncate(?:\s|/\*.*?\*/)+table)\b" +); + +/// Issue #1725 (ADR 0167): first command word of a segment that only +/// searches or reads text (`grep -i "drop table" x.sql`); such a segment is +/// not rated for the SQL statement it mentions. `sed` counts only with `-n`. +pub(super) const SQL_READ_TOOL: &str = concat!( + r"^(?:\S*/)?(?:grep|egrep|fgrep|zgrep|rg|ag|ack|less|more|cat|zcat|head|tail|bat|awk|gawk", + r"|sed\s+(?:-[a-z]*n[a-z]*|--quiet|--silent))(?:\s|$)" ); +/// Reason shown for `SQL_DESTRUCTIVE`. +pub(super) const SQL_DESTRUCTIVE_REASON: &str = + "SQL-Anweisung löscht Daten (drop database/schema/table, truncate table)"; + pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static str)] { static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new(); @@ -436,11 +446,12 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static RiskLevel::Red, "Rechte werden rekursiv auf 777 gesetzt", ), - // Issue #1725: further destructive families. Each regex is - // anchored to the command word (optionally path-qualified); the - // classifier tries every segment and its sudo/wrapper-resolved - // form, so `sudo shred x`, `bash -c "shred x"` and chained - // segments are covered. + // Issue #1725: further destructive families. The regexes start + // at the command word (optionally path-qualified) and, where a + // family has sub-commands or options, look for them later in + // the segment; the classifier tries every segment and its + // sudo/wrapper-resolved form, so `sudo shred x`, + // `bash -c "shred x"` and chained segments are covered. ( Regex(r"^(?:\S*/)?shred(?:\s|$)".to_string()), RiskLevel::Red, @@ -453,7 +464,8 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static ), ( Regex( - r"^(?:\S*/)?truncate\s(?:.*\s)?(?:-[a-z]*s|--size)(?:[^a-z-]|$)".to_string(), + r"^(?:\S*/)?truncate\s(?:.*\s)?(?:-[a-z]*s|--si(?:z(?:e)?)?)(?:[^a-z]|$)" + .to_string(), ), RiskLevel::Red, "Setzt die Dateigröße und verwirft Inhalt (truncate -s)", @@ -470,7 +482,7 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static ), ( Regex( - r"^(?:\S*/)?sgdisk\s(?:.*\s)?(?:--zap(?:-all)?|-z)(?:\s|$)".to_string(), + r"^(?:\S*/)?sgdisk\s(?:.*\s)?(?:--zap(?:-all)?|-[a-z]*z[a-z]*)(?:\s|$)".to_string(), ), RiskLevel::Red, "Zerstört die Partitionstabelle (sgdisk --zap)", @@ -486,7 +498,7 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static "Überschreibt ein Gerät mit Swap-Signatur (mkswap)", ), ( - Regex(r"^(?:\S*/)?(?:lv|vg|pv)remove(?:\s|$)".to_string()), + Regex(r"^(?:\S*/)?(?:lvm\s+)?(?:lv|vg|pv)remove(?:\s|$)".to_string()), RiskLevel::Red, "Entfernt LVM-Volumes/-Gruppen/-Geräte (lvremove/vgremove/pvremove)", ), @@ -503,20 +515,10 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static // `dd` with the target before the source (`dd of=/dev/sdb if=…`); // the glob above only knows `if=` first. ( - Regex(r"^(?:\S*/)?dd\s(?:.*\s)?of=/dev/".to_string()), + Regex(r#"^(?:\S*/)?dd\s(?:.*\s)?["']?of=/dev/"#.to_string()), RiskLevel::Red, "Direktes Schreiben auf ein Blockgerät (dd of=/dev/...)", ), - // SQL statements that drop data, anywhere in a command that - // involves a SQL client (`mysql -e "…"`, `psql <<< "…"`, - // `echo "…" | psql`). A client word is required so that merely - // searching for the text (`grep -i "drop table" x.sql`) keeps its - // rating. - ( - Regex(SQL_DESTRUCTIVE.to_string()), - RiskLevel::Red, - "SQL-Anweisung löscht Daten (drop database/schema/table, truncate table)", - ), // --- Gelb: potenziell destruktiv, aber üblicherweise gezielt -- ( Glob("rm *".to_string()), @@ -562,7 +564,7 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static }) } -#[allow(clippy::too_many_lines)] // a flat pattern table +#[expect(clippy::too_many_lines, reason = "a flat pattern table")] pub(super) fn data_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static str)] { static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new(); diff --git a/crates/core/src/risk/tests_destructive_families.rs b/crates/core/src/risk/tests_destructive_families.rs index c85d85dce..745745b3c 100644 --- a/crates/core/src/risk/tests_destructive_families.rs +++ b/crates/core/src/risk/tests_destructive_families.rs @@ -15,21 +15,31 @@ const FAMILIES: &[&str] = &[ "truncate -s0 /var/log/syslog", "truncate --size=0 /var/log/syslog", "truncate -c -s 10 /data/db", + "truncate --siz=0 /var/log/syslog", + "truncate --si 0 /var/log/syslog", + "truncate -s-1G /data/db", "find /x -mtime +7 -delete", "find . -delete", "blkdiscard /dev/nvme0n1", "sgdisk --zap-all /dev/sda", "sgdisk --zap /dev/sda", "sgdisk -Z /dev/sda", + "sgdisk -Zo /dev/sda", + "sgdisk -oZ /dev/sda", "mke2fs /dev/sdb1", "mkswap /dev/sdb2", "lvremove -f vg/data", "vgremove vg", "pvremove /dev/sdb", + "lvm lvremove -f vg/data", + "lvm vgremove vg", + "lvm pvremove /dev/sdb", "zpool destroy tank", "zfs destroy -r tank/data", "dd of=/dev/sdb if=/tmp/img", "dd bs=1M of=/dev/sdb if=/tmp/img", + "dd \"of=/dev/sdb\" if=/tmp/img", + "dd 'of=/dev/sdb' if=/tmp/img", "/usr/sbin/wipefs -a /dev/sdb", "mysql -e \"DROP DATABASE shop\"", "psql -c \"truncate table orders\"", @@ -38,6 +48,14 @@ const FAMILIES: &[&str] = &[ "psql <<< \"drop table users;\"", "echo \"drop table x\" | mysql", "sqlite3 app.db 'DROP TABLE t'", + "mysqlsh -e \"drop database x\"", + "cockroach sql -e 'drop database x'", + "git commit -m 'drop table x'", + "echo \"drop table t\" | psql", + "grep x f | psql -c \"drop table t\"", + "grep x f; echo 'drop table t'", + "psql -c \"DROP/**/DATABASE x\"", + "psql -c \"drop\ttable t\"", ]; #[test] @@ -68,6 +86,18 @@ fn near_misses_keep_their_rating() { ("sgdisk -p /dev/sda", RiskLevel::None), ("dd if=/dev/sda of=/tmp/img", RiskLevel::None), ("grep -i \"drop table\" migrations.sql", RiskLevel::None), + ("grep -i 'drop table' mysql.log", RiskLevel::None), + ("sudo grep -i 'drop table' migrations.sql", RiskLevel::None), + ("rg -i 'truncate table' db/", RiskLevel::None), + ("ag 'drop schema' .", RiskLevel::None), + ( + "cat migrations.sql | grep -i 'drop database'", + RiskLevel::None, + ), + ("less migrations.sql # drop table", RiskLevel::None), + ("sed -n '/drop table/p' migrations.sql", RiskLevel::None), + ("awk '/drop table/' migrations.sql", RiskLevel::None), + ("head -n 5 drop_table.sql", RiskLevel::None), ("mysql -e \"select 1\"", RiskLevel::None), ("mysqldump shop", RiskLevel::None), ("lvs", RiskLevel::None), diff --git a/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md b/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md new file mode 100644 index 000000000..44d9f09da --- /dev/null +++ b/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md @@ -0,0 +1,44 @@ +# ADR 0167 — Destructive SQL is rated red anywhere in a command + +## Status + +Accepted + +Betrifft: Spec 0026, Issue #1725 + +## Problem + +`drop database`, `drop schema`, `drop table` and `truncate table` destroy +data, but the classifier only sees the command text, not which program runs +the SQL. A first version required one of 14 SQL client words in the same +command. That missed `mysqlsh`, `cockroach sql`, `trino`, `beeline` and every +client nobody listed, and it rated `grep -i 'drop table' mysql.log` red. + +## Decision + +1. The statement is matched anywhere in a command, without regard to a + client (comments may replace whitespace: `DROP/**/DATABASE`). +2. A segment is exempt only when its first command word (after + sudo/wrapper resolution) is a search or read tool: `grep`, `egrep`, + `fgrep`, `zgrep`, `rg`, `ag`, `ack`, `less`, `more`, `cat`, `zcat`, + `head`, `tail`, `bat`, `awk`, `gawk`, `sed -n`. +3. The exemption is per segment. The classifier rates every segment and the + whole command; the whole command may start with `grep` and so be exempt, + while a later `| psql -c "drop table t"` segment is still rated red. + +## Accepted consequences + +- False positives ask for a confirmation: `echo … > file`, `git commit -m + "drop table x"`, editor calls, and `bash -c "grep … 'drop table' …"` + (the wrapper hides the first word of the outer segment). +- False negatives remain where the statement is built at run time + (`psql -c "$(printf 'dr%s' 'op table t')"`) or hidden in an `awk`/`sed -n` + program, because the classifier is a text check and the filter engine still + applies. `truncate ` without `table`, `mysqladmin drop` and `dropdb` + are not covered. + +## `find -delete` + +Its pattern is anchored to the command word `find` (optionally +path-qualified) and looks for `-delete` as a later whole argument, so +`grep -- -delete notes.txt` and `find . -name '*.log'` stay unrated. diff --git a/docs/adr/INDEX.md b/docs/adr/INDEX.md index 2e0cbf769..47e831243 100644 --- a/docs/adr/INDEX.md +++ b/docs/adr/INDEX.md @@ -169,3 +169,4 @@ | 0163 | License change Apache-2.0 → GPL-3.0-only | Accepted | [0163-license-change-gpl-3-0-only.md](0163-license-change-gpl-3-0-only.md) | | 0164 | ONNX Runtime license texts are committed, not taken from a crate | Accepted | [0164-onnx-runtime-license-texts-committed.md](0164-onnx-runtime-license-texts-committed.md) | | 0165 | AI provider kinds contributed by the embedding application | Accepted | [0165-ai-provider-kinds-from-the-embedding-app.md](0165-ai-provider-kinds-from-the-embedding-app.md) | +| 0167 | Destructive SQL is rated red anywhere in a command | Accepted | [0167-destructive-sql-rated-anywhere-in-a-command.md](0167-destructive-sql-rated-anywhere-in-a-command.md) | diff --git a/docs/specs/0026-command-risk-indicators.md b/docs/specs/0026-command-risk-indicators.md index 8ba183058..8bc55c1ad 100644 --- a/docs/specs/0026-command-risk-indicators.md +++ b/docs/specs/0026-command-risk-indicators.md @@ -78,9 +78,14 @@ Fork-Bomb, `shutdown*`/`reboot*`/`poweroff*`, `iptables -F*`, `find … -delete`, `blkdiscard`, `sgdisk --zap`/`--zap-all`/`-Z`, `mke2fs`, `mkswap`, `lvremove`/`vgremove`/`pvremove`, `zpool destroy`, `zfs destroy`, `dd` mit `of=/dev/…` in beliebiger Argument-Reihenfolge und die SQL-Anweisungen -`drop database`/`drop schema`/`drop table`/`truncate table` in einem Kommando -mit SQL-Client (`mysql`, `psql`, `sqlite3`, …; ein bloßes `grep "drop table"` -bleibt unbewertet). Gelb: `rm *` (ohne `-rf`), `systemctl stop/restart *`, +`drop database`/`drop schema`/`drop table`/`truncate table` an jeder Stelle eines +Kommandos, auch mit unbekanntem SQL-Client. Ausgenommen ist nur ein Teilkommando, +dessen erstes Kommandowort ein Such- oder Lesewerkzeug ist (`grep`, `rg`, `ag`, +`less`, `more`, `cat`, `head`, `tail`, `sed -n`, `awk` und ähnliche): `grep -i +"drop table" migrations.sql` bleibt unbewertet, `grep x f | psql -c "drop table +t"` und `echo "drop table t" | psql` sind rot. Kommandos, die eine solche +Anweisung nur erwähnen (`git commit -m "drop table x"`), fragen ebenfalls nach +Bestätigung. Gelb: `rm *` (ohne `-rf`), `systemctl stop/restart *`, `apt/yum remove *`, `git reset --hard*`, `kill *` (ohne PID 1). **Beispiele Daten-Risiko.** Rot: `cat`/`less`/`head`/`tail` auf jeden privaten SSH-Schlüssel From 06d24cc9d21a4e1e7167f7ef6e9c3292005e1920 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:41:18 +0000 Subject: [PATCH 3/8] refactor(core): split data risk pattern table instead of a lint exception (#1725) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/risk/patterns.rs | 368 ++++++++++++++++--------------- 1 file changed, 190 insertions(+), 178 deletions(-) diff --git a/crates/core/src/risk/patterns.rs b/crates/core/src/risk/patterns.rs index eccb318a3..5a886d9e3 100644 --- a/crates/core/src/risk/patterns.rs +++ b/crates/core/src/risk/patterns.rs @@ -564,187 +564,199 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static }) } -#[expect(clippy::too_many_lines, reason = "a flat pattern table")] +/// Red data-risk entries: files that very likely hold secrets. +fn data_risk_red_patterns() -> Vec<(Pattern, RiskLevel, &'static str)> { + vec![ + // --- Rot: enthält mit hoher Wahrscheinlichkeit Secrets -------- + ( + Regex(format!( + concat!("{}", ssh_identity_key!()), + READ_COMMAND_PREFIX + )), + RiskLevel::Red, + "Zugriff auf eine SSH-Private-Key-Datei (id_*)", + ), + ( + Regex(format!(concat!("{}", ssh_host_key!()), READ_COMMAND_PREFIX)), + RiskLevel::Red, + "Zugriff auf einen SSH-Host-Private-Key (ssh_host_*_key)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.pem\b")), + RiskLevel::Red, + "Zugriff auf eine Zertifikat-/Key-Datei (.pem)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.key\b")), + RiskLevel::Red, + "Zugriff auf eine Key-Datei (.key)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.env\b")), + RiskLevel::Red, + "Zugriff auf eine .env-Datei", + ), + ( + Regex(format!("{READ_COMMAND_PREFIX}credentials")), + RiskLevel::Red, + "Zugriff auf eine Datei/einen Pfad namens \"credentials\"", + ), + ( + Regex(format!("{READ_COMMAND_PREFIX}shadow")), + RiskLevel::Red, + "Zugriff auf /etc/shadow", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.aws/credentials")), + RiskLevel::Red, + "Zugriff auf AWS-Zugangsdaten", + ), + ( + Exact("env".to_string()), + RiskLevel::Red, + "Gibt alle Umgebungsvariablen aus (env)", + ), + ( + Glob("env *".to_string()), + RiskLevel::Red, + "Gibt alle Umgebungsvariablen aus (env)", + ), + ( + Exact("printenv".to_string()), + RiskLevel::Red, + "Gibt alle Umgebungsvariablen aus (printenv)", + ), + ( + Glob("printenv *".to_string()), + RiskLevel::Red, + "Gibt Umgebungsvariablen aus (printenv)", + ), + ( + Glob("mysqldump*".to_string()), + RiskLevel::Red, + "Datenbank-Export ohne erkennbare Redaction (mysqldump)", + ), + ( + Glob("pg_dump*".to_string()), + RiskLevel::Red, + "Datenbank-Export ohne erkennbare Redaction (pg_dump)", + ), + ( + Glob("*select*from*user*".to_string()), + RiskLevel::Red, + "SQL-Abfrage auf eine user-Tabelle", + ), + ( + Glob("*select*from*password*".to_string()), + RiskLevel::Red, + "SQL-Abfrage auf eine password-Spalte/-Tabelle", + ), + // Spec 0068, Teil 2: weitere Secret-Pfade auch in der Anzeige + // (die eigentliche Eskalation macht `secret_path_read_reason`). + ( + Regex(format!("{READ_COMMAND_PREFIX}/etc/gshadow")), + RiskLevel::Red, + "Zugriff auf /etc/gshadow", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.docker/config\.json")), + RiskLevel::Red, + "Zugriff auf Docker-Registry-Zugangsdaten", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.kube/config")), + RiskLevel::Red, + "Zugriff auf eine Kubernetes-Konfiguration", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.netrc\b")), + RiskLevel::Red, + "Zugriff auf ~/.netrc", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.pgpass\b")), + RiskLevel::Red, + "Zugriff auf ~/.pgpass", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.git-credentials\b")), + RiskLevel::Red, + "Zugriff auf ~/.git-credentials", + ), + // Issue #1725 + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.tfstate\b")), + RiskLevel::Red, + "Zugriff auf einen Terraform-State (.tfstate)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.kdbx\b")), + RiskLevel::Red, + "Zugriff auf eine KeePass-Datenbank (.kdbx)", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.s3cfg\b")), + RiskLevel::Red, + "Zugriff auf ~/.s3cfg", + ), + ( + Regex(format!( + "{READ_COMMAND_PREFIX}application_default_credentials\\.json" + )), + RiskLevel::Red, + "Zugriff auf gcloud-Zugangsdaten", + ), + ( + Regex(format!(r"{READ_COMMAND_PREFIX}\.azure/")), + RiskLevel::Red, + "Zugriff auf Azure-CLI-Zugangsdaten (~/.azure/)", + ), + ] +} + +/// Yellow data-risk entries: may point to secrets, but not certain. +fn data_risk_yellow_patterns() -> Vec<(Pattern, RiskLevel, &'static str)> { + vec![ + // --- Gelb: könnte auf Secrets hindeuten, aber nicht sicher ---- + ( + Glob("find*-name*.key*".to_string()), + RiskLevel::Yellow, + "Sucht gezielt nach Key-Dateien (find -name *.key)", + ), + ( + Glob("ls*.ssh*".to_string()), + RiskLevel::Yellow, + "Listet den .ssh-Ordner auf", + ), + ( + Glob("ls*/etc*".to_string()), + RiskLevel::Yellow, + "Listet /etc auf", + ), + ( + Glob("grep*password*".to_string()), + RiskLevel::Yellow, + "Sucht nach dem Begriff \"password\" in Dateien", + ), + ( + Glob("grep*secret*".to_string()), + RiskLevel::Yellow, + "Sucht nach dem Begriff \"secret\" in Dateien", + ), + ( + Glob("grep*token*".to_string()), + RiskLevel::Yellow, + "Sucht nach dem Begriff \"token\" in Dateien", + ), + ] +} + pub(super) fn data_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static str)] { static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new(); PATTERNS.get_or_init(|| { - vec![ - // --- Rot: enthält mit hoher Wahrscheinlichkeit Secrets -------- - ( - Regex(format!( - concat!("{}", ssh_identity_key!()), - READ_COMMAND_PREFIX - )), - RiskLevel::Red, - "Zugriff auf eine SSH-Private-Key-Datei (id_*)", - ), - ( - Regex(format!(concat!("{}", ssh_host_key!()), READ_COMMAND_PREFIX)), - RiskLevel::Red, - "Zugriff auf einen SSH-Host-Private-Key (ssh_host_*_key)", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.pem\b")), - RiskLevel::Red, - "Zugriff auf eine Zertifikat-/Key-Datei (.pem)", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.key\b")), - RiskLevel::Red, - "Zugriff auf eine Key-Datei (.key)", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.env\b")), - RiskLevel::Red, - "Zugriff auf eine .env-Datei", - ), - ( - Regex(format!("{READ_COMMAND_PREFIX}credentials")), - RiskLevel::Red, - "Zugriff auf eine Datei/einen Pfad namens \"credentials\"", - ), - ( - Regex(format!("{READ_COMMAND_PREFIX}shadow")), - RiskLevel::Red, - "Zugriff auf /etc/shadow", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.aws/credentials")), - RiskLevel::Red, - "Zugriff auf AWS-Zugangsdaten", - ), - ( - Exact("env".to_string()), - RiskLevel::Red, - "Gibt alle Umgebungsvariablen aus (env)", - ), - ( - Glob("env *".to_string()), - RiskLevel::Red, - "Gibt alle Umgebungsvariablen aus (env)", - ), - ( - Exact("printenv".to_string()), - RiskLevel::Red, - "Gibt alle Umgebungsvariablen aus (printenv)", - ), - ( - Glob("printenv *".to_string()), - RiskLevel::Red, - "Gibt Umgebungsvariablen aus (printenv)", - ), - ( - Glob("mysqldump*".to_string()), - RiskLevel::Red, - "Datenbank-Export ohne erkennbare Redaction (mysqldump)", - ), - ( - Glob("pg_dump*".to_string()), - RiskLevel::Red, - "Datenbank-Export ohne erkennbare Redaction (pg_dump)", - ), - ( - Glob("*select*from*user*".to_string()), - RiskLevel::Red, - "SQL-Abfrage auf eine user-Tabelle", - ), - ( - Glob("*select*from*password*".to_string()), - RiskLevel::Red, - "SQL-Abfrage auf eine password-Spalte/-Tabelle", - ), - // Spec 0068, Teil 2: weitere Secret-Pfade auch in der Anzeige - // (die eigentliche Eskalation macht `secret_path_read_reason`). - ( - Regex(format!("{READ_COMMAND_PREFIX}/etc/gshadow")), - RiskLevel::Red, - "Zugriff auf /etc/gshadow", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.docker/config\.json")), - RiskLevel::Red, - "Zugriff auf Docker-Registry-Zugangsdaten", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.kube/config")), - RiskLevel::Red, - "Zugriff auf eine Kubernetes-Konfiguration", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.netrc\b")), - RiskLevel::Red, - "Zugriff auf ~/.netrc", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.pgpass\b")), - RiskLevel::Red, - "Zugriff auf ~/.pgpass", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.git-credentials\b")), - RiskLevel::Red, - "Zugriff auf ~/.git-credentials", - ), - // Issue #1725 - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.tfstate\b")), - RiskLevel::Red, - "Zugriff auf einen Terraform-State (.tfstate)", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.kdbx\b")), - RiskLevel::Red, - "Zugriff auf eine KeePass-Datenbank (.kdbx)", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.s3cfg\b")), - RiskLevel::Red, - "Zugriff auf ~/.s3cfg", - ), - ( - Regex(format!( - "{READ_COMMAND_PREFIX}application_default_credentials\\.json" - )), - RiskLevel::Red, - "Zugriff auf gcloud-Zugangsdaten", - ), - ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.azure/")), - RiskLevel::Red, - "Zugriff auf Azure-CLI-Zugangsdaten (~/.azure/)", - ), - // --- Gelb: könnte auf Secrets hindeuten, aber nicht sicher ---- - ( - Glob("find*-name*.key*".to_string()), - RiskLevel::Yellow, - "Sucht gezielt nach Key-Dateien (find -name *.key)", - ), - ( - Glob("ls*.ssh*".to_string()), - RiskLevel::Yellow, - "Listet den .ssh-Ordner auf", - ), - ( - Glob("ls*/etc*".to_string()), - RiskLevel::Yellow, - "Listet /etc auf", - ), - ( - Glob("grep*password*".to_string()), - RiskLevel::Yellow, - "Sucht nach dem Begriff \"password\" in Dateien", - ), - ( - Glob("grep*secret*".to_string()), - RiskLevel::Yellow, - "Sucht nach dem Begriff \"secret\" in Dateien", - ), - ( - Glob("grep*token*".to_string()), - RiskLevel::Yellow, - "Sucht nach dem Begriff \"token\" in Dateien", - ), - ] + let mut all = data_risk_red_patterns(); + all.extend(data_risk_yellow_patterns()); + all }) } From 964776b0c2c989939c456653e8bd6da598b417c4 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 12:59:07 +0000 Subject: [PATCH 4/8] style(core): shorten comment to stay under the file size limit (#1725) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/risk/classifier.rs | 10 ++++------ 1 file changed, 4 insertions(+), 6 deletions(-) diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index d3c3fbd8f..5587c9828 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -220,12 +220,10 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat } } -/// Issue #1725 (ADR 0167): the segment contains a data-destroying SQL -/// statement and does not start with a search/read tool. The first word is -/// taken from the sudo/wrapper-resolved form, so `sudo grep -i "drop table" -/// x` is exempt like `grep`; a pipe or chain is rated per segment because the -/// caller passes every segment, and the whole command (which may start with -/// `grep`) cannot hide a later `| psql` segment. +/// Issue #1725 (ADR 0167): the segment holds a destructive SQL statement and +/// its first word (after sudo/wrapper resolution) is not a search/read tool. +/// Rated per segment: a whole command starting with `grep` cannot hide a +/// later `| psql` segment, which the caller passes separately. fn destructive_sql(lower_segment: &str) -> bool { static STATEMENT: std::sync::OnceLock = std::sync::OnceLock::new(); static READ_TOOL: std::sync::OnceLock = std::sync::OnceLock::new(); From 25480441f44974bab53cfaf2f4c64546cd54ecd0 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:13:36 +0000 Subject: [PATCH 5/8] fix(core): rate piped read tools, quoted dd of=, truncate --s as destructive (#1725) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/risk/classifier.rs | 30 ++++++++++++++----- crates/core/src/risk/patterns.rs | 4 +-- .../src/risk/tests_destructive_families.rs | 6 ++++ ...ructive-sql-rated-anywhere-in-a-command.md | 4 +++ docs/specs/0026-command-risk-indicators.md | 4 ++- 5 files changed, 38 insertions(+), 10 deletions(-) diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index 5587c9828..ec182f426 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -220,22 +220,38 @@ pub(super) fn classify_into(command: &str, depth: usize, acc: &mut RiskAccumulat } } -/// Issue #1725 (ADR 0167): the segment holds a destructive SQL statement and -/// its first word (after sudo/wrapper resolution) is not a search/read tool. -/// Rated per segment: a whole command starting with `grep` cannot hide a -/// later `| psql` segment, which the caller passes separately. -fn destructive_sql(lower_segment: &str) -> bool { +/// Issue #1725 (ADR 0167): the text holds a destructive SQL statement in a +/// stage that is not a search/read tool, or in a read-tool stage whose output +/// is piped on into a stage that is not one (`cat <<< "drop table t" | psql`). +/// A read tool alone (`grep -i "drop table" x.sql`) is exempt. The text is +/// split naively on `;`, `&`, newline and `|` (also inside quotes); that can +/// only rate higher, never lower. The caller passes each pipeline segment and +/// the whole command, so a later `| psql` is seen in the whole-command pass. +fn destructive_sql(lower_text: &str) -> bool { static STATEMENT: std::sync::OnceLock = std::sync::OnceLock::new(); static READ_TOOL: std::sync::OnceLock = std::sync::OnceLock::new(); let statement = STATEMENT.get_or_init(|| { regex::Regex::new(SQL_DESTRUCTIVE).expect("SQL_DESTRUCTIVE is a valid regex") }); - if !statement.is_match(lower_segment) { + if !statement.is_match(lower_text) { return false; } let read_tool = READ_TOOL .get_or_init(|| regex::Regex::new(SQL_READ_TOOL).expect("SQL_READ_TOOL is a valid regex")); - !read_tool.is_match(resolve_effective_command(lower_segment).trim_start()) + let is_read = + |stage: &str| read_tool.is_match(resolve_effective_command(stage.trim()).trim_start()); + lower_text + .split(|c| matches!(c, ';' | '&' | '\n')) + .any(|command| { + let stages: Vec<&str> = command + .split('|') + .filter(|stage| !stage.trim().is_empty()) + .collect(); + stages.iter().enumerate().any(|(i, stage)| { + statement.is_match(stage) + && (!is_read(stage) || stages[i + 1..].iter().any(|later| !is_read(later))) + }) + }) } /// Höchstes unter allen zutreffenden Mustern — ein Teilkommando kann diff --git a/crates/core/src/risk/patterns.rs b/crates/core/src/risk/patterns.rs index 5a886d9e3..8a5bf926b 100644 --- a/crates/core/src/risk/patterns.rs +++ b/crates/core/src/risk/patterns.rs @@ -464,7 +464,7 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static ), ( Regex( - r"^(?:\S*/)?truncate\s(?:.*\s)?(?:-[a-z]*s|--si(?:z(?:e)?)?)(?:[^a-z]|$)" + r"^(?:\S*/)?truncate\s(?:.*\s)?(?:-[a-z]*s|--s(?:i(?:ze?)?)?)(?:[^a-z]|$)" .to_string(), ), RiskLevel::Red, @@ -515,7 +515,7 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static // `dd` with the target before the source (`dd of=/dev/sdb if=…`); // the glob above only knows `if=` first. ( - Regex(r#"^(?:\S*/)?dd\s(?:.*\s)?["']?of=/dev/"#.to_string()), + Regex(r#"^(?:\S*/)?dd\s(?:.*\s)?["']?of=["']?/dev/"#.to_string()), RiskLevel::Red, "Direktes Schreiben auf ein Blockgerät (dd of=/dev/...)", ), diff --git a/crates/core/src/risk/tests_destructive_families.rs b/crates/core/src/risk/tests_destructive_families.rs index 745745b3c..73963dab0 100644 --- a/crates/core/src/risk/tests_destructive_families.rs +++ b/crates/core/src/risk/tests_destructive_families.rs @@ -16,6 +16,8 @@ const FAMILIES: &[&str] = &[ "truncate --size=0 /var/log/syslog", "truncate -c -s 10 /data/db", "truncate --siz=0 /var/log/syslog", + "truncate --s=0 /var/log/syslog", + "truncate --s 0 /var/log/syslog", "truncate --si 0 /var/log/syslog", "truncate -s-1G /data/db", "find /x -mtime +7 -delete", @@ -40,6 +42,8 @@ const FAMILIES: &[&str] = &[ "dd bs=1M of=/dev/sdb if=/tmp/img", "dd \"of=/dev/sdb\" if=/tmp/img", "dd 'of=/dev/sdb' if=/tmp/img", + "dd of=\"/dev/sda\" if=x", + "dd if=x of='/dev/sda'", "/usr/sbin/wipefs -a /dev/sdb", "mysql -e \"DROP DATABASE shop\"", "psql -c \"truncate table orders\"", @@ -54,6 +58,8 @@ const FAMILIES: &[&str] = &[ "echo \"drop table t\" | psql", "grep x f | psql -c \"drop table t\"", "grep x f; echo 'drop table t'", + "cat <<< \"drop table users\" | psql", + "awk 'BEGIN{print \"drop table t\"}' | psql", "psql -c \"DROP/**/DATABASE x\"", "psql -c \"drop\ttable t\"", ]; diff --git a/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md b/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md index 44d9f09da..8f5e1e14a 100644 --- a/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md +++ b/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md @@ -25,6 +25,10 @@ client nobody listed, and it rated `grep -i 'drop table' mysql.log` red. 3. The exemption is per segment. The classifier rates every segment and the whole command; the whole command may start with `grep` and so be exempt, while a later `| psql -c "drop table t"` segment is still rated red. +4. A read-tool stage that holds the statement and pipes into a stage that is + not a read tool is rated red too (`cat <<< "drop table t" | psql`, + `awk 'BEGIN{print "drop table t"}' | psql`). The whole command is split + naively on `;`, `&`, newline and `|`, which can only rate higher. ## Accepted consequences diff --git a/docs/specs/0026-command-risk-indicators.md b/docs/specs/0026-command-risk-indicators.md index 8bc55c1ad..2f7dfd39d 100644 --- a/docs/specs/0026-command-risk-indicators.md +++ b/docs/specs/0026-command-risk-indicators.md @@ -83,7 +83,9 @@ Kommandos, auch mit unbekanntem SQL-Client. Ausgenommen ist nur ein Teilkommando dessen erstes Kommandowort ein Such- oder Lesewerkzeug ist (`grep`, `rg`, `ag`, `less`, `more`, `cat`, `head`, `tail`, `sed -n`, `awk` und ähnliche): `grep -i "drop table" migrations.sql` bleibt unbewertet, `grep x f | psql -c "drop table -t"` und `echo "drop table t" | psql` sind rot. Kommandos, die eine solche +t"`, `echo "drop table t" | psql` und `cat <<< "drop table t" | psql` sind rot: +ein Lesewerkzeug ist nur ausgenommen, wenn seine Ausgabe nicht in ein anderes +Kommando als ein Lesewerkzeug weitergeleitet wird. Kommandos, die eine solche Anweisung nur erwähnen (`git commit -m "drop table x"`), fragen ebenfalls nach Bestätigung. Gelb: `rm *` (ohne `-rf`), `systemctl stop/restart *`, `apt/yum remove *`, `git reset --hard*`, `kill *` (ohne PID 1). From 9dcef012167e303ab572a0ddf3ccba220a27a0d7 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:19:38 +0000 Subject: [PATCH 6/8] style(core): satisfy clippy in destructive_sql (#1725) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/risk/classifier.rs | 20 +++++++++----------- 1 file changed, 9 insertions(+), 11 deletions(-) diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index c1d0ee09b..03da83049 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -281,18 +281,16 @@ fn destructive_sql(lower_text: &str) -> bool { .get_or_init(|| regex::Regex::new(SQL_READ_TOOL).expect("SQL_READ_TOOL is a valid regex")); let is_read = |stage: &str| read_tool.is_match(resolve_effective_command(stage.trim()).trim_start()); - lower_text - .split(|c| matches!(c, ';' | '&' | '\n')) - .any(|command| { - let stages: Vec<&str> = command - .split('|') - .filter(|stage| !stage.trim().is_empty()) - .collect(); - stages.iter().enumerate().any(|(i, stage)| { - statement.is_match(stage) - && (!is_read(stage) || stages[i + 1..].iter().any(|later| !is_read(later))) - }) + lower_text.split([';', '&', '\n']).any(|command| { + let stages: Vec<&str> = command + .split('|') + .filter(|stage| !stage.trim().is_empty()) + .collect(); + stages.iter().enumerate().any(|(i, stage)| { + statement.is_match(stage) + && (!is_read(stage) || stages[i + 1..].iter().any(|later| !is_read(later))) }) + }) } /// Ergebnis der Secret-Pfad- bzw. `sftp-server`-Prüfung (Issue #109). From d734ab4fb9bf3ca8975be01e77b50be8ae9945ac Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 14:39:21 +0000 Subject: [PATCH 7/8] test(core): compare only filter decisions for find -delete, risk is red (#1725) Co-Authored-By: Claude Sonnet 5.5 --- .../src/filter/adversarial_tests/sudo_options.rs | 12 ++++++++++++ .../adversarial_tests/tests_execution_wrappers.rs | 7 ++++--- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/core/src/filter/adversarial_tests/sudo_options.rs b/crates/core/src/filter/adversarial_tests/sudo_options.rs index bcafdbbcc..329ef79b0 100644 --- a/crates/core/src/filter/adversarial_tests/sudo_options.rs +++ b/crates/core/src/filter/adversarial_tests/sudo_options.rs @@ -80,6 +80,12 @@ const OPAQUE_VALUES: [(&str, &str); 15] = [ /// Compares decision (under three policies) and risk of each pair. pub(super) async fn mismatches(pairs: &[(&str, &str)]) -> Vec { + risk_mismatches(pairs, filter_mismatches(pairs).await) +} + +/// Like `mismatches`, but compares only the filter decisions, not the risk +/// rating (for pairs the risk classifier deliberately rates differently). +pub(super) async fn filter_mismatches(pairs: &[(&str, &str)]) -> Vec { let policies: [(&str, Vec); 3] = [ ("allow-all + deny-rm", vec![allow_all(), deny_rm()]), ("allow-all", vec![allow_all()]), @@ -97,6 +103,12 @@ pub(super) async fn mismatches(pairs: &[(&str, &str)]) -> Vec { )); } } + } + mismatches +} + +fn risk_mismatches(pairs: &[(&str, &str)], mut mismatches: Vec) -> Vec { + for &(with_option, without_option) in pairs { let expected = RuleBasedRiskClassifier.classify(without_option); let actual = RuleBasedRiskClassifier.classify(with_option); let expected = (expected.server_risk, expected.data_risk); diff --git a/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs b/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs index 47e0f7fd2..1b8ce649f 100644 --- a/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs +++ b/crates/core/src/filter/adversarial_tests/tests_execution_wrappers.rs @@ -4,7 +4,7 @@ //! see the command they run as they see the bare command, and where it //! cannot be read for sure the call needs at least `Confirm`. -use super::sudo_options::mismatches; +use super::sudo_options::{filter_mismatches, mismatches}; use super::*; use crate::risk::RuleBasedRiskClassifier; @@ -258,10 +258,11 @@ async fn test_adv_nested_execution_wrappers_hit_deny_rule() { } } -/// `find -delete` removes what it finds, like `rm -r`. +/// `find -delete` removes what it finds, like `rm -r`. Only the filter +/// decisions are compared: the risk classifier rates `find -delete` red (#1725). #[tokio::test] async fn test_adv_find_delete_is_checked_like_rm() { - let found = mismatches(&[ + let found = filter_mismatches(&[ ("find /srv -delete", "rm -r /srv"), ("find -name '*.log' -delete", "rm -r ."), ("find / -xdev -delete", "rm -r /"), From df1c847e83f0e022dd2a32912a911a5c6d3fbb44 Mon Sep 17 00:00:00 2001 From: "smart-ssh-coder[bot]" <338317697+smart-ssh-coder[bot]@users.noreply.github.com> Date: Sat, 5 Dec 2026 15:00:59 +0000 Subject: [PATCH 8/8] refactor(core): move destructive SQL check into its own module (#1725) Co-Authored-By: Claude Sonnet 5.5 --- crates/core/src/risk/classifier.rs | 36 +---------------- crates/core/src/risk/mod.rs | 1 + crates/core/src/risk/patterns.rs | 21 ---------- crates/core/src/risk/sql_statement.rs | 56 +++++++++++++++++++++++++++ 4 files changed, 59 insertions(+), 55 deletions(-) create mode 100644 crates/core/src/risk/sql_statement.rs diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index 03da83049..14ea42cd0 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -8,10 +8,10 @@ use crate::filter::{ use super::patterns::{ best_match, data_risk_patterns, secret_path_patterns, server_risk_patterns, SECRET_FILE_CANDIDATES, SECRET_PATH_HINTS, SECRET_READ_COMMANDS, SECRET_RELATIVE_PREFIXES, - SFTP_SERVER_INVOCATION, SQL_DESTRUCTIVE, SQL_DESTRUCTIVE_REASON, SQL_READ_TOOL, - SSH_KEY_GLOB_CANDIDATES, + SFTP_SERVER_INVOCATION, SSH_KEY_GLOB_CANDIDATES, }; use super::sftp_word_check::{quoted_sftp_server_invocation, sftp_server_word_check, WordCheck}; +use super::sql_statement::{destructive_sql, SQL_DESTRUCTIVE_REASON}; use super::types::{RiskAssessment, RiskLevel}; /// Regelbasierter Klassifikator (Spec 0026, Abschnitt 2) — @@ -261,38 +261,6 @@ fn rate_segments( segments } -/// Issue #1725 (ADR 0167): the text holds a destructive SQL statement in a -/// stage that is not a search/read tool, or in a read-tool stage whose output -/// is piped on into a stage that is not one (`cat <<< "drop table t" | psql`). -/// A read tool alone (`grep -i "drop table" x.sql`) is exempt. The text is -/// split naively on `;`, `&`, newline and `|` (also inside quotes); that can -/// only rate higher, never lower. The caller passes each pipeline segment and -/// the whole command, so a later `| psql` is seen in the whole-command pass. -fn destructive_sql(lower_text: &str) -> bool { - static STATEMENT: std::sync::OnceLock = std::sync::OnceLock::new(); - static READ_TOOL: std::sync::OnceLock = std::sync::OnceLock::new(); - let statement = STATEMENT.get_or_init(|| { - regex::Regex::new(SQL_DESTRUCTIVE).expect("SQL_DESTRUCTIVE is a valid regex") - }); - if !statement.is_match(lower_text) { - return false; - } - let read_tool = READ_TOOL - .get_or_init(|| regex::Regex::new(SQL_READ_TOOL).expect("SQL_READ_TOOL is a valid regex")); - let is_read = - |stage: &str| read_tool.is_match(resolve_effective_command(stage.trim()).trim_start()); - lower_text.split([';', '&', '\n']).any(|command| { - let stages: Vec<&str> = command - .split('|') - .filter(|stage| !stage.trim().is_empty()) - .collect(); - stages.iter().enumerate().any(|(i, stage)| { - statement.is_match(stage) - && (!is_read(stage) || stages[i + 1..].iter().any(|later| !is_read(later))) - }) - }) -} - /// Ergebnis der Secret-Pfad- bzw. `sftp-server`-Prüfung (Issue #109). /// Beide Varianten eskalieren gleich (`AutoExec` → `Confirm`); sie /// unterscheiden nur den Grund, den der Bestätigungsdialog nennt. diff --git a/crates/core/src/risk/mod.rs b/crates/core/src/risk/mod.rs index 0c95770a5..7f7523f86 100644 --- a/crates/core/src/risk/mod.rs +++ b/crates/core/src/risk/mod.rs @@ -22,6 +22,7 @@ mod classifier; mod patterns; mod sftp_word_check; +mod sql_statement; mod types; mod wrapper_state; diff --git a/crates/core/src/risk/patterns.rs b/crates/core/src/risk/patterns.rs index 8343c4879..7514eabf1 100644 --- a/crates/core/src/risk/patterns.rs +++ b/crates/core/src/risk/patterns.rs @@ -329,27 +329,6 @@ pub(super) const SFTP_SERVER_INVOCATION: &str = concat!( r"(?:\S*/)?sftp-server(?:\s|$)" ); -/// Issue #1725 (ADR 0167): a data-destroying SQL statement anywhere in a -/// command. SQL comments may stand in for whitespace (`DROP/**/DATABASE`). -/// The statement is matched without regard to a SQL client, so unknown -/// clients are covered too; `SQL_READ_TOOL` is the only exemption. -pub(super) const SQL_DESTRUCTIVE: &str = concat!( - r"(?s)\b(?:drop(?:\s|/\*.*?\*/)+(?:database|schema|table)", - r"|truncate(?:\s|/\*.*?\*/)+table)\b" -); - -/// Issue #1725 (ADR 0167): first command word of a segment that only -/// searches or reads text (`grep -i "drop table" x.sql`); such a segment is -/// not rated for the SQL statement it mentions. `sed` counts only with `-n`. -pub(super) const SQL_READ_TOOL: &str = concat!( - r"^(?:\S*/)?(?:grep|egrep|fgrep|zgrep|rg|ag|ack|less|more|cat|zcat|head|tail|bat|awk|gawk", - r"|sed\s+(?:-[a-z]*n[a-z]*|--quiet|--silent))(?:\s|$)" -); - -/// Reason shown for `SQL_DESTRUCTIVE`. -pub(super) const SQL_DESTRUCTIVE_REASON: &str = - "SQL-Anweisung löscht Daten (drop database/schema/table, truncate table)"; - pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static str)] { static PATTERNS: std::sync::OnceLock> = std::sync::OnceLock::new(); diff --git a/crates/core/src/risk/sql_statement.rs b/crates/core/src/risk/sql_statement.rs new file mode 100644 index 000000000..2b6aaa6ee --- /dev/null +++ b/crates/core/src/risk/sql_statement.rs @@ -0,0 +1,56 @@ +//! Destructive SQL statements in a command (issue #1725, ADR 0167). + +use crate::filter::resolve_effective_command; + +/// Issue #1725 (ADR 0167): a data-destroying SQL statement anywhere in a +/// command. SQL comments may stand in for whitespace (`DROP/**/DATABASE`). +/// The statement is matched without regard to a SQL client, so unknown +/// clients are covered too; `SQL_READ_TOOL` is the only exemption. +const SQL_DESTRUCTIVE: &str = concat!( + r"(?s)\b(?:drop(?:\s|/\*.*?\*/)+(?:database|schema|table)", + r"|truncate(?:\s|/\*.*?\*/)+table)\b" +); + +/// Issue #1725 (ADR 0167): first command word of a segment that only +/// searches or reads text (`grep -i "drop table" x.sql`); such a segment is +/// not rated for the SQL statement it mentions. `sed` counts only with `-n`. +const SQL_READ_TOOL: &str = concat!( + r"^(?:\S*/)?(?:grep|egrep|fgrep|zgrep|rg|ag|ack|less|more|cat|zcat|head|tail|bat|awk|gawk", + r"|sed\s+(?:-[a-z]*n[a-z]*|--quiet|--silent))(?:\s|$)" +); + +/// Reason shown for `SQL_DESTRUCTIVE`. +pub(super) const SQL_DESTRUCTIVE_REASON: &str = + "SQL-Anweisung löscht Daten (drop database/schema/table, truncate table)"; + +/// Issue #1725 (ADR 0167): the text holds a destructive SQL statement in a +/// stage that is not a search/read tool, or in a read-tool stage whose output +/// is piped on into a stage that is not one (`cat <<< "drop table t" | psql`). +/// A read tool alone (`grep -i "drop table" x.sql`) is exempt. The text is +/// split naively on `;`, `&`, newline and `|` (also inside quotes); that can +/// only rate higher, never lower. The caller passes each pipeline segment and +/// the whole command, so a later `| psql` is seen in the whole-command pass. +pub(super) fn destructive_sql(lower_text: &str) -> bool { + static STATEMENT: std::sync::OnceLock = std::sync::OnceLock::new(); + static READ_TOOL: std::sync::OnceLock = std::sync::OnceLock::new(); + let statement = STATEMENT.get_or_init(|| { + regex::Regex::new(SQL_DESTRUCTIVE).expect("SQL_DESTRUCTIVE is a valid regex") + }); + if !statement.is_match(lower_text) { + return false; + } + let read_tool = READ_TOOL + .get_or_init(|| regex::Regex::new(SQL_READ_TOOL).expect("SQL_READ_TOOL is a valid regex")); + let is_read = + |stage: &str| read_tool.is_match(resolve_effective_command(stage.trim()).trim_start()); + lower_text.split([';', '&', '\n']).any(|command| { + let stages: Vec<&str> = command + .split('|') + .filter(|stage| !stage.trim().is_empty()) + .collect(); + stages.iter().enumerate().any(|(i, stage)| { + statement.is_match(stage) + && (!is_read(stage) || stages[i + 1..].iter().any(|later| !is_read(later))) + }) + }) +}