From 2d3f2f986a61789254cf3b9e52c660d2789459c4 Mon Sep 17 00:00:00 2001 From: blockmandev <194144408+blockmandev@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:57:18 -0600 Subject: [PATCH 1/5] permissions, guards: read bash's $'...' quoting the way bash does Inside $'...' a backslash escapes the next character, a quote included, so $'\'' is one quote and the ; after it is a real separator. The permission rules' splitter and the protected-path guard's lexer both read it as a plain '...', where the backslash is just a character, and took the rest of the line for one quoted argument: - `echo $'\'' ; rm -rf x #'` was allowed by Bash(echo:*), and bash runs the rm (checked with real bash). - `echo $'\'' ; echo x > tests/a.rs #'` wrote a protected file unseen. src/ansi_c.rs decodes $'...' as bash does (man bash, QUOTING) and is used by permissions::rules (split_into, substitution, words, unquote) and guards::shell (lex, substitution). $$ is read as the pid, so a quote after it stays an ordinary one; $"..." is read as "...". A part with $'...' or $"..." is opaque, so no allow rule passes it. Deny and ask rules are also matched against each form unquoted: `$'\x72m' -rf /`, `$'bash' -c '...'` and plain `'rm' -rf /` or `sudo "rm" -rf /` all run rm, and a deny on rm -rf now meets them. Tests fail with the fix taken out: the allow and deny cases come back Allow, and the guard reports no write target. --- src/ansi_c.rs | 151 +++++++++++++++++++++++++++++++++ src/guards/shell.rs | 64 ++++++++++++++ src/lib.rs | 1 + src/permissions/rules.rs | 90 +++++++++++++++++--- src/permissions/rules_tests.rs | 65 ++++++++++++++ 5 files changed, 360 insertions(+), 11 deletions(-) create mode 100644 src/ansi_c.rs diff --git a/src/ansi_c.rs b/src/ansi_c.rs new file mode 100644 index 0000000..cb3ac55 --- /dev/null +++ b/src/ansi_c.rs @@ -0,0 +1,151 @@ +//! Bash's ANSI-C quoting, `$'…'`, read the way bash reads it. +//! +//! Inside `$'…'` a backslash escapes the next character, a quote included, so +//! `$'\''` is ONE quote character and whatever follows the closing quote is +//! shell syntax again. Read as a plain `'…'`, where a backslash is just a +//! character, the same text looks like a quote that runs on: a `;` and the +//! command after it are taken for one quoted argument. Every reader of a +//! command line that decides what runs must agree with bash here, or a command +//! hides behind the quote. +//! +//! Used by the two such readers: +//! - `permissions::rules` — `split_into`, `substitution`, `words` and +//! `unquote`: which commands a line holds, for the allow / ask / deny rules. +//! - `guards::shell` — `lex` and `Lexer::substitution`: which files a command +//! writes, for the protected-path guard. +//! +//! `$"…"` (a double-quoted string translated by the locale) needs nothing +//! here: past its `$` it is read exactly as `"…"`. + +/// The text of the `$'…'` whose body starts at `start` (just past `$'`), +/// decoded as bash decodes it (`man bash`, QUOTING), and the index just past +/// its closing quote. Unterminated: the rest of `chars`, decoded. +#[must_use] +pub fn quoted(chars: &[char], start: usize) -> (String, usize) { + let mut out = String::new(); + let mut i = start; + while i < chars.len() { + let c = chars[i]; + i += 1; + if c == '\'' { + return (out, i); + } + if c != '\\' { + out.push(c); + continue; + } + let Some(&escaped) = chars.get(i) else { + out.push('\\'); + break; + }; + i += 1; + match escaped { + 'a' => out.push('\u{7}'), + 'b' => out.push('\u{8}'), + 'e' | 'E' => out.push('\u{1b}'), + 'f' => out.push('\u{c}'), + 'n' => out.push('\n'), + 'r' => out.push('\r'), + 't' => out.push('\t'), + 'v' => out.push('\u{b}'), + '\\' | '\'' | '"' | '?' => out.push(escaped), + // `\nnn`: one to three octal digits, the first already read. + '0'..='7' => { + let (rest, used) = digits(chars, i, 8, 2); + i += used; + let value = (escaped as u32 - '0' as u32) * 8u32.pow(used as u32) + rest; + push_code(&mut out, value & 0xff); + } + 'x' | 'u' | 'U' => { + let most = match escaped { + 'x' => 2, + 'u' => 4, + _ => 8, + }; + let (value, used) = digits(chars, i, 16, most); + if used == 0 { + // No digits: bash keeps the escape as written. + out.push('\\'); + out.push(escaped); + } else { + i += used; + push_code(&mut out, value); + } + } + // `\cx`: the control character of `x`. + 'c' => match chars.get(i) { + Some(&x) => { + i += 1; + push_code(&mut out, x as u32 & 0x1f); + } + None => out.push_str("\\c"), + }, + other => { + out.push('\\'); + out.push(other); + } + } + } + (out, chars.len()) +} + +/// Up to `most` digits in `radix` from `start`: their value and how many. +fn digits(chars: &[char], start: usize, radix: u32, most: usize) -> (u32, usize) { + let mut value = 0u32; + let mut used = 0; + while used < most { + let Some(digit) = chars.get(start + used).and_then(|c| c.to_digit(radix)) else { + break; + }; + value = value.saturating_mul(radix).saturating_add(digit); + used += 1; + } + (value, used) +} + +fn push_code(out: &mut String, code: u32) { + out.push(char::from_u32(code).unwrap_or(char::REPLACEMENT_CHARACTER)); +} + +#[cfg(test)] +mod tests { + use super::quoted; + + fn decode(body: &str) -> (String, usize) { + let chars: Vec = body.chars().collect(); + quoted(&chars, 0) + } + + #[test] + fn an_escaped_quote_does_not_close_the_string() { + assert_eq!(decode(r"\'' ; rm"), ("'".to_string(), 3)); + assert_eq!(decode(r"it\'s' tail"), ("it's".to_string(), 6)); + } + + #[test] + fn escapes_decode_as_bash_does() { + for (body, meant) in [ + (r"a\tb'", "a\tb"), + (r"\x72m'", "rm"), + (r"\x7'", "\u{7}"), + (r"\162m'", "rm"), + (r"\0'", "\0"), + (concat!("\\", "u0072m'"), "rm"), + (r"\U00000072m'", "rm"), + (r"\cA'", "\u{1}"), + (r"\\'", "\\"), + (r#"\"\?'"#, "\"?"), + (r"\e\E'", "\u{1b}\u{1b}"), + (r"\z'", "\\z"), + (r"\xg'", "\\xg"), + ] { + assert_eq!(decode(body).0, meant, "`$'{body}`"); + } + } + + #[test] + fn an_unterminated_string_runs_to_the_end() { + assert_eq!(decode(r"abc\"), ("abc\\".to_string(), 4)); + assert_eq!(decode("abc"), ("abc".to_string(), 3)); + } +} diff --git a/src/guards/shell.rs b/src/guards/shell.rs index 2943747..48f2702 100644 --- a/src/guards/shell.rs +++ b/src/guards/shell.rs @@ -498,6 +498,23 @@ fn lex(text: &str) -> Lexed { } '`' => index = lexer.substitution(&chars, index), '$' if matches!(next, Some('(' | '{')) => index = lexer.substitution(&chars, index), + // `$$`, the shell's pid: a quote after it is an ordinary one. + '$' if next == Some('$') => { + lexer.word.push_str("$$"); + lexer.started = true; + index += 2; + } + // `$'…'`: escapes decoded, ending where bash ends it + // (`crate::ansi_c`) — a backslash escapes the quote. + '$' if next == Some('\'') => { + let (text, end) = crate::ansi_c::quoted(&chars, index + 2); + lexer.word.push_str(&text); + lexer.started = true; + lexer.quoted = true; + index = end; + } + // `$"…"` is read as `"…"`. + '$' if next == Some('"') => index += 1, '#' if !lexer.started => { while index < chars.len() && chars[index] != '\n' { index += 1; @@ -647,6 +664,14 @@ impl Lexer { index += 2; continue; } + if c == '$' && chars.get(index + 1) == Some(&'$') { + index += 2; + continue; + } + if c == '$' && chars.get(index + 1) == Some(&'\'') { + index = crate::ansi_c::quoted(chars, index + 2).1; + continue; + } // A quoted `)` does not close `$(...)`: a quoted span is skipped // whole, or the rest of the command would be read off by one. if matches!(c, '\'' | '"') && c != close { @@ -756,6 +781,45 @@ mod tests { ); } + /// **`$'…'` ENDS WHERE BASH SAYS.** A backslash escapes its quote, so + /// `$'\''` is one character and the redirect after the `;` is real. Read + /// as a plain `'…'`, the rest of the line looked quoted and the write to a + /// protected file went unseen. + #[test] + fn an_ansi_c_quote_does_not_hide_a_redirect_after_it() { + for command in [ + r"echo $'\'' ; echo x > tests/a.rs #'", + r"echo $'it\'s' && echo x >tests/a.rs #'", + r"echo $(echo $'\'') ; echo x > tests/a.rs #'", + ] { + assert_eq!( + targets(command), + vec!["tests/a.rs".to_string()], + "{command}" + ); + } + assert!( + targets(r"echo $'a > tests/a.rs'").is_empty(), + "a `>` inside `$'…'` is text" + ); + } + + /// A target spelled with `$'…'` or `$"…"` is the file bash writes. + #[test] + fn a_target_in_ansi_c_or_locale_quotes_is_the_file_written() { + for command in [ + r"echo x > $'tests/a.rs'", + r"echo x > $'tests\x2fa.rs'", + r#"echo x > $"tests/a.rs""#, + ] { + assert_eq!( + targets(command), + vec!["tests/a.rs".to_string()], + "{command}" + ); + } + } + /// The body of a heredoc given to `cat` is what is written, not where. #[test] fn heredoc_data_is_not_a_target() { diff --git a/src/lib.rs b/src/lib.rs index cd0341a..2f136cd 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,6 +4,7 @@ pub mod acp_agent; pub mod admin; pub mod agent; +pub mod ansi_c; pub mod ask; pub mod auditor; pub mod brief; diff --git a/src/permissions/rules.rs b/src/permissions/rules.rs index 2d6bd68..f889edb 100644 --- a/src/permissions/rules.rs +++ b/src/permissions/rules.rs @@ -320,7 +320,8 @@ pub struct Segment { /// As written, whitespace-collapsed. What an allow rule is matched with. pub text: String, /// The forms a deny or ask rule is matched with: `text`, and `text` with - /// leading assignments and wrapper commands peeled off, one at a time. + /// leading assignments and wrapper commands peeled off, one at a time; + /// each as written and unquoted. pub peeled: Vec, /// A part no allow rule may pass: it substitutes a command, redirects, /// or hands a string to a shell. @@ -431,6 +432,30 @@ fn split_into(line: &str, out: &mut Vec, depth: usize) { bare.push_str("__"); i += 2; } + // `$$`, the shell's pid: a quote after it is an ordinary one. + '$' if next == Some('$') => { + raw.push_str("$$"); + bare.push_str("$$"); + i += 2; + } + // `$'…'`: a backslash escapes the quote, so it ends where bash + // says (`crate::ansi_c`). What it spells is decided by escapes, + // so no allow rule passes the part. + '$' if next == Some('\'') => { + let (_, end) = crate::ansi_c::quoted(&chars, i + 2); + raw.extend(&chars[i..end]); + bare.extend(std::iter::repeat_n('_', end - i)); + opaque = true; + i = end; + } + // `$"…"`: a double-quoted string the locale may translate into + // other text; past the `$` it is read as `"…"`. + '$' if next == Some('"') => { + raw.push(c); + bare.push('_'); + opaque = true; + i += 1; + } '\'' | '"' => { quote = Some(c); raw.push(c); @@ -540,6 +565,14 @@ fn substitution(chars: &[char], start: usize) -> (String, usize) { i += 2; continue; } + '$' if chars.get(i + 1) == Some(&'$') => { + i += 2; + continue; + } + '$' if chars.get(i + 1) == Some(&'\'') => { + i = crate::ansi_c::quoted(chars, i + 2).1; + continue; + } '\'' | '"' => quote = Some(c), '(' => depth += 1, ')' => { @@ -622,14 +655,18 @@ fn words(text: &str) -> Vec { let mut words = Vec::new(); let mut word = String::new(); let mut quote: Option = None; - let mut chars = text.chars().peekable(); - while let Some(c) = chars.next() { + let chars: Vec = text.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + i += 1; match quote { Some(q) => { word.push(c); if c == '\\' && q == '"' { - if let Some(n) = chars.next() { + if let Some(&n) = chars.get(i) { word.push(n); + i += 1; } } else if c == q { quote = None; @@ -641,14 +678,25 @@ fn words(text: &str) -> Vec { words.push(std::mem::take(&mut word)); } } + '$' if chars.get(i) == Some(&'$') => { + word.push_str("$$"); + i += 1; + } + // `$'…'`, kept as written, to where bash ends it. + '$' if chars.get(i) == Some(&'\'') => { + let (_, end) = crate::ansi_c::quoted(&chars, i + 1); + word.extend(&chars[i - 1..end]); + i = end; + } '\'' | '"' => { quote = Some(c); word.push(c); } '\\' => { word.push(c); - if let Some(n) = chars.next() { + if let Some(&n) = chars.get(i) { word.push(n); + i += 1; } } _ => word.push(c), @@ -661,18 +709,35 @@ fn words(text: &str) -> Vec { words } -/// A word with its outer quotes and backslashes removed. +/// A word with its outer quotes and backslashes removed, and a `$'…'` in it +/// decoded (`crate::ansi_c`): `$'\x72m'` is `rm`. fn unquote(word: &str) -> String { let mut out = String::new(); let mut quote: Option = None; - let mut chars = word.chars(); - while let Some(c) = chars.next() { + let chars: Vec = word.chars().collect(); + let mut i = 0; + while i < chars.len() { + let c = chars[i]; + let next = chars.get(i + 1).copied(); + i += 1; match (quote, c) { + (None, '$') if next == Some('$') => { + out.push_str("$$"); + i += 1; + } + (None, '$') if next == Some('\'') => { + let (text, end) = crate::ansi_c::quoted(&chars, i + 1); + out.push_str(&text); + i = end; + } + // `$"…"` is `"…"`. + (None, '$') if next == Some('"') => {} (None, '\'' | '"') => quote = Some(c), (Some(q), _) if c == q => quote = None, (None | Some('"'), '\\') => { - if let Some(n) = chars.next() { + if let Some(n) = next { out.push(n); + i += 1; } } _ => out.push(c), @@ -722,10 +787,12 @@ fn flag_takes_value(wrapper: &str, flag: &str) -> bool { } /// `text`, then `text` with each leading assignment and wrapper peeled off in -/// turn; and the script, when the command hands one to a shell. +/// turn — each form also unquoted, since `'rm' -rf /` and `$'\x72m' -rf /` run +/// `rm` — and the script, when the command hands one to a shell. fn peel(text: &str) -> (Vec, Option) { let all = words(text); - let mut forms = vec![all.join(" ")]; + let plain: Vec = all.iter().map(|w| unquote(w)).collect(); + let mut forms = vec![all.join(" "), plain.join(" ")]; let mut at = 0; while at < all.len() { let word = &all[at]; @@ -748,6 +815,7 @@ fn peel(text: &str) -> (Vec, Option) { } if at < all.len() { forms.push(all[at..].join(" ")); + forms.push(plain[at..].join(" ")); } } // `sh -c '