From 5d5bfa8d5bcb86f8ad198742277fba8aeb3478e0 Mon Sep 17 00:00:00 2001 From: Cuihtlauac ALVARADO Date: Fri, 20 Nov 2026 15:33:21 +0100 Subject: [PATCH 1/6] protocol: widen the forbidden prompt-character class to Cc/Cf/Zl/Zp/DICP (#86) has_dangerous_chars only knew C0, three zero-width/bidi ranges, and nothing else: DEL, C1 (NEL, CSI, OSC), soft hyphen, ALM, LS/PS, word joiner and invisible operators, BOM, tag characters and variation selectors all reached the approval prompt. Replace the hand-listed ranges with one table-driven class, dangerous(c) <=> c != TAB && c in Cc u Cf u Zl u Zp u Default_Ignorable_Code_Point, built from the Unicode 16.0.0 UCD (DANGEROUS_RANGES, binary-searched by is_dangerous_char), and reuse it in the audit-record and --log-json escapers. An exhaustive unit test checks the table against a General_Category oracle (unicode-general-category =1.1.0, a pinned test-only dev-dependency) plus a verbatim copy of the DICP list. The env-key error no longer echoes the raw key; this is for consistency (the key only reaches the response, and the audit copy is escaped), not a security fix. Validation messages are otherwise unchanged. Tests: oracle and table-shape tests, a regression table, integration tests over every newly covered character in argv/reason/session/env value/plan Exec/plan Chdir, a non-ASCII accept test, an audit-record escape test, and a property test whose env keys are now valid by construction and whose alphabet includes multibyte text. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Cuihtlauac ALVARADO --- Cargo.lock | 7 ++ Cargo.toml | 4 + src/audit.rs | 14 ++- src/protocol.rs | 228 +++++++++++++++++++++++++++++++++++++++++--- src/server.rs | 72 +++++++++++--- tests/audit.rs | 14 +++ tests/validation.rs | 95 +++++++++++++++++- 7 files changed, 397 insertions(+), 37 deletions(-) diff --git a/Cargo.lock b/Cargo.lock index 7b96891..86f624e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -576,6 +576,7 @@ dependencies = [ "serde_json", "tempfile", "tokio", + "unicode-general-category", "uuid", ] @@ -704,6 +705,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "unicode-general-category" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b993bddc193ae5bd0d623b49ec06ac3e9312875fdae725a975c51db1cc1677f" + [[package]] name = "unicode-ident" version = "1.0.23" diff --git a/Cargo.toml b/Cargo.toml index 96cee79..2832873 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,3 +82,7 @@ schemars = { version = "1", optional = true } [dev-dependencies] tempfile = "3" +# Test-only Unicode General_Category oracle for the exhaustive +# forbidden-character class test (src/protocol.rs). Pinned exactly: its +# Unicode version fixes the version of the hand-copied DICP list there. +unicode-general-category = "=1.1.0" diff --git a/src/audit.rs b/src/audit.rs index 5047998..ba7be77 100644 --- a/src/audit.rs +++ b/src/audit.rs @@ -24,7 +24,7 @@ use std::sync::Mutex; use serde::Serialize; -use crate::protocol::{Response, Status}; +use crate::protocol::{is_dangerous_char, Response, Status}; /// Longest a single untrusted field may be in a record. A request that fails /// validation can carry up to 1 MiB in `id`/`session`/`host`; the log must not @@ -312,17 +312,15 @@ fn clip(s: &str) -> String { } } -/// Clip, then make terminal-safe: every C0/C1 control (newline and tab -/// included — a record is one line), DEL, and the zero-width / bidi characters -/// `has_dangerous_chars` forbids are written as `\u{…}` escapes. +/// Clip, then make terminal-safe: newline, tab (a record is one line) and +/// every character `protocol::is_dangerous_char` forbids on the prompt +/// (control, format, separator, default-ignorable) are written as `\u{…}` +/// escapes. fn safe(s: &str) -> String { let mut out = String::new(); for c in clip(s).chars() { let u = c as u32; - if u < 0x20 - || (0x7F..=0x9F).contains(&u) - || matches!(u, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069) - { + if c == '\t' || c == '\n' || is_dangerous_char(c) { out.push_str(&format!("\\u{{{u:x}}}")); } else { out.push(c); diff --git a/src/protocol.rs b/src/protocol.rs index 97bb050..6e84210 100644 --- a/src/protocol.rs +++ b/src/protocol.rs @@ -623,27 +623,103 @@ fn default_session() -> String { "unknown".to_string() } +/// Every code point forbidden in prompt-rendered text, as sorted, +/// non-overlapping, inclusive `(lo, hi)` ranges. The rule is +/// +/// > dangerous(c) ⇔ c ≠ TAB ∧ c ∈ Cc ∪ Cf ∪ Zl ∪ Zp ∪ Default_Ignorable_Code_Point +/// +/// i.e. control (C0, DEL, C1 including NEL/CSI/OSC), format (soft hyphen, +/// zero-width, bidi embeddings/overrides/isolates/marks, BOM, invisible +/// operators, interlinear annotation, tag characters), line/paragraph +/// separators, and every default-ignorable code point (variation selectors, +/// Hangul fillers, reserved ignorables such as U+2065 and U+E0000–E0FFF), which +/// render as nothing and so can hide text from the approver. +/// +/// Built from the Unicode 16.0.0 UCD (General_Category, and +/// `DerivedCoreProperties.txt` Default_Ignorable_Code_Point), merging adjacent +/// ranges. TAB is in the table (it is Cc) and is exempted by +/// [`is_dangerous_char`]. The table is not trusted by inspection: the unit test +/// `dangerous_class_matches_unicode_oracle` checks it exhaustively, over every +/// `char`, against a General_Category oracle of the same Unicode version plus +/// a verbatim copy of the DICP list. +pub(crate) const DANGEROUS_RANGES: &[(u32, u32)] = &[ + (0x0000, 0x001F), + (0x007F, 0x009F), + (0x00AD, 0x00AD), + (0x034F, 0x034F), + (0x0600, 0x0605), + (0x061C, 0x061C), + (0x06DD, 0x06DD), + (0x070F, 0x070F), + (0x0890, 0x0891), + (0x08E2, 0x08E2), + (0x115F, 0x1160), + (0x17B4, 0x17B5), + (0x180B, 0x180F), + (0x200B, 0x200F), + (0x2028, 0x202E), + (0x2060, 0x206F), + (0x3164, 0x3164), + (0xFE00, 0xFE0F), + (0xFEFF, 0xFEFF), + (0xFFA0, 0xFFA0), + (0xFFF0, 0xFFFB), + (0x110BD, 0x110BD), + (0x110CD, 0x110CD), + (0x13430, 0x1343F), + (0x1BCA0, 0x1BCA3), + (0x1D173, 0x1D17A), + (0xE0000, 0xE0FFF), +]; + +/// True if `c` is forbidden in any request-derived string rendered on the +/// approval prompt: a control, format, separator or default-ignorable +/// character other than TAB (see [`DANGEROUS_RANGES`]). +/// +/// Also used by `mcp::sanitize_description` (same crate) to strip this class +/// from the MCP `description` before it becomes `reason`. +/// +/// The lookup is a binary search (`partition_point`) rather than a linear +/// scan, so the Kani harnesses in `src/proofs.rs` need an unwind bound near +/// log2(table length) rather than the table length + 1. +pub(crate) fn is_dangerous_char(c: char) -> bool { + if c == '\t' { + return false; + } + let u = c as u32; + // First range whose upper bound is >= u; it holds u iff its lower bound + // is <= u. + let i = DANGEROUS_RANGES.partition_point(|&(_, hi)| hi < u); + i < DANGEROUS_RANGES.len() && DANGEROUS_RANGES[i].0 <= u +} + /// True if `s` contains a character forbidden in any request-derived string -/// that is rendered on the approval prompt: control chars (except tab), and -/// zero-width / bidi-override characters. The prompt is the security gate, so -/// a field carrying raw ANSI/escape/newline or bidi bytes could redraw the -/// terminal and misrepresent the command being approved. +/// that is rendered on the approval prompt: control, format, separator and +/// default-ignorable characters (Cc/Cf/Zl/Zp/DICP), except tab. The prompt is +/// the security gate, so a field carrying raw ANSI/escape/newline, bidi or +/// invisible characters could redraw the terminal or hide text, and so +/// misrepresent the command being approved. See [`is_dangerous_char`]. /// /// `pub(crate)` so the Rung 2 property test and the Rung 3 Kani harness can /// drive it directly; the only *enforcement* path is `ValidatedRequest::validate`. pub(crate) fn has_dangerous_chars(s: &str) -> bool { + s.chars().any(is_dangerous_char) +} + +/// Make text that never went through `ValidatedRequest::validate` (e.g. a +/// filesystem-derived path) safe to print on the approval prompt: every +/// [`is_dangerous_char`] character is written as a `\u{…}` escape; tab and +/// everything else are kept as is. +pub(crate) fn escape_dangerous(s: &str) -> String { + let mut out = String::with_capacity(s.len()); for c in s.chars() { - // Control chars 0x00-0x1F except tab (0x09) - if c != '\t' && (c as u32) < 0x20 { - return true; - } - // Zero-width and bidi override characters - match c as u32 { - 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069 => return true, - _ => {} + if is_dangerous_char(c) { + out.push_str(&format!("\\u{{{:x}}}", c as u32)); + } else { + out.push(c); } } - false + out } /// A `Request` that has passed `ValidatedRequest::validate`. @@ -707,7 +783,8 @@ impl ValidatedRequest { } for key in req.env.keys() { if has_dangerous_chars(key) { - return Err(format!("env key '{key}' contains forbidden characters")); + // Do not echo the key: by construction it holds a forbidden char. + return Err("env key contains forbidden characters".to_string()); } if !is_valid_env_name(key) { return Err(format!("env key '{key}' is not a valid variable name")); @@ -1270,4 +1347,127 @@ mod tests { let p = Plan::RunAs { who: RunAs::User { name: "nobody".into() }, body: Box::new(exec(&["id"])) }; assert!(!ValidatedRequest::validate(plan_req(p)).unwrap().runs_as_root()); } + + /// Default_Ignorable_Code_Point, copied verbatim (one entry per line, not + /// merged) from `DerivedCoreProperties.txt` of Unicode 16.0.0 — the + /// version `unicode-general-category` 1.1.0 implements + /// (`UNICODE_VERSION`, checked below). Independent of `DANGEROUS_RANGES`: + /// it is not derived from the table. Bump both together. + const DICP_16_0: &[(u32, u32)] = &[ + (0x00AD, 0x00AD), // Cf SOFT HYPHEN + (0x034F, 0x034F), // Mn COMBINING GRAPHEME JOINER + (0x061C, 0x061C), // Cf ARABIC LETTER MARK + (0x115F, 0x1160), // Lo HANGUL CHOSEONG FILLER..HANGUL JUNGSEONG FILLER + (0x17B4, 0x17B5), // Mn KHMER VOWEL INHERENT AQ..KHMER VOWEL INHERENT AA + (0x180B, 0x180D), // Mn MONGOLIAN FREE VARIATION SELECTOR ONE..THREE + (0x180E, 0x180E), // Cf MONGOLIAN VOWEL SEPARATOR + (0x180F, 0x180F), // Mn MONGOLIAN FREE VARIATION SELECTOR FOUR + (0x200B, 0x200F), // Cf ZERO WIDTH SPACE..RIGHT-TO-LEFT MARK + (0x202A, 0x202E), // Cf LEFT-TO-RIGHT EMBEDDING..RIGHT-TO-LEFT OVERRIDE + (0x2060, 0x2064), // Cf WORD JOINER..INVISIBLE PLUS + (0x2065, 0x2065), // Cn + (0x2066, 0x206F), // Cf LEFT-TO-RIGHT ISOLATE..NOMINAL DIGIT SHAPES + (0x3164, 0x3164), // Lo HANGUL FILLER + (0xFE00, 0xFE0F), // Mn VARIATION SELECTOR-1..VARIATION SELECTOR-16 + (0xFEFF, 0xFEFF), // Cf ZERO WIDTH NO-BREAK SPACE + (0xFFA0, 0xFFA0), // Lo HALFWIDTH HANGUL FILLER + (0xFFF0, 0xFFF8), // Cn .. + (0x1BCA0, 0x1BCA3), // Cf SHORTHAND FORMAT LETTER OVERLAP..SHORTHAND FORMAT UP STEP + (0x1D173, 0x1D17A), // Cf MUSICAL SYMBOL BEGIN BEAM..MUSICAL SYMBOL END PHRASE + (0xE0000, 0xE0000), // Cn + (0xE0001, 0xE0001), // Cf LANGUAGE TAG + (0xE0002, 0xE001F), // Cn .. + (0xE0020, 0xE007F), // Cf TAG SPACE..CANCEL TAG + (0xE0080, 0xE00FF), // Cn .. + (0xE0100, 0xE01EF), // Mn VARIATION SELECTOR-17..VARIATION SELECTOR-256 + (0xE01F0, 0xE0FFF), // Cn .. + ]; + + /// Issue #86: `is_dangerous_char` is exactly + /// `c != TAB && (gc(c) ∈ {Cc, Cf, Zl, Zp} || DICP(c))`, checked over every + /// `char`. A Unicode bump of the oracle that adds Cf characters fails here. + #[test] + fn dangerous_class_matches_unicode_oracle() { + use unicode_general_category::{get_general_category, GeneralCategory as Gc}; + assert_eq!( + unicode_general_category::UNICODE_VERSION, + (16, 0, 0), + "oracle bumped: refresh DICP_16_0 and DANGEROUS_RANGES from the same UCD" + ); + let dicp = |u: u32| DICP_16_0.iter().any(|&(lo, hi)| lo <= u && u <= hi); + let mut mismatches = Vec::new(); + for u in 0..=0x10FFFFu32 { + let Some(c) = char::from_u32(u) else { continue }; + let expected = c != '\t' + && (matches!( + get_general_category(c), + Gc::Control | Gc::Format | Gc::LineSeparator | Gc::ParagraphSeparator + ) || dicp(u)); + if is_dangerous_char(c) != expected { + mismatches.push(format!("U+{u:04X} expected {expected}")); + } + } + assert!(mismatches.is_empty(), "class mismatches: {mismatches:?}"); + } + + #[test] + fn dangerous_ranges_sorted_and_disjoint() { + for &(lo, hi) in DANGEROUS_RANGES { + assert!(lo <= hi, "({lo:#x}, {hi:#x}) inverted"); + } + for w in DANGEROUS_RANGES.windows(2) { + assert!( + w[0].1 < w[1].0, + "{:#x?} and {:#x?} overlap or are unsorted", + w[0], + w[1] + ); + } + } + + /// Issue #86 regression table: every code point the issue names, plus a + /// tag character, an emoji variation selector and reserved U+2065, is + /// forbidden; ordinary printable text (ASCII, accents, CJK, dashes, + /// arrows, NBSP, a bare emoji) and TAB are not. + #[test] + fn dangerous_char_regression_table() { + let must_reject = [ + '\u{7f}', + '\u{85}', + '\u{9b}', + '\u{9d}', + '\u{ad}', + '\u{61c}', + '\u{2028}', + '\u{2029}', + '\u{2060}', + '\u{2061}', + '\u{2062}', + '\u{2063}', + '\u{2064}', + '\u{feff}', + '\u{e0041}', + '\u{fe0f}', + '\u{2065}', + ]; + for c in must_reject { + assert!(is_dangerous_char(c), "U+{:04X} must be dangerous", c as u32); + assert!(has_dangerous_chars(&format!("ok{c}ok"))); + } + let mut must_accept: Vec = (0x20u8..=0x7E).map(char::from).collect(); + must_accept.extend(['\t', 'é', '漢', '—', '→', '\u{a0}', '\u{1f642}']); + for c in must_accept { + assert!(!is_dangerous_char(c), "U+{:04X} must be accepted", c as u32); + } + assert!(!has_dangerous_chars("café 漢字 — → 🙂\tend")); + } + + #[test] + fn escape_dangerous_escapes_class_keeps_rest() { + assert_eq!( + escape_dangerous("a\u{1b}[2J\nb\tc\u{2065}é"), + "a\\u{1b}[2J\\u{a}b\tc\\u{2065}é" + ); + assert_eq!(escape_dangerous("/usr/bin/ls"), "/usr/bin/ls"); + } } diff --git a/src/server.rs b/src/server.rs index 6776ca1..a4da61a 100644 --- a/src/server.rs +++ b/src/server.rs @@ -13,7 +13,7 @@ use std::time::{Duration, Instant}; use crate::audit::{AuditConfig, AuditLog, Event, Outcome, Reject}; use crate::executor::{exec_direct, exec_pkexec, exec_sudo, sanitize_env}; use crate::mode::Mode; -use crate::protocol::{Request, Response, ValidatedRequest}; +use crate::protocol::{is_dangerous_char, Request, Response, ValidatedRequest}; use crate::tui::{self, Prompter, ResultSink}; const PROMPT_TIMEOUT: Duration = Duration::from_secs(60); @@ -637,17 +637,15 @@ fn log_plan_json(line: &[u8]) { } } -/// Make untrusted text safe to print on the approval terminal: C0 controls -/// (except newline and tab), DEL, C1 controls, and the zero-width / bidi -/// characters `has_dangerous_chars` forbids are written as `\u{…}` escapes. +/// Make untrusted text safe to print on the approval terminal: every +/// character `protocol::is_dangerous_char` forbids (control, format, +/// separator, default-ignorable; tab is not one) except newline is written as +/// a `\u{…}` escape. fn escape_for_terminal(s: &str) -> String { let mut out = String::with_capacity(s.len()); for c in s.chars() { let u = c as u32; - let unsafe_char = (u < 0x20 && c != '\n' && c != '\t') - || (0x7F..=0x9F).contains(&u) - || matches!(u, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069); - if unsafe_char { + if c != '\n' && is_dangerous_char(c) { out.push_str(&format!("\\u{{{u:x}}}")); } else { out.push(c); @@ -1547,16 +1545,55 @@ mod tests { } /// Build a string of length `0..=max_len` from a benign `char` alphabet — - /// every one of these passes `has_dangerous_chars`. + /// every one of these passes `has_dangerous_chars`. It includes printable + /// non-ASCII (issue #86), so the accept direction covers multibyte text. + /// Used for argv, reason, host, session, version, id, requester and env + /// *values*; env keys come from `rand_env_key`. fn rand_chars(rng: &mut Rng, max_len: usize) -> String { - const BENIGN: &[char] = &['a', 'b', 'c', '0', '1', ' ', '/', '-', '.', '_', '=', ':', ',']; + const BENIGN: &[char] = &[ + 'a', 'b', 'c', '0', '1', ' ', '/', '-', '.', '_', '=', ':', ',', 'é', '漢', '→', + ]; let len = rng.below(max_len + 1); (0..len).map(|_| BENIGN[rng.below(BENIGN.len())]).collect() } - // The exact danger classes `has_dangerous_chars` forbids: control chars - // (NUL, ESC, newline, CR) and zero-width / bidi overrides. - const DANGEROUS: &[char] = &['\u{0}', '\u{1b}', '\n', '\r', '\u{200b}', '\u{202e}', '\u{2066}']; + /// A valid env key (`[a-z_][a-z0-9_]{0,4}`), so `is_valid_env_name` never + /// rejects the request before the property under test is reached. + fn rand_env_key(rng: &mut Rng) -> String { + const FIRST: &[char] = &['a', 'b', 'c', '_']; + const REST: &[char] = &['a', 'b', 'c', '0', '1', '_']; + let mut key = String::from(FIRST[rng.below(FIRST.len())]); + for _ in 0..rng.below(5) { + key.push(REST[rng.below(REST.len())]); + } + key + } + + // A sample of every danger class `has_dangerous_chars` forbids: C0 + // controls (NUL, ESC, newline, CR), DEL and C1 (NEL, CSI), format + // characters (soft hyphen, ALM, zero-width, bidi override/isolate, word + // joiner, BOM, tag), line/paragraph separators, and reserved + // default-ignorable U+2065 (issue #86). + const DANGEROUS: &[char] = &[ + '\u{0}', + '\u{1b}', + '\n', + '\r', + '\u{200b}', + '\u{202e}', + '\u{2066}', + '\u{7f}', + '\u{85}', + '\u{9b}', + '\u{ad}', + '\u{61c}', + '\u{2028}', + '\u{2029}', + '\u{2060}', + '\u{2065}', + '\u{feff}', + '\u{e0041}', + ]; /// Generate a request whose fields are all benign, then with probability /// 1/2 splice one dangerous char into one randomly-chosen displayed field. @@ -1575,7 +1612,7 @@ mod tests { let mut env = std::collections::HashMap::new(); // Always at least one entry so the env branch is reachable. for _ in 0..(1 + rng.below(2)) { - env.insert(rand_chars(rng, 5), rand_chars(rng, 5)); + env.insert(rand_env_key(rng), rand_chars(rng, 5)); } let mut req = Request { id: rand_chars(rng, 6), @@ -1634,5 +1671,12 @@ mod tests { // Both directions exercised: the implication is not vacuous. assert!(accepted > 0, "generator never produced an accepted request"); assert!(rejected > 0, "generator never produced a rejected request"); + // About half the requests are clean by construction; demand a solid + // share so the accept direction (multibyte text included) is not + // vacuous. + assert!( + accepted >= 2000, + "too few accepted requests: {accepted} of 5000" + ); } } diff --git a/tests/audit.rs b/tests/audit.rs index 981a867..672f547 100644 --- a/tests/audit.rs +++ b/tests/audit.rs @@ -133,6 +133,20 @@ fn validation_failure_is_recorded_without_command() { assert_eq!(s.prompter.call_count(), 0); } +/// Issue #86: a line separator and a soft hyphen are now forbidden; the +/// rejected request is recorded with both escaped. +#[test] +fn widened_class_is_rejected_and_escaped_in_record() { + let s = server(); + let mut req = make_req("a-sep", vec![vec!["true"]]); + req.session = "evil\u{2028}ses\u{ad}sion".into(); + assert_eq!(s.send(&req).status, Status::Error); + let r = s.audit_for("a-sep"); + check_common(&r, "rejected:invalid_request"); + assert_eq!(r["session"], "evil\\u{2028}ses\\u{ad}sion"); + assert_eq!(s.prompter.call_count(), 0); +} + #[test] fn disallowed_env_is_recorded_without_its_value() { let s = server(); diff --git a/tests/validation.rs b/tests/validation.rs index 3578414..63607c7 100644 --- a/tests/validation.rs +++ b/tests/validation.rs @@ -79,7 +79,100 @@ fn dangerous_env_key_rejected() { req.env.insert("BAD\u{0001}KEY".into(), "v".into()); let resp = s.send(&req); assert_eq!(resp.status, Status::Error); - assert!(resp.message.as_deref().unwrap().contains("env key")); + let msg = resp.message.as_deref().unwrap(); + assert!(msg.contains("env key")); + // Issue #86: the message no longer echoes the raw (forbidden) key. + assert!(!msg.contains("BAD"), "raw key echoed: {msg:?}"); + assert!(!msg.contains('\u{0001}'), "raw key echoed: {msg:?}"); +} + +/// Issue #86: the forbidden class is Cc ∪ Cf ∪ Zl ∪ Zp ∪ Default_Ignorable +/// (minus TAB). Every newly covered character is rejected in every +/// prompt-rendered field, on both the flat-pipeline and the structured-plan +/// path. +#[test] +fn newly_forbidden_chars_rejected() { + use sudo_proxy::protocol::Plan; + let s = server(); + let chars = [ + '\u{9b}', + '\u{85}', + '\u{ad}', + '\u{61c}', + '\u{2028}', + '\u{2060}', + '\u{2065}', + '\u{feff}', + '\u{e0041}', + ]; + let fields = [ + "argv", + "reason", + "session", + "env value", + "plan exec", + "plan chdir", + ]; + for c in chars { + let bad = format!("a{c}b"); + for field in fields { + let id = format!("v-new-{:x}-{}", c as u32, field.replace(' ', "-")); + let mut req = make_req(&id, vec![vec!["true"]]); + match field { + "argv" => req.pipeline = vec![vec!["echo".into(), bad.clone()]], + "reason" => req.reason = bad.clone(), + "session" => req.session = bad.clone(), + "env value" => { + req.env.insert("OK".into(), bad.clone()); + } + "plan exec" => { + req.pipeline = vec![]; + req.plan = Some(Plan::Exec { + argv: vec!["echo".into(), bad.clone()], + }); + } + "plan chdir" => { + req.pipeline = vec![]; + req.plan = Some(Plan::Chdir { + dir: bad.clone(), + body: Box::new(Plan::Exec { + argv: vec!["true".into()], + }), + }); + } + _ => unreachable!(), + } + let resp = s.send(&req); + assert_eq!( + resp.status, + Status::Error, + "U+{:04X} in {field} must be rejected", + c as u32 + ); + let msg = resp.message.as_deref().unwrap_or(""); + assert!( + msg.contains("forbidden"), + "U+{:04X} in {field}: got {msg:?}", + c as u32 + ); + } + } + assert_eq!( + s.prompter.call_count(), + 0, + "no rejected request may reach the prompt" + ); +} + +/// Issue #86: the widened class must not reject legitimate printable +/// non-ASCII text. +#[test] +fn legitimate_non_ascii_accepted() { + let s = server(); + let req = make_req("v-non-ascii", vec![vec!["echo", "café 漢字 — →"]]); + let resp = s.send(&req); + assert_eq!(resp.status, Status::Ok, "got: {:?}", resp.message); + assert_eq!(s.prompter.call_count(), 1); } #[test] From 40fb80918c4ab244cc30970e7d6cf85001925947 Mon Sep 17 00:00:00 2001 From: Cuihtlauac ALVARADO Date: Fri, 20 Nov 2026 15:33:22 +0100 Subject: [PATCH 2/6] tui, gui: escape filesystem-derived Resolves paths (#86) The Resolves: text printed canonicalize() output raw. A same-UID caller can exec an absolute symlink whose target name holds ESC or a newline; only argv[0] is validated, so that name reached the prompt verbatim. Print every displayed path through escape_dangerous. Only the canonical path is caller-influenced; escaping the resolved path (tui) and the gui's shown path is defence in depth. Comparisons keep the raw strings, so benign paths render byte-identically and the pty goldens are unchanged. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Cuihtlauac ALVARADO --- src/gui.rs | 10 +++++++-- src/tui.rs | 66 +++++++++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 68 insertions(+), 8 deletions(-) diff --git a/src/gui.rs b/src/gui.rs index c44ed9b..f4e961b 100644 --- a/src/gui.rs +++ b/src/gui.rs @@ -3,7 +3,7 @@ use std::process::{Command, Stdio}; use std::time::Duration; use crate::executor::{plan_display, which}; -use crate::protocol::ValidatedRequest; +use crate::protocol::{escape_dangerous, ValidatedRequest}; use crate::tui::{self, pipeline_join, Prompter, PromptResult}; const PROMPT_TIMEOUT: Duration = Duration::from_secs(60); @@ -73,7 +73,13 @@ fn format_prompt_text(req: &ValidatedRequest) -> String { None => "(not found in PATH)".to_string(), }; if shown != *cmd_name && seen.insert((cmd_name.clone(), shown.clone())) { - lines.push(format!("Resolves: {cmd_name} → {shown}")); + // Escaped for display only (issue #86): `shown` is built from the + // validated argv[0]/cwd and the constant login PATH, so this is + // defence in depth; the comparison above uses the raw string. + lines.push(format!( + "Resolves: {cmd_name} → {}", + escape_dangerous(&shown) + )); } } lines.push(String::new()); diff --git a/src/tui.rs b/src/tui.rs index d27e4d3..412a8bc 100644 --- a/src/tui.rs +++ b/src/tui.rs @@ -7,7 +7,9 @@ use base64::engine::general_purpose::STANDARD as B64; use base64::Engine; use crate::executor::{plan_display, LeafPrivilege, LeafView}; -use crate::protocol::{Plan, RedirTarget, Response, RunAs, Status, Stream, ValidatedRequest}; +use crate::protocol::{ + escape_dangerous, Plan, RedirTarget, Response, RunAs, Status, Stream, ValidatedRequest, +}; /// Quote a single token for safe, paste-able POSIX shell. Anything outside a /// conservative unquoted-safe set is wrapped in single quotes (with embedded @@ -910,7 +912,7 @@ fn write_resolve_block(w: &mut W, views: &[LeafView], style: &Style) - match &view.resolved_bin { Some(p) => format!( "{bold}opaque — resolves only the shell: {}{reset}", - p.display() + escape_dangerous(&p.display().to_string()) ), None => format!("{bold}opaque — shell not found in PATH{reset}"), } @@ -936,6 +938,12 @@ fn write_resolve_block(w: &mut W, views: &[LeafView], style: &Style) - /// always naming a concrete path. Used by the consolidated resolve block; it /// mirrors `write_resolves_line`'s symlink display but never elides — the block /// shows every binary, even one supplied as an already-canonical absolute path. +/// +/// Both paths are printed through `escape_dangerous` (issue #86). Only the +/// canonical path is caller-influenced (a symlink's target name never goes +/// through `ValidatedRequest::validate`); the resolved path is built from the +/// validated `argv[0]`/cwd and the constant login PATH, so escaping it is +/// defence in depth. Comparisons use the raw strings. fn resolve_detail(resolved: Option<&Path>, style: &Style) -> String { let Style { bold, dim, reset, .. } = *style; let resolved = match resolved { @@ -947,12 +955,19 @@ fn resolve_detail(resolved: Option<&Path>, style: &Style) -> String { Ok(canonical) => { let canonical_str = canonical.display().to_string(); if canonical_str != resolved_str { - format!("{resolved_str} {bold}->{reset} {canonical_str}") + format!( + "{} {bold}->{reset} {}", + escape_dangerous(&resolved_str), + escape_dangerous(&canonical_str) + ) } else { - resolved_str + escape_dangerous(&resolved_str) } } - Err(_) => format!("{resolved_str} {dim}(canonicalize failed){reset}"), + Err(_) => format!( + "{} {dim}(canonicalize failed){reset}", + escape_dangerous(&resolved_str) + ), } } @@ -971,6 +986,9 @@ fn resolve_detail(resolved: Option<&Path>, style: &Style) -> String { /// - canonicalize fails (broken symlink, EACCES): show what we know and /// flag `(canonicalize failed)` so the prompt is honest about not /// having verified the target. +/// +/// Printed paths go through `escape_dangerous` (issue #86), as in +/// `resolve_detail`; the comparisons use the raw strings. fn write_resolves_line( w: &mut W, cmd_name: &str, @@ -986,11 +1004,14 @@ fn write_resolves_line( }; let resolved_str = resolved.display().to_string(); let resolved_differs = resolved_str != *cmd_name; + let resolved_shown = escape_dangerous(&resolved_str); match std::fs::canonicalize(resolved) { Ok(canonical) => { let canonical_str = canonical.display().to_string(); let canonical_differs = canonical_str != resolved_str; + let resolved_str = resolved_shown; + let canonical_str = escape_dangerous(&canonical_str); match (resolved_differs, canonical_differs) { (false, false) => Ok(()), (true, false) => writeln!(w, "Resolves: {resolved_str}"), @@ -1006,7 +1027,7 @@ fn write_resolves_line( } Err(_) => writeln!( w, - "Resolves: {resolved_str} {dim}(canonicalize failed){reset}" + "Resolves: {resolved_shown} {dim}(canonicalize failed){reset}" ), } } @@ -2162,4 +2183,37 @@ mod tests { assert_eq!(run_sh(&steps), via_plan, "Steps:\n{steps}"); } } + + /// Issue #86: a symlink's target name never goes through validation, so a + /// same-UID caller can point an absolute symlink at a file named with ESC + /// and newline. The `Resolves:` text must print it escaped, not raw. + #[test] + fn resolves_escapes_dangerous_symlink_target() { + let dir = tempfile::tempdir().expect("tempdir"); + // No `/` in the name: a file name cannot hold one. + let target = dir.path().join("evil\x1b[2J\nExecute? [y|N]"); + std::fs::write(&target, b"").expect("write target"); + let link = dir.path().join("link"); + // Absolute target, so `canonicalize` succeeds and the + // `resolved -> canonical` arm is exercised. + std::os::unix::fs::symlink(&target, &link).expect("symlink"); + let style = style_for(true); + + let check = |text: &str| { + assert!(text.contains("\\u{1b}"), "ESC not escaped: {text:?}"); + assert!(text.contains("\\u{a}"), "newline not escaped: {text:?}"); + assert!(!text.contains('\x1b'), "raw ESC: {text:?}"); + assert!(text.contains("->"), "canonical arm not taken: {text:?}"); + }; + + let detail = resolve_detail(Some(&link), &style); + check(&detail); + assert!(!detail.contains('\n'), "raw newline: {detail:?}"); + + let mut out = Vec::new(); + write_resolves_line(&mut out, link.to_str().unwrap(), Some(&link), &style).unwrap(); + let line = String::from_utf8(out).unwrap(); + check(&line); + assert_eq!(line.matches('\n').count(), 1, "raw newline: {line:?}"); + } } From 49f5a7229253c678e1178e4869b146d940a0fa08 Mon Sep 17 00:00:00 2001 From: Cuihtlauac ALVARADO Date: Fri, 20 Nov 2026 15:33:22 +0100 Subject: [PATCH 3/6] mcp: strip forbidden prompt characters from description (#86) With the widened class, an agent's description such as "Restart nginx" followed by a warning-sign emoji with U+FE0F would make the daemon reject the request. sanitize_description removes every is_dangerous_char character before the description becomes reason; the daemon gate stays strict. The execute tool description says so. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Cuihtlauac ALVARADO --- src/mcp.rs | 38 ++++++++++++++++++++++++++++++++++++-- 1 file changed, 36 insertions(+), 2 deletions(-) diff --git a/src/mcp.rs b/src/mcp.rs index fe1404e..157cecd 100644 --- a/src/mcp.rs +++ b/src/mcp.rs @@ -47,6 +47,18 @@ fn read_timeout_for(privileged: bool, timeout_ms: Option) -> Option String { + desc.chars() + .filter(|c| !protocol::is_dangerous_char(*c)) + .collect() +} + /// Build the outgoing `Request` from the tool parameters. Exactly one command /// form is accepted: a structured `plan`, or the legacy `pipeline` / `argv`. /// The daemon re-validates; this is only the client-side assembly. @@ -60,7 +72,7 @@ fn build_request(params: &ExecuteParams, host: String) -> Result Date: Fri, 20 Nov 2026 15:33:23 +0100 Subject: [PATCH 4/6] proofs: Kani harnesses over the whole char domain for the new class (#86) Drop the < 0x2100 bound (tag characters sit at U+E0000). The per-char harness now proves (a) has_dangerous_chars(encode(c)) == is_dangerous_char(c) for every char, (b) an independently written list of the code points #86 names is dangerous, (c) TAB and printable ASCII are not. Exact membership is left to the exhaustive oracle unit test. unwind 8 covers the 4-byte decode and the binary search. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Cuihtlauac ALVARADO --- src/proofs.rs | 94 +++++++++++++++++++++++++++++++++++---------------- 1 file changed, 64 insertions(+), 30 deletions(-) diff --git a/src/proofs.rs b/src/proofs.rs index ea0ffab..566845a 100644 --- a/src/proofs.rs +++ b/src/proofs.rs @@ -11,8 +11,9 @@ //! that are *our* code: //! - `datetime::ymd_hms_to_epoch` — the panic/overflow/wrap-relevant core of //! the `parse_age` freshness gate (issues #11/#14). -//! - `protocol::has_dangerous_chars` — the control/bidi scanner the approval -//! prompt relies on. +//! - `protocol::has_dangerous_chars` / `is_dangerous_char` — the scanner for +//! the control, format, separator and default-ignorable characters +//! (Cc/Cf/Zl/Zp/DICP) the approval prompt relies on (widened in #86). //! It deliberately does *not* attempt the base64 and `serde_json` decode paths: //! those are upstream crates that return `Result`, and our call sites contain no //! `.unwrap()` on them (`if let Ok`/`?` throughout — server.rs, tui.rs, mcp.rs, @@ -105,39 +106,72 @@ fn ymd_hms_to_epoch_is_monotone_on_valid_dates() { } } -/// Proof: `has_dangerous_chars` is panic-free for any character and classifies -/// it *exactly* per its documented danger ranges. The function is a per-char -/// fold with no cross-character state, so single-char coverage of the -/// classification generalises to any string. This is the Rung 3 discharge of -/// the display-field clause behind `ValidatedRequest::validate`. +/// Proof: `has_dangerous_chars` is panic-free for any character, agrees with +/// the per-char class `is_dangerous_char` through UTF-8 encode/decode, and +/// that class contains every code point issue #86 names and excludes TAB and +/// printable ASCII. The function is a per-char fold with no cross-character +/// state, so single-char coverage generalises to any string. This is the +/// Rung 3 discharge of the display-field clause behind +/// `ValidatedRequest::validate`. /// -/// Two tractability choices keep CBMC fast without weakening the result: -/// - `encode_utf8` writes into a stack `[u8; 4]` rather than allocating a -/// `String`, so CBMC need not model the heap. -/// - The codepoint is bounded below `0x2100`. Every range the function -/// forbids lies at or below `0x2069`, and for any codepoint `>= 0x2100` -/// *both* the function (no matching arm) and `expected` are `false` by -/// inspection — so the bound excludes only a region where the equality -/// holds trivially. The proof is therefore total in substance. +/// The spec has three parts, none of them tautological: +/// (a) no panic, and `has_dangerous_chars(encode(c)) == is_dangerous_char(c)` +/// for every `char` (the string fold agrees with the char class); +/// (b) must-reject: an independently written `matches!` of the ranges the +/// issue names, plus C0/C1/DEL and reserved U+2065, implies dangerous; +/// (c) must-accept: TAB and `0x20..=0x7E` are not dangerous. +/// Exact set membership (every code point in or out of +/// Cc ∪ Cf ∪ Zl ∪ Zp ∪ DICP) is *not* proved here: it is discharged by the +/// exhaustive unit test `protocol::tests::dangerous_class_matches_unicode_oracle`, +/// which checks all 1,114,112 `char`s against a General_Category oracle. /// -/// `#[kani::unwind(5)]` bounds the `for c in s.chars()` loop: the buffer holds -/// a single (≤3-byte) char, so the loop runs once and the UTF-8 byte decode -/// at most three times — 5 unwindings cover every path and let CBMC discharge -/// the unwinding assertion. +/// `encode_utf8` writes into a stack `[u8; 4]` rather than allocating a +/// `String`, so CBMC need not model the heap. The domain is the whole `char` +/// range (the earlier `< 0x2100` bound no longer holds: tag characters sit at +/// U+E0000). +/// +/// `#[kani::unwind(8)]`: the buffer holds one (≤4-byte) char, so the +/// `chars()` loop runs once and the UTF-8 decode at most four times; the +/// `is_dangerous_char` lookup is a `partition_point` binary search over the +/// 27-entry `DANGEROUS_RANGES`, which iterates at most ⌈log2 27⌉ + 1 = 6 +/// times (a linear scan would need 28). 8 covers both with margin and lets +/// CBMC discharge the unwinding assertion. #[kani::proof] -#[kani::unwind(5)] +#[kani::unwind(8)] fn has_dangerous_chars_matches_spec_per_char() { let c: char = kani::any(); - kani::assume((c as u32) < 0x2100); let mut buf = [0u8; 4]; let s: &str = c.encode_utf8(&mut buf); let got = crate::protocol::has_dangerous_chars(s); + let class = crate::protocol::is_dangerous_char(c); + + // (a) the string fold agrees with the char class. + assert_eq!(got, class); let u = c as u32; - let expected = (c != '\t' && u < 0x20) - || matches!(u, 0x200B..=0x200F | 0x202A..=0x202E | 0x2066..=0x2069); - assert_eq!(got, expected); + // (b) must-reject (written independently of `DANGEROUS_RANGES`). + let must_reject = (c != '\t' && u < 0x20) + || matches!( + u, + 0x7F..=0x9F + | 0xAD + | 0x61C + | 0x200B..=0x200F + | 0x2028..=0x202E + | 0x2060..=0x2069 + | 0xFE0F + | 0xFEFF + | 0xE0001 + | 0xE0020..=0xE007F + ); + if must_reject { + assert!(class, "a code point named by #86 must be dangerous"); + } + // (c) must-accept. + if c == '\t' || (0x20..=0x7E).contains(&u) { + assert!(!class, "TAB and printable ASCII must be accepted"); + } } /// Proof: the structured-plan leaf check is panic-free and agrees with the @@ -150,15 +184,15 @@ fn has_dangerous_chars_matches_spec_per_char() { /// predicates. /// /// Scope mirrors `has_dangerous_chars_matches_spec_per_char`: one leaf, one -/// character bounded below `0x2100` (every forbidden range lies ≤ `0x2069`), so -/// the single-leaf result generalises — `validate_tree` is a fold applying that -/// same per-char predicate to every string leaf. `unwind(6)` bounds the single -/// ≤3-byte char decode plus the one-element argv loop. +/// character over the whole `char` domain (no bound since #86: tag characters +/// sit at U+E0000), so the single-leaf result generalises — `validate_tree` is +/// a fold applying that same per-char predicate to every string leaf. +/// `unwind(8)` bounds the single ≤4-byte char decode, the one-element argv +/// loop and the ≤6-step binary search of `is_dangerous_char`. #[kani::proof] -#[kani::unwind(6)] +#[kani::unwind(8)] fn plan_run_leaf_matches_dangerous_char_spec() { let c: char = kani::any(); - kani::assume((c as u32) < 0x2100); let mut buf = [0u8; 4]; let s: &str = c.encode_utf8(&mut buf); From 303393300f804f2abd16266190f0609cb0947d34 Mon Sep 17 00:00:00 2001 From: Cuihtlauac ALVARADO Date: Fri, 20 Nov 2026 15:34:12 +0100 Subject: [PATCH 5/6] docs: record the widened forbidden-character class (#86) Assurance case G3.3/G4.1 and their solutions, threat model (control row and the 3.4 residual), security.md, REVIEWING.md C6, the audit-escape note in usage.md, the MCP description note in README, a line under security-audit F1, a changelog entry, and the #86 clause struck from the Phase 0 backlog line. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Cuihtlauac ALVARADO --- README.md | 3 ++- REVIEWING.md | 4 ++-- backlog.md | 3 +-- changelog.md | 33 +++++++++++++++++++++++++++++++++ docs/assurance-case.md | 8 ++++---- docs/security-audit.md | 1 + docs/security.md | 9 +++++---- docs/threat-model.md | 6 +++++- docs/usage.md | 5 +++-- 9 files changed, 56 insertions(+), 16 deletions(-) diff --git a/README.md b/README.md index 628d7ad..02b106c 100644 --- a/README.md +++ b/README.md @@ -183,7 +183,8 @@ execute({"argv": ["apt", "install", "nginx"], "description": "Install nginx"}) Each `execute` shows the exact command in the TUI; press `y` to approve, `N` (default) to deny. For remote hosts, pass `host` to `start_server` and -`execute`. +`execute`. Invisible/format characters (e.g. emoji variation selectors, +zero-width or bidi controls) are removed from `description` before it is shown. When a prompt appears, the TUI rings the terminal bell and blinks the question line so a request is not missed while the daemon's terminal is diff --git a/REVIEWING.md b/REVIEWING.md index a7889f5..0ab65c0 100644 --- a/REVIEWING.md +++ b/REVIEWING.md @@ -62,8 +62,8 @@ finding. authentication is owned entirely by `sudo`/`pkexec`. *Attack:* find any path where sudo-proxy holds, caches, or replays a credential. → `src/executor.rs`. - **C6 — Display fields can't lie.** Fields shown at the prompt are rejected if - they contain control (0x00–0x1F bar tab), zero-width (U+200B–U+200F), or bidi - override (U+202A–U+202E, U+2066–U+2069) characters, so shown text cannot be + they contain control, format, separator or default-ignorable characters + (Cc/Cf/Zl/Zp/DICP bar tab; `protocol::DANGEROUS_RANGES`), so shown text cannot be made to diverge from real `argv` via those classes. *Attack:* get a divergence-causing character past the scanner to the prompt. → `src/protocol.rs` (`ValidatedRequest::validate`, `:172`), `has_dangerous_chars`. diff --git a/backlog.md b/backlog.md index 1ee33a2..bb8e7e7 100644 --- a/backlog.md +++ b/backlog.md @@ -151,8 +151,7 @@ One PR per item; each moves its evidence status in `docs/assurance-case.md`; every prompt-touching PR gets the pty goldens plus a live manual run. **Phase 0 — close the current gaps** (independent; patch releases 1.2.x): -#86 `has_dangerous_chars` gaps (DEL/C1, U+00AD, U+061C, U+2028/2029, -U+2060–2064, U+FEFF; update the Kani harness and proptest with it) · #85 bound +~~#86 `has_dangerous_chars` gaps~~ (done, see changelog) · #85 bound each `Steps:` line like `Command:` · #88 `--pkexec` multi-leaf plans (item 6 above) · #87 wrapper-aware `runs_shell` (item 5 above). diff --git a/changelog.md b/changelog.md index b6d12b2..bc69d83 100644 --- a/changelog.md +++ b/changelog.md @@ -3,6 +3,39 @@ Most recent at top. See [docs/formalisation-roadmap.md](docs/formalisation-roadmap.md) for the assurance-ladder context behind the security-formalisation entries. +## Unreleased — Widen the prompt's forbidden-character class (#86) + +`has_dangerous_chars` rejected C0 controls and three zero-width/bidi ranges +only. DEL and C1 (NEL, CSI, OSC), soft hyphen, ALM, line/paragraph +separators, word joiner and invisible operators, BOM, tag characters and +variation selectors all reached the approval prompt. The class is now one +rule, `c != TAB && c in Cc u Cf u Zl u Zp u Default_Ignorable_Code_Point`, +held as a table built from the Unicode 16.0.0 UCD +(`protocol::DANGEROUS_RANGES`) and reused by the audit-record and +`--log-json` escapers. + +- **Resolves paths.** Paths shown on `Resolves:` (tui and zenity) are printed + through `escape_dangerous`: a symlink's target name never goes through + validation, so a same-UID caller could put ESC or a newline on the prompt + that way. +- **Env-key message.** The "env key contains forbidden characters" error no + longer echoes the key. For consistency only: the key reached only the + response, and the audit copy was already escaped. +- **MCP.** `sudo-proxy-mcp` strips the class from `description` before it + becomes `reason`, so an emoji with U+FE0F no longer fails the request. The + daemon gate stays strict. +- **Newly rejected input.** Soft hyphens, emoji presentation sequences with + U+FE0F in `reason` from non-MCP clients, Arabic/Syriac text using U+061C, + U+0600–0605 or U+070F, a leading BOM, and tag characters now get the + existing validation error; drop the character. +- **Tests.** An exhaustive unit test checks the table over every `char` + against a General_Category oracle (`unicode-general-category`, a pinned + dev-dependency) plus a verbatim copy of the DICP list; a regression table; + integration tests over argv/reason/session/env value/plan leaves; a + non-ASCII accept test; an audit escape test; a `Resolves:` symlink test; + the property test with valid env keys and multibyte text; and the Kani + harnesses over the whole `char` domain. + ## Unreleased — Audit log for every request outcome (#65) The daemon logged prompted requests and unattended runs, and only with `-v`. It diff --git a/docs/assurance-case.md b/docs/assurance-case.md index 5299364..3a4ef86 100644 --- a/docs/assurance-case.md +++ b/docs/assurance-case.md @@ -99,8 +99,8 @@ a sanitized environment.* | **Sn3.1** | `Command::new(argv[0]).args(…)`, never `sh -c` (`src/executor.rs`); the multi-stage `shell_escape` fuzzed with 5000 inputs, round-tripped through `/bin/sh` byte-for-byte. | 2 | [partial] → Flux boundary type (Rung 3) | | **G3.2** | The environment is a hard-reject allowlist; `LD_PRELOAD`/`LD_*`/`IFS`/`BASH_ENV`/`SSH_AUTH_SOCK` are rejected, not stripped. | — | | | **Sn3.2** | `src/executor.rs` env sanitization; login defaults from `getpwuid(geteuid())`, not the request. | 1–2 | [discharged] | -| **G3.3** | Inputs carrying control / zero-width / bidi characters are rejected before use. | — | | -| **Sn3.3** | `has_dangerous_chars()` over every `pipeline` arg and `env` key/value; `tests/validation.rs`. | 2 | [discharged] | +| **G3.3** | Inputs carrying control, format, separator and default-ignorable (Cc/Cf/Zl/Zp/DICP) characters are rejected before use. | — | | +| **Sn3.3** | `has_dangerous_chars()` over every `pipeline` arg and `env` key/value; `tests/validation.rs` (widened in #86; class checked exhaustively against the UCD; Kani proves string/char agreement). | 2 | [discharged] | ### G4 — Faithful display at the gate @@ -108,8 +108,8 @@ a sanitized environment.* | Node | Claim / Evidence | Rung | Status | |------|------------------|------|--------| -| **G4.1** | No request field rendered to `/dev/tty` can inject ANSI / control / bidi sequences. | — | | -| **Sn4.1** | After **F1** fix: `has_dangerous_chars()` is applied to `reason`, `session`, `host`, `version`, `id`, `requester` in `validate_request`, covering both MCP and direct-socket paths; regression test. | 2 | [discharged] | +| **G4.1** | No request field rendered to `/dev/tty` can inject ANSI or control, format, separator and default-ignorable (Cc/Cf/Zl/Zp/DICP) characters. | — | | +| **Sn4.1** | After **F1** fix: `has_dangerous_chars()` is applied to `reason`, `session`, `host`, `version`, `id`, `requester` in `validate_request`, covering both MCP and direct-socket paths; regression test (widened in #86; class checked exhaustively against the UCD; Kani proves string/char agreement). | 2 | [discharged] | | **G4.2** | The resolved absolute path of argv[0] is shown, with `-> target` when it is a symlink, so redirection cannot be hidden. | — | | | **Sn4.2** | `src/tui.rs` path canonicalisation + explicit failure message. | 1 | [discharged] | | **G4.3** | A large command cannot push the real command or the `[y/N]` line off-screen. | — | | diff --git a/docs/security-audit.md b/docs/security-audit.md index 8f4ba04..7f529db 100644 --- a/docs/security-audit.md +++ b/docs/security-audit.md @@ -118,6 +118,7 @@ and covers both the MCP and direct-socket paths. Residual after fix: printable-r Unicode look-alikes/NBSP in `reason` — a far weaker, passive social-engineering vector that cannot hide the real command (documented, see F3 for the length dimension). Regression test mirrors the existing argv bidi/control tests in `tests/validation.rs`. +Class widened under #86 (to Cc/Cf/Zl/Zp/DICP; filesystem-derived `Resolves:` paths escaped). --- diff --git a/docs/security.md b/docs/security.md index 797730e..873fa59 100644 --- a/docs/security.md +++ b/docs/security.md @@ -24,10 +24,11 @@ in [usage.md](usage.md)). **No shell invocation:** commands are executed via `Command::new(argv[0]).args(…)`, never `sh -c`. This prevents `;`, `|`, `&&` injection. -**Input validation:** argv and env strings are rejected if they contain control -characters (0x00–0x1F except tab), zero-width characters (U+200B–U+200F), or -bidi override characters (U+202A–U+202E, U+2066–U+2069) that could mislead -the user during TUI approval. +**Input validation:** argv and env strings are rejected if they contain control, +format, separator or default-ignorable characters (Unicode Cc, Cf, Zl, Zp and +Default_Ignorable_Code_Point, except tab: e.g. ESC, DEL, C1, soft hyphen, +zero-width, bidi controls, BOM, tag characters, variation selectors) that could +mislead the user during TUI approval. **Replay protection:** request UUIDs are tracked in a set that is cleared every 1000 entries. Duplicate IDs are rejected. Requests must carry a non-empty diff --git a/docs/threat-model.md b/docs/threat-model.md index 39ff5fb..982f29c 100644 --- a/docs/threat-model.md +++ b/docs/threat-model.md @@ -70,7 +70,7 @@ invariant at a given boundary are omitted. | STRIDE | Threat | Control | Ref | |--------|--------|---------|-----| -| Spoofing | ANSI / control / bidi sequences forge a benign-looking command in the prompt. | `has_dangerous_chars()` rejects control/zero-width/bidi on every displayed field; resolved absolute path of argv[0] shown with `-> target` on symlinks. | G4.1, G4.2 / F1 | +| Spoofing | ANSI / control / bidi sequences forge a benign-looking command in the prompt. | `has_dangerous_chars()` rejects control, format, separator and default-ignorable (Cc/Cf/Zl/Zp/DICP) characters on every displayed field; resolved absolute path of argv[0] shown with `-> target` on symlinks; filesystem-derived `Resolves:` paths escaped (#86). | G4.1, G4.2 / F1 | | Tampering | A huge argument pushes the real command and `[y/N]` off-screen. | Displayed command length bounded with a hidden-bytes marker. | G4.3 / F3 | | DoS | Operator never answers, leaving the gate open. | 60 s timeout, default **deny**. | G5.2 | | Elevation | Social-engineer the human into approving. | Covered by G4; residual printable-range look-alikes accepted. | G4.4 (residual) | @@ -186,6 +186,10 @@ is unaccounted for. The residuals — already on record and accepted — are: or the multiplexer's socket. - **3.4 — look-alike `reason` (F1 residual).** Printable Unicode can mislead but cannot conceal the real command line, which is printed separately. + Combining overlays (U+0334–0338), RTL letters and whitespace look-alikes + (U+00A0, U+2000–200A, U+3000) remain accepted after #86: they are printable, + and `shquote` single-quotes any non-ASCII token, so they cannot sit next to an + operator. - **4.2 — SSH first-contact MITM (assumption A4).** The ssh invocation sets no `StrictHostKeyChecking`; safety depends on the remote being in `known_hosts` first, or configuring `StrictHostKeyChecking=accept-new`. diff --git a/docs/usage.md b/docs/usage.md index 1a69523..cf5601d 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -225,8 +225,9 @@ declared one), `host`, `privileged`, `command` (only for requests that passed validation), `detail` (the error sent to the client), `status` and `exit_codes` (for requests that ran). Request `env` values, `reason`, and the raw bytes of an invalid request are never -recorded. Request-derived strings are clipped to 256 characters, and control, -bidi and zero-width characters are written as `\u{…}` escapes (as on stderr), so +recorded. Request-derived strings are clipped to 256 characters, and tab, +newline and every character the prompt forbids (control, format, separator and +default-ignorable) are written as `\u{…}` escapes (as on stderr), so the file is safe to `cat` or `tail -f` in a terminal. The file belongs to the daemon's UID, which is also the requester's UID, so a From 8c65706c2144e57e840fd777a8c01d9e247c19d3 Mon Sep 17 00:00:00 2001 From: Cuihtlauac ALVARADO Date: Fri, 20 Nov 2026 15:56:20 +0100 Subject: [PATCH 6/6] chore: review nits C2: use set-theory symbols in the changelog rule, as in the DANGEROUS_RANGES doc comment. Co-Authored-By: Claude Opus 5.5 Signed-off-by: Cuihtlauac ALVARADO --- changelog.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/changelog.md b/changelog.md index bc69d83..594760c 100644 --- a/changelog.md +++ b/changelog.md @@ -9,7 +9,7 @@ for the assurance-ladder context behind the security-formalisation entries. only. DEL and C1 (NEL, CSI, OSC), soft hyphen, ALM, line/paragraph separators, word joiner and invisible operators, BOM, tag characters and variation selectors all reached the approval prompt. The class is now one -rule, `c != TAB && c in Cc u Cf u Zl u Zp u Default_Ignorable_Code_Point`, +rule, `c ≠ TAB ∧ c ∈ Cc ∪ Cf ∪ Zl ∪ Zp ∪ Default_Ignorable_Code_Point`, held as a table built from the Unicode 16.0.0 UCD (`protocol::DANGEROUS_RANGES`) and reused by the audit-record and `--log-json` escapers.