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 6c580274a..d78b2ce92 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 @@ -786,3 +786,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/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 /"), diff --git a/crates/core/src/risk/classifier.rs b/crates/core/src/risk/classifier.rs index e05269a47..14ea42cd0 100644 --- a/crates/core/src/risk/classifier.rs +++ b/crates/core/src/risk/classifier.rs @@ -11,6 +11,7 @@ use super::patterns::{ 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) — @@ -247,6 +248,10 @@ fn rate_segments( 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 = diff --git a/crates/core/src/risk/mod.rs b/crates/core/src/risk/mod.rs index 7c620dc77..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; @@ -34,6 +35,8 @@ mod property_tests; #[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 733cbc1cd..7514eabf1 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/", ]; @@ -201,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)", @@ -239,6 +252,25 @@ 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/)", + ), ] .into_iter() .map(|(pattern, reason)| { @@ -278,6 +310,11 @@ pub(super) const SECRET_PATH_HINTS: &[&str] = &[ ".p12", ".pfx", ".jks", + // Issue #1725 (the credential names are covered by "credentials") + "tfstate", + ".kdbx", + "s3cfg", + ".azure", ]; /// Aufruf von `sftp-server` am Anfang eines Teilkommandos, direkt oder per @@ -388,207 +425,321 @@ pub(super) fn server_risk_patterns() -> &'static [(Pattern, RiskLevel, &'static RiskLevel::Red, "Rechte werden rekursiv auf 777 gesetzt", ), - // --- Gelb: potenziell destruktiv, aber üblicherweise gezielt -- - ( - Glob("rm *".to_string()), - RiskLevel::Yellow, - "Löscht Dateien (rm)", - ), - ( - Glob("systemctl*stop*".to_string()), - RiskLevel::Yellow, - "Dienst wird gestoppt (systemctl stop)", - ), - ( - Glob("systemctl*restart*".to_string()), - RiskLevel::Yellow, - "Dienst wird neu gestartet (systemctl restart)", - ), - ( - Glob("apt*remove*".to_string()), - RiskLevel::Yellow, - "Paket wird entfernt (apt remove)", - ), - ( - Glob("yum*remove*".to_string()), - RiskLevel::Yellow, - "Paket wird entfernt (yum remove)", - ), - ( - Glob("git*reset*--hard*".to_string()), - RiskLevel::Yellow, - "Lokale Änderungen werden verworfen (git reset --hard)", - ), - ( - Glob("kill *".to_string()), - RiskLevel::Yellow, - "Prozess wird beendet (kill)", - ), - ( - Glob("kill*-9*".to_string()), - RiskLevel::Yellow, - "Prozess wird hart beendet (kill -9)", - ), - ] - }) -} - -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", - ), + // 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(format!("{READ_COMMAND_PREFIX}credentials")), + Regex(r"^(?:\S*/)?shred(?:\s|$)".to_string()), RiskLevel::Red, - "Zugriff auf eine Datei/einen Pfad namens \"credentials\"", + "Überschreibt Dateien/Geräte unwiederbringlich (shred)", ), ( - Regex(format!("{READ_COMMAND_PREFIX}shadow")), + Regex(r"^(?:\S*/)?wipefs(?:\s|$)".to_string()), RiskLevel::Red, - "Zugriff auf /etc/shadow", + "Löscht Dateisystem-Signaturen (wipefs)", ), ( - 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()), + Regex( + r"^(?:\S*/)?truncate\s(?:.*\s)?(?:-[a-z]*s|--s(?:i(?:ze?)?)?)(?:[^a-z]|$)" + .to_string(), + ), RiskLevel::Red, - "Gibt alle Umgebungsvariablen aus (printenv)", + "Setzt die Dateigröße und verwirft Inhalt (truncate -s)", ), ( - Glob("printenv *".to_string()), + Regex(r"^(?:\S*/)?find\s(?:.*\s)?-delete(?:\s|$)".to_string()), RiskLevel::Red, - "Gibt Umgebungsvariablen aus (printenv)", + "Löscht alle Treffer von find (find -delete)", ), ( - Glob("mysqldump*".to_string()), + Regex(r"^(?:\S*/)?blkdiscard(?:\s|$)".to_string()), RiskLevel::Red, - "Datenbank-Export ohne erkennbare Redaction (mysqldump)", + "Verwirft Blöcke eines Geräts (blkdiscard)", ), ( - Glob("pg_dump*".to_string()), + Regex( + r"^(?:\S*/)?sgdisk\s(?:.*\s)?(?:--zap(?:-all)?|-[a-z]*z[a-z]*)(?:\s|$)".to_string(), + ), RiskLevel::Red, - "Datenbank-Export ohne erkennbare Redaction (pg_dump)", + "Zerstört die Partitionstabelle (sgdisk --zap)", ), ( - Glob("*select*from*user*".to_string()), + Regex(r"^(?:\S*/)?mke2fs(?:\s|$)".to_string()), RiskLevel::Red, - "SQL-Abfrage auf eine user-Tabelle", + "Dateisystem neu erstellen (mke2fs)", ), ( - Glob("*select*from*password*".to_string()), + Regex(r"^(?:\S*/)?mkswap(?:\s|$)".to_string()), RiskLevel::Red, - "SQL-Abfrage auf eine password-Spalte/-Tabelle", + "Überschreibt ein Gerät mit Swap-Signatur (mkswap)", ), - // 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")), + Regex(r"^(?:\S*/)?(?:lvm\s+)?(?:lv|vg|pv)remove(?:\s|$)".to_string()), RiskLevel::Red, - "Zugriff auf /etc/gshadow", + "Entfernt LVM-Volumes/-Gruppen/-Geräte (lvremove/vgremove/pvremove)", ), ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.docker/config\.json")), + Regex(r"^(?:\S*/)?zpool\s(?:.*\s)?destroy(?:\s|$)".to_string()), RiskLevel::Red, - "Zugriff auf Docker-Registry-Zugangsdaten", + "Zerstört einen ZFS-Pool (zpool destroy)", ), ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.kube/config")), + Regex(r"^(?:\S*/)?zfs\s(?:.*\s)?destroy(?:\s|$)".to_string()), RiskLevel::Red, - "Zugriff auf eine Kubernetes-Konfiguration", + "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(format!(r"{READ_COMMAND_PREFIX}\.netrc\b")), + Regex(r#"^(?:\S*/)?dd\s(?:.*\s)?["']?of=["']?/dev/"#.to_string()), RiskLevel::Red, - "Zugriff auf ~/.netrc", + "Direktes Schreiben auf ein Blockgerät (dd of=/dev/...)", ), + // --- Gelb: potenziell destruktiv, aber üblicherweise gezielt -- ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.pgpass\b")), - RiskLevel::Red, - "Zugriff auf ~/.pgpass", + Glob("rm *".to_string()), + RiskLevel::Yellow, + "Löscht Dateien (rm)", ), ( - Regex(format!(r"{READ_COMMAND_PREFIX}\.git-credentials\b")), - RiskLevel::Red, - "Zugriff auf ~/.git-credentials", + Glob("systemctl*stop*".to_string()), + RiskLevel::Yellow, + "Dienst wird gestoppt (systemctl stop)", ), - // --- Gelb: könnte auf Secrets hindeuten, aber nicht sicher ---- ( - Glob("find*-name*.key*".to_string()), + Glob("systemctl*restart*".to_string()), RiskLevel::Yellow, - "Sucht gezielt nach Key-Dateien (find -name *.key)", + "Dienst wird neu gestartet (systemctl restart)", ), ( - Glob("ls*.ssh*".to_string()), + Glob("apt*remove*".to_string()), RiskLevel::Yellow, - "Listet den .ssh-Ordner auf", + "Paket wird entfernt (apt remove)", ), ( - Glob("ls*/etc*".to_string()), + Glob("yum*remove*".to_string()), RiskLevel::Yellow, - "Listet /etc auf", + "Paket wird entfernt (yum remove)", ), ( - Glob("grep*password*".to_string()), + Glob("git*reset*--hard*".to_string()), RiskLevel::Yellow, - "Sucht nach dem Begriff \"password\" in Dateien", + "Lokale Änderungen werden verworfen (git reset --hard)", ), ( - Glob("grep*secret*".to_string()), + Glob("kill *".to_string()), RiskLevel::Yellow, - "Sucht nach dem Begriff \"secret\" in Dateien", + "Prozess wird beendet (kill)", ), ( - Glob("grep*token*".to_string()), + Glob("kill*-9*".to_string()), RiskLevel::Yellow, - "Sucht nach dem Begriff \"token\" in Dateien", + "Prozess wird hart beendet (kill -9)", ), ] }) } +/// 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(|| { + let mut all = data_risk_red_patterns(); + all.extend(data_risk_yellow_patterns()); + all + }) +} + /// 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/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))) + }) + }) +} 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..73963dab0 --- /dev/null +++ b/crates/core/src/risk/tests_destructive_families.rs @@ -0,0 +1,156 @@ +//! 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", + "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", + "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", + "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\"", + "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'", + "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'", + "cat <<< \"drop table users\" | psql", + "awk 'BEGIN{print \"drop table t\"}' | psql", + "psql -c \"DROP/**/DATABASE x\"", + "psql -c \"drop\ttable 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), + ("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), + ] { + 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/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..8f5e1e14a --- /dev/null +++ b/docs/adr/0167-destructive-sql-rated-anywhere-in-a-command.md @@ -0,0 +1,48 @@ +# 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. +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 + +- 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 0f86d2357..b59ea169d 100644 --- a/docs/adr/INDEX.md +++ b/docs/adr/INDEX.md @@ -170,3 +170,4 @@ | 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 | Filter: commands that another program runs | Accepted | [0165-filter-commands-run-by-other-programs.md](0165-filter-commands-run-by-other-programs.md) | | 0166 | AI provider kinds contributed by the embedding application | Accepted | [0166-ai-provider-kinds-from-the-embedding-app.md](0166-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 6247578af..d4d60f47e 100644 --- a/docs/specs/0026-command-risk-indicators.md +++ b/docs/specs/0026-command-risk-indicators.md @@ -77,7 +77,20 @@ 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` 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"`, `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). **Beispiele Daten-Risiko.** Rot: `cat`/`less`/`head`/`tail` auf jeden privaten SSH-Schlüssel @@ -85,7 +98,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`,