diff --git a/crates/bashkit/Cargo.toml b/crates/bashkit/Cargo.toml index df9121abe..42abc3e5c 100644 --- a/crates/bashkit/Cargo.toml +++ b/crates/bashkit/Cargo.toml @@ -462,8 +462,21 @@ tokio = { version = "1", features = ["rt-multi-thread", "fs"] } # (TM-DOS-142, interpreter/grow_stack.rs). Already in the tree via Monty. stacker = "0.1.25" # markkit builtin (native only: markkit-cli needs tokio's multi-thread rt). -markkit-cli = { version = "0.3.1", default-features = false, features = ["all_formats"], optional = true } -markkit = { version = "0.3.1", default-features = false, features = ["all_formats"], optional = true } +# +# Capped below 0.3.2 to hold the consumer Rust floor. markkit 0.3.2 moved from +# `mail-parser ^0.11` to `^1.0`, and every mail-parser 1.x declares +# `rust-version = 1.98`, so a fresh external consumer resolved on 1.96 (the +# required `msrv` job, which deliberately ignores this repository's Cargo.lock) +# stops at `rustc 1.96.0 is not supported by mail-parser@1.0.2`. The workspace +# lock already pins 0.3.1, so this only stops fresh resolution drifting past +# the floor -- exactly the drift that job exists to catch. markkit-cli is +# capped in lockstep because markkit-cli 0.3.3 requires `markkit ^0.3.3`. +# +# Lift both together once the floor rises to 1.98 or later on purpose, or once +# markkit's mail-parser dependency supports 1.96 again. See +# knowledge/operations/testing.md#rust-toolchain-and-consumer-compatibility. +markkit-cli = { version = ">=0.3.1, <0.3.2", default-features = false, features = ["all_formats"], optional = true } +markkit = { version = ">=0.3.1, <0.3.2", default-features = false, features = ["all_formats"], optional = true } # fetchkit builtin (native only). No `reqwest-tls`: all traffic goes through # bashkit's HttpClient, so fetchkit adds no TLS stack. fetchkit-cli = { version = "0.7.2", default-features = false, features = ["docs-pdf", "docs-markkit"], optional = true } diff --git a/crates/bashkit/fuzz/fuzz_targets/printf_fuzz.rs b/crates/bashkit/fuzz/fuzz_targets/printf_fuzz.rs index ab8939076..5dcb79337 100644 --- a/crates/bashkit/fuzz/fuzz_targets/printf_fuzz.rs +++ b/crates/bashkit/fuzz/fuzz_targets/printf_fuzz.rs @@ -35,9 +35,11 @@ fuzz_target!(|data: &[u8]| { // The shape need not be in the input -- the message separator's colon // completes it, so an argument of `Undefined:` renders // `printf: Undefined:: invalid number` and spells `Undefined::` across - // the join. `assert_fuzz_invariants`' script attribution cannot see a - // join at the slot boundary, so gate at the input layer as - // `arithmetic_fuzz` and `glob_fuzz` do. Nightly run after 304. + // the join. `assert_fuzz_invariants` now attributes that join itself + // (`script_explains` decomposes the pattern, not the whole script), so + // this gate is no longer load-bearing for banned shapes; it is kept + // because it also skips inputs that forge the host canary, which the + // detector hands libFuzzer the bytes to reconstruct. if bashkit::testing::input_echo_would_trip(input) { return; } diff --git a/crates/bashkit/src/parser/lexer.rs b/crates/bashkit/src/parser/lexer.rs index 57953e4cf..19d2c20d1 100644 --- a/crates/bashkit/src/parser/lexer.rs +++ b/crates/bashkit/src/parser/lexer.rs @@ -37,6 +37,29 @@ const DEFAULT_MAX_SUBST_DEPTH: usize = 50; const QUOTED_SEGMENT_START: char = '\u{1e}'; const QUOTED_SEGMENT_END: char = '\u{1f}'; +/// Append one literal source character to word text, hiding the lexer's own +/// quote-boundary markers behind the NUL literal sentinel. +/// +/// The markers are in-band: `parse_word` reads a bare `\u{1e}`/`\u{1f}` as a +/// quotedness boundary and consumes it. A marker byte that came from the +/// *script* is data, though — 0x1e/0x1f are ordinary record/unit separators in +/// real data, and `IFS=$'\x1f'` is a common idiom — so it has to reach +/// `parse_word` escaped, exactly as a single-quoted segment already does via +/// `push_literal_with_escaped_dollar`. +/// +/// Unescaped, the byte was silently deleted from unquoted and double-quoted +/// text: `printf '[%s]' A<1f>B` printed `[AB]` where bash prints `[A<1f>B]`. +/// That also broke the fuzz harness' leak attribution, which compares a +/// builtin's stderr against the script that produced it — the script carried +/// `target/debug/<1f><1f><1f>deps/` and stderr the banned host path +/// `target/debug/deps/` (nightly fuzz `tomlq_fuzz`). +fn push_literal_char(word: &mut String, ch: char) { + if matches!(ch, QUOTED_SEGMENT_START | QUOTED_SEGMENT_END) { + word.push('\x00'); + } + word.push(ch); +} + #[derive(Default)] struct ContinuationFlags { has_unquoted_expansion: bool, @@ -901,7 +924,7 @@ impl<'a> Lexer<'a> { } _ => { word.push('\\'); - word.push(next); + push_literal_char(&mut word, next); self.advance(); } } @@ -937,13 +960,14 @@ impl<'a> Lexer<'a> { } continue; } - if quote_char == '\'' && matches!(c, '$' | '\u{1e}' | '\u{1f}') { + if quote_char == '\'' && c == '$' { // Preserve literal '$' semantics from single-quoted // segments when concatenated into an existing word // (e.g. foo'$(id)' or VAR='${HOME}'). word.push('\x00'); } - word.push(c); + // A marker byte is data inside either quote kind. + push_literal_char(&mut word, c); self.advance(); } if !closed { @@ -1016,7 +1040,7 @@ impl<'a> Lexer<'a> { // reserved word, not a metacharacter, so it stays inside the // word unless it stands alone (`echo }}` prints `}}`). `{` // keeps a brace tail in the word (`[k]="v"{1,2}`). - word.push(ch); + push_literal_char(&mut word, ch); self.advance(); } else { break; @@ -1101,7 +1125,7 @@ impl<'a> Lexer<'a> { } _ => { word.push('\\'); - word.push(next); + push_literal_char(&mut word, next); self.advance(); } } @@ -1142,13 +1166,14 @@ impl<'a> Lexer<'a> { } continue; } - if quote_char == '\'' && matches!(c, '$' | '\u{1e}' | '\u{1f}') { + if quote_char == '\'' && c == '$' { // Preserve literal '$' semantics from single-quoted // segments when concatenated into an existing word // (e.g. foo'$(id)' or VAR='${HOME}'). word.push('\x00'); } - word.push(c); + // A marker byte is data inside either quote kind. + push_literal_char(&mut word, c); self.advance(); } if !closed { @@ -1217,7 +1242,7 @@ impl<'a> Lexer<'a> { } _ => { word.push('\\'); - word.push(next); + push_literal_char(&mut word, next); self.advance(); } } @@ -1396,7 +1421,9 @@ impl<'a> Lexer<'a> { if Self::is_glob_escape_char(next) { quoted_ranges.push((word.len(), word.len() + next.len_utf8())); } - word.push(next); + // A marker is never a glob escape char, so the range + // above is unaffected by the sentinel this may add. + push_literal_char(&mut word, next); self.advance(); } } else { @@ -1413,7 +1440,10 @@ impl<'a> Lexer<'a> { self.advance(); let mut depth = 1; while let Some(c) = self.peek_char() { - word.push(c); + // A marker is never `(`, `)`, a quote or a backslash, so + // the sentinel this may add leaves the depth counting, + // `extglob_escaped` and the `word.pop()` arms below alone. + push_literal_char(&mut word, c); self.advance(); match c { '(' => depth += 1, @@ -1430,7 +1460,7 @@ impl<'a> Lexer<'a> { word.pop(); Self::push_extglob_literal(&mut word, esc); } else { - word.push(esc); + push_literal_char(&mut word, esc); } self.advance(); } @@ -1478,7 +1508,7 @@ impl<'a> Lexer<'a> { if matches!(ch, '*' | '?' | '[') { has_unquoted_glob = true; } - word.push(ch); + push_literal_char(&mut word, ch); self.advance(); } else if matches!(ch, ' ' | '\t' | '&' | '|' | '<' | '>' | '(' | ')') && self.spaced_subscript @@ -1654,7 +1684,7 @@ impl<'a> Lexer<'a> { if matches!(ch, '\x00' | '$') { content.push('\x00'); } - content.push(ch); + push_literal_char(content, ch); self.advance(); } if !closed { @@ -1731,7 +1761,7 @@ impl<'a> Lexer<'a> { if next == '$' { content.push('\x00'); } - content.push(next); + push_literal_char(content, next); self.advance(); flags.quoted_ranges.push((start, content.len())); } @@ -1743,9 +1773,12 @@ impl<'a> Lexer<'a> { || (self.extglob_bang && content.ends_with('!')) => { // `"$*"*@(.py|cc)`: an extglob group after a quoted start. + // Same marker handling as the `read_word_from` twin: a + // marker is never `(`, `)` or a backslash, so the sentinel + // leaves the depth counting alone. let mut depth = 0usize; while let Some(c) = self.peek_char() { - content.push(c); + push_literal_char(content, c); self.advance(); match c { '(' => depth += 1, @@ -1757,7 +1790,7 @@ impl<'a> Lexer<'a> { } '\\' => { if let Some(e) = self.peek_char() { - content.push(e); + push_literal_char(content, e); self.advance(); } } @@ -1771,7 +1804,7 @@ impl<'a> Lexer<'a> { if matches!(ch, '*' | '?' | '[' | '{') { flags.has_unquoted_glob = true; } - content.push(ch); + push_literal_char(content, ch); self.advance(); } _ => break, @@ -1914,7 +1947,11 @@ impl<'a> Lexer<'a> { Some(n) => { self.advance(); word.push('\\'); - word.push(n); + if subscript > 0 { + word.push(n); + } else { + push_literal_char(word, n); + } } None => word.push('\\'), }, @@ -1952,7 +1989,7 @@ impl<'a> Lexer<'a> { word.push('\\'); if let Some(n) = self.peek_char() { self.advance(); - word.push(n); + push_literal_char(word, n); } continue; } @@ -1966,7 +2003,7 @@ impl<'a> Lexer<'a> { '{' | '}' => word.push('\x00'), _ => {} } - word.push(q); + push_literal_char(word, q); } if !closed { return Err("unterminated double quote".to_string()); @@ -2007,7 +2044,10 @@ impl<'a> Lexer<'a> { break; } } - _ => word.push(c), + // Subscript text stays verbatim for subscript evaluation; see + // `read_param_expansion_into`. + _ if subscript > 0 => word.push(c), + _ => push_literal_char(word, c), } } Ok(()) @@ -2243,6 +2283,11 @@ impl<'a> Lexer<'a> { /// Push one quoted character of an extglob group so it stays literal: /// pattern metacharacters get a backslash, `$`/`` ` `` the NUL sentinel. + /// + /// The final push goes through [`push_literal_char`] so a quote-boundary + /// marker byte gets the sentinel too, without a backslash it does not need + /// (it is no glob metacharacter). Without that, `@('A<1f>B')` lost the byte + /// while the unquoted `@(A<1f>B)` kept it. fn push_extglob_literal(word: &mut String, ch: char) { if Self::is_glob_escape_char(ch) || matches!(ch, '"' | '\'') { word.push('\\'); @@ -2250,7 +2295,7 @@ impl<'a> Lexer<'a> { word.push('\\'); word.push('\x00'); } - word.push(ch); + push_literal_char(word, ch); } fn is_glob_escape_char(ch: char) -> bool { @@ -2373,7 +2418,7 @@ impl<'a> Lexer<'a> { } _ => { content.push('\\'); - content.push(next); + push_literal_char(content, next); self.advance(); } } @@ -2401,7 +2446,7 @@ impl<'a> Lexer<'a> { } '`' => self.read_dquote_backtick_into(content), _ => { - content.push(ch); + push_literal_char(content, ch); self.advance(); } } @@ -2653,8 +2698,23 @@ impl<'a> Lexer<'a> { /// before parser fuel is checked, so recursion here can overflow the host stack. fn read_param_expansion_into(&mut self, content: &mut String) -> Result<(), String> { let mut depth = 1usize; + // Subscript text is handed to arithmetic (`${a[i+1]}`) or associative + // key expansion (`${m[k]}`), which resolve quoting themselves and have + // their own handling of marker bytes, so it is copied verbatim and + // `push_literal_char` is applied only to operand text. + let mut subscript = 0usize; while let Some(c) = self.peek_char() { match c { + '[' => { + subscript += 1; + content.push(c); + self.advance(); + } + ']' => { + subscript = subscript.saturating_sub(1); + content.push(c); + self.advance(); + } '{' => { if depth >= self.max_subst_depth { return Err("parameter expansion nesting too deep".to_string()); @@ -2689,7 +2749,7 @@ impl<'a> Lexer<'a> { content.push('\\'); if let Some(n) = self.peek_char() { self.advance(); - content.push(n); + push_literal_char(content, n); } } '$' if self.peek_char() == Some('{') => { @@ -2705,7 +2765,7 @@ impl<'a> Lexer<'a> { content.push('\x00'); content.push(q); } - _ => content.push(q), + _ => push_literal_char(content, q), } } } @@ -2721,7 +2781,19 @@ impl<'a> Lexer<'a> { if matches!(q, '{' | '}') { content.push('\x00'); } - content.push(q); + // Only the plain `'...'` span needs the sentinel. An + // ANSI-C `$'...'` span is decoded again downstream and + // that decode does not consume the literal sentinel, so + // escaping there leaked a raw NUL into the value + // (`"${x:-$'A<1f>B'}"` became `A\0<1f>B`); its markers + // already survive unescaped. The plain span is not + // decoded again, so without the sentinel it lost them + // (`"${x:-'A<1f>B'}"` became `'AB'`). + if ansi_c { + content.push(q); + } else { + push_literal_char(content, q); + } if ansi_c && q == '\\' { if let Some(n) = self.peek_char() { self.advance(); @@ -2767,7 +2839,11 @@ impl<'a> Lexer<'a> { } _ => { content.push('\\'); - content.push(esc); + if subscript > 0 { + content.push(esc); + } else { + push_literal_char(content, esc); + } self.advance(); } } @@ -2792,7 +2868,11 @@ impl<'a> Lexer<'a> { } } _ => { - content.push(c); + if subscript > 0 { + content.push(c); + } else { + push_literal_char(content, c); + } self.advance(); } } @@ -2855,7 +2935,9 @@ impl<'a> Lexer<'a> { if c == '\n' { break; } - word.push(c); + // A marker is never `(` or `)`, so depth counting is + // unaffected by the sentinel this may add. + push_literal_char(&mut word, c); self.advance(); match c { '(' => depth += 1, @@ -2875,7 +2957,7 @@ impl<'a> Lexer<'a> { if matches!(ch, '(' | ')') { break; } - word.push(ch); + push_literal_char(&mut word, ch); self.advance(); if ch == ']' { break; @@ -2891,7 +2973,7 @@ impl<'a> Lexer<'a> { return self.read_word_starting_with(&word); } else if self.is_word_char(ch) || matches!(ch, '{' | '}') { // Braces are word text too (`[k]=v{1,2}`, `[ab]{x,y}`). - word.push(ch); + push_literal_char(&mut word, ch); self.advance(); } else { break; diff --git a/crates/bashkit/src/parser/mod.rs b/crates/bashkit/src/parser/mod.rs index cb46a69af..fe7a400a3 100644 --- a/crates/bashkit/src/parser/mod.rs +++ b/crates/bashkit/src/parser/mod.rs @@ -5534,7 +5534,10 @@ pub(crate) fn arith_exec_text(raw: &str) -> String { /// for its own parser (only `\` is removed); backticks become /// `$(...)`. fn heredoc_body_escapes(content: &str) -> String { - if !content.contains(['\\', '`']) && !content.contains("$'") { + // `\u{1e}`/`\u{1f}` are `parse_word`'s quote-boundary markers, so a body + // byte that spells one has to leave here behind the NUL sentinel or it is + // read as a marker and dropped. See `lexer::push_literal_char`. + if !content.contains(['\\', '`', '\u{1e}', '\u{1f}']) && !content.contains("$'") { return content.to_string(); } let mut out = String::with_capacity(content.len()); @@ -5600,6 +5603,10 @@ fn heredoc_body_escapes(content: &str) -> String { } out.push(')'); } + '\u{1e}' | '\u{1f}' => { + out.push('\x00'); + out.push(c); + } _ => out.push(c), } } diff --git a/crates/bashkit/src/testing.rs b/crates/bashkit/src/testing.rs index ffee6cda3..ae536f321 100644 --- a/crates/bashkit/src/testing.rs +++ b/crates/bashkit/src/testing.rs @@ -329,12 +329,32 @@ fn carries_through_expansion(text: &str, needle: &str) -> bool { /// does: the harness applies it to every caller, so a new target cannot /// forget it. /// -/// Padding mirrors [`DIAGNOSTIC_ECHO_PAD`] — a diagnostic wraps the quoted -/// slot in `: ` on both sides, so a shape can be spelled across the join. -/// A shape formed where the slot meets script text *inside* the script is -/// not covered here; [`input_echo_would_trip`] remains the precise gate for -/// that case (run 295's `wZTok:`), which is why the targets that call it -/// keep doing so. +/// # Spelling a shape across the template join +/// +/// The echoed slot is an arbitrary *substring* of the script, and the +/// diagnostic wraps it in its own punctuation, so a banned shape can be +/// spelled as `(tail of the template prefix) ++ (script text) ++ (head of the +/// template suffix)` while appearing nowhere in the script. Padding the whole +/// script with [`DIAGNOSTIC_ECHO_PAD`] only sees a join at the script's own +/// ends, so nightly fuzz run 310 went red on two targets at once: `awk_fuzz` +/// on a program of `{ code:…`, which `awk: cmd. line:1: {program}` renders as +/// ` { code:`, and `printf_fuzz` on an operand of `{ code:`, which +/// `printf: {arg}: invalid number` renders the same way. Both joins are +/// interior, so both scripts looked unexplained. +/// +/// So the decomposition is applied to the *pattern* instead: drop a leading +/// fragment the template's lead could have supplied and a trailing fragment +/// its trail could have supplied, then ask whether the remaining core is +/// script text. Both pads are two bytes, so this is at most nine `contains` +/// calls, and it loosens only the banned shapes that begin with a space or +/// end in a colon (` { code:`, `Tok::`, `Undefined::`, `internal error:`) — +/// every other shape has no fragment to drop and stays absolute. Those four +/// need it: `printf '%d' 'internal error'` really does render +/// `printf: internal error: invalid number` with no panic behind it. +/// +/// An empty core is never accepted. A shape made purely of template text +/// would mean a builtin's own format string spells it, which is a real +/// TM-INF-022 bug and not an echo, so it must keep failing. /// /// # Residual false negative /// @@ -366,8 +386,38 @@ fn carries_through_expansion(text: &str, needle: &str) -> bool { /// hidden is a formatter whose leak is *triggered* by parsing the shape. fn script_explains(script: &str, pat: &str) -> bool { let (lead, trail) = DIAGNOSTIC_ECHO_PAD; - carries_through_expansion(script, pat) - || carries_through_expansion(&format!("{lead}{}{trail}", script.trim()), pat) + for drop_lead in pad_suffixes(lead) { + let Some(rest) = pat.strip_prefix(drop_lead) else { + continue; + }; + for drop_trail in pad_prefixes(trail) { + let Some(core) = rest.strip_suffix(drop_trail) else { + continue; + }; + if !core.is_empty() && carries_through_expansion(script, core) { + return true; + } + } + } + false +} + +/// Every suffix of `pad`, longest first and the empty one last: what a +/// diagnostic's template prefix can contribute immediately left of an echoed +/// operand. See [`script_explains`]. +fn pad_suffixes(pad: &'static str) -> impl Iterator { + pad.char_indices() + .map(move |(i, _)| &pad[i..]) + .chain(std::iter::once("")) +} + +/// Every prefix of `pad`, shortest first and the empty one last: what a +/// diagnostic's template suffix can contribute immediately right of an echoed +/// operand. See [`script_explains`]. +fn pad_prefixes(pad: &'static str) -> impl Iterator { + pad.char_indices() + .map(move |(i, c)| &pad[..i + c.len_utf8()]) + .chain(std::iter::once("")) } /// Trailing halves of the real-shell diagnostic templates that quote user @@ -685,6 +735,68 @@ mod tests { ); } + #[test] + fn banned_shape_spelled_across_the_template_lead_is_an_echo() { + // `printf: {arg}: invalid number` prefixes the operand with `: `, so + // an operand of `{ code:` spells ` { code:` while the script holds + // only `{ code:`. Nightly fuzz run 310 (`printf_fuzz`, `awk_fuzz`). + let result = ExecResult { + stderr: "bash: line 1: printf: { code:: invalid number".into(), + ..Default::default() + }; + assert_fuzz_invariants(&result, "printf '%d' '{ code:'", "join_lead", &[]); + } + + #[test] + fn banned_shape_spelled_across_the_template_trail_is_an_echo() { + // Run 295: `wZTok:` renders `bash: line 1: wZTok:: syntax error …`, + // where the message separator's colon completes `Tok::`. + let result = ExecResult { + stderr: "bash: line 1: wZTok:: syntax error in expression".into(), + ..Default::default() + }; + assert_fuzz_invariants(&result, "echo $((wZTok:))", "join_trail", &[]); + } + + #[test] + fn banned_shape_spelled_across_both_template_joins_is_an_echo() { + // Both halves at once: an operand of `{ code` renders + // `printf: { code: invalid number`, whose ` { code:` is the lead's + // space plus the operand plus the separator's colon. + let result = ExecResult { + stderr: "bash: line 1: printf: { code: invalid number".into(), + ..Default::default() + }; + assert_fuzz_invariants(&result, "printf '%d' '{ code'", "join_both", &[]); + } + + #[test] + #[should_panic(expected = "stderr leaks banned shape ` { code:`")] + fn template_join_attribution_still_needs_the_core_in_the_script() { + // Decomposition only forgives the pad fragments. A script that spells + // none of the cores (` { code:`, `{ code:`, ` { code`, `{ code`) is + // still unexplained, so a Debug shape there is a real leak. + let result = ExecResult { + stderr: "parse failed: { code: 3 } at offset 1".into(), + ..Default::default() + }; + assert_fuzz_invariants(&result, "jq '.a' f.json", "join_unexplained", &[]); + } + + #[test] + #[should_panic(expected = "stderr leaks banned shape `: `")] + fn a_shape_made_only_of_template_text_is_still_a_leak() { + // An empty core would mean the shape is entirely the diagnostic's own + // punctuation — a format string spelling it, not an echo — so it must + // not be excused. Exercised through the per-tool list, since no + // universal shape is a substring of the pad. + let result = ExecResult { + stderr: "tool: boom".into(), + ..Default::default() + }; + assert_fuzz_invariants(&result, "tool run", "empty_core", &[": "]); + } + #[test] #[should_panic(expected = "stderr leaks banned shape `Undefined::`")] fn banned_shape_absent_from_the_script_is_still_a_leak() { diff --git a/crates/bashkit/tests/fuzz_crash_regressions.rs b/crates/bashkit/tests/fuzz_crash_regressions.rs index a637e2301..3c2897588 100644 --- a/crates/bashkit/tests/fuzz_crash_regressions.rs +++ b/crates/bashkit/tests/fuzz_crash_regressions.rs @@ -186,3 +186,79 @@ async fn a_bare_banned_shape_framed_only_by_template_text_is_an_echo() { fuzz_exec(&mut bash, &script, "printf_fuzz", &[]).await; } } + +/// `awk_fuzz` run 310: the awk program was `{ code:…`, and +/// `awk: cmd. line:1: {program}` prefixes it with `line:1: `. The Debug shape +/// ` { code:` is spelled across that join — the leading space is the +/// template's, the rest is the program — so it appears nowhere in the script. +/// Whole-script padding cannot see an interior join, which is why +/// `script_explains` pads the *pattern* instead. +#[tokio::test] +async fn awk_crash_code_shape_across_template_join_is_an_echo_not_a_leak() { + fuzz_init(); + let data = b64("eyBjb2RlOgAAAAAAAABobw=="); + let input = std::str::from_utf8(&data).expect("crash unit is UTF-8"); + let (program, input_data) = match input.find('\n') { + Some(pos) => (&input[..pos], &input[pos + 1..]), + None => (input, "a b c\n1 2 3\n"), + }; + let mut bash = bash(4096); + for script in [ + format!("echo '{}' | awk '{}'", sq(input_data), sq(program)), + format!("echo '{}' | awk -F: '{}'", sq(input_data), sq(program)), + ] { + fuzz_exec(&mut bash, &script, "awk_fuzz", &[]).await; + } +} + +/// `printf_fuzz` run 310: the same interior join one builtin further on. +/// `printf: {arg}: invalid number` prefixes the operand with `printf: `, so an +/// operand of `{ code:` spells ` { code:`. The target's +/// `input_echo_would_trip` gate pads the whole input and so misses it too; +/// attribution in the harness is what has to cover this. +#[tokio::test] +async fn printf_crash_code_shape_across_template_join_is_an_echo_not_a_leak() { + fuzz_init(); + let data = b64("JWNgY2B7IGNvZGU6Cgp7IGNvZGU6Cgo="); + let input = std::str::from_utf8(&data).expect("crash unit is UTF-8"); + let (format_str, args_str) = match input.find('\n') { + Some(pos) => (&input[..pos], &input[pos + 1..]), + None => (input, ""), + }; + let args_joined = args_str + .lines() + .map(|a| format!("'{}'", sq(a))) + .collect::>() + .join(" "); + let mut bash = bash(4096); + for script in [ + format!("printf '{}' {}", sq(format_str), args_joined), + format!("printf -v result '{}' {}", sq(format_str), args_joined), + format!("printf '%d %o %x' {args_joined}"), + ] { + fuzz_exec(&mut bash, &script, "printf_fuzz", &[]).await; + } +} + +/// `tomlq_fuzz` run 310: the query held `target/debug/\x1f\x1f\x1fdeps/`, which +/// is *not* the banned host path — until the diagnostic sanitizes the control +/// bytes out of the quoted operand and `tomlq: path '…' not found` reads +/// `target/debug/deps/`. Attribution compares against the raw script, so it +/// has to account for the same sanitization the renderer applies. +#[tokio::test] +async fn tomlq_crash_control_bytes_sanitized_into_host_path_is_an_echo() { + fuzz_init(); + let data = b64("UwAAAAAnJ0BAQEAnCicAAAAAAAoAdGFyZ2V0L2RlYnVnLx8fH2RlcHMvOgE="); + let input = std::str::from_utf8(&data).expect("crash unit is UTF-8"); + let (toml_doc, query) = match input.find('\n') { + Some(pos) => (&input[..pos], &input[pos + 1..]), + None => (input, "."), + }; + let mut bash = bash(4096); + for script in [ + format!("echo '{}' | tomlq '{}'", sq(toml_doc), sq(query)), + format!("echo '{}' | tomlq", sq(toml_doc)), + ] { + fuzz_exec(&mut bash, &script, "tomlq_fuzz", &[]).await; + } +} diff --git a/crates/bashkit/tests/integration/main.rs b/crates/bashkit/tests/integration/main.rs index 0a4451126..bd051d760 100644 --- a/crates/bashkit/tests/integration/main.rs +++ b/crates/bashkit/tests/integration/main.rs @@ -67,6 +67,7 @@ pub mod markkit_builtin_tests; pub mod memory_growth_security_tests; pub mod mixed_control_tests; pub mod output_file_tests; +pub mod quote_marker_byte_tests; pub mod streaming_command_tests; pub mod tar_files_from_budget_tests; // Both assert named-IANA-zone behavior, which only exists with `tzdata`. diff --git a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs new file mode 100644 index 000000000..fc5f9ec17 --- /dev/null +++ b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs @@ -0,0 +1,365 @@ +//! 0x1e/0x1f in script text are data, not the lexer's quote-boundary markers. +//! +//! `parser::lexer` marks the quoted spans of a mixed word with in-band +//! `\u{1e}`/`\u{1f}` markers that `parse_word` turns into per-part quotedness +//! and then consumes. A byte that spells a marker but came from the *script* +//! has to survive that round trip behind the NUL literal sentinel +//! (`lexer::push_literal_char`); unescaped it was silently deleted, so +//! `printf '[%s]' A<1f>B` printed `[AB]` where bash prints `[A<1f>B]`. +//! +//! 0x1e and 0x1f are RS and US, ordinary separators in real data +//! (`IFS=$'\x1f'`, `awk -F$'\x1e'`), so this is reachable without any +//! adversarial intent. It also broke the fuzz harness' leak attribution, +//! which compares a builtin's stderr against the script that produced it: +//! nightly `tomlq_fuzz` ran `tomlq 'target/debug/<1f><1f><1f>deps/'` and the +//! diagnostic quoted back the banned host path `target/debug/deps/`, a shape +//! the script did not spell. See `bashkit::testing::script_explains` and +//! `tests/fuzz_crash_regressions.rs`. + +use bashkit::Bash; + +/// Every quoting context that copies literal source characters into a word, +/// for both markers. `printf '[%s]'` brackets each field, so a dropped byte +/// and a split field are both visible. +fn marker_cases() -> Vec { + let mut cases = Vec::new(); + for m in ['\u{1e}', '\u{1f}'] { + cases.extend([ + // Single-, double- and unquoted word text. + format!("printf '[%s]' 'A{m}B'"), + format!("printf '[%s]' \"A{m}B\""), + format!("printf '[%s]' A{m}B"), + // Concatenated segments: the continuation reader has its own + // single-quote, backslash and unquoted paths. + format!("printf '[%s]' \"A{m}B\"'C{m}D'"), + format!("printf '[%s]' 'A{m}B'\"C{m}D\""), + format!("printf '[%s]' 'A'{m}'B'"), + format!("printf '[%s]' ''\\''A{m}B'"), + format!("printf '[%s]' \\{m}'A{m}B'"), + format!(r"printf '[%s]' A\{m}B"), + format!(r#"printf '[%s]' "A\{m}B""#), + format!(r"printf '[%s]' \{m}"), + // A `${...}` operand and a pattern operator inside one. + format!(r#"x=aA{m}Bz; printf '[%s]' "${{x#aA{m}}}""#), + format!(r#"x=q; printf '[%s]' "${{x:+A{m}B}}""#), + // Backslash-escaped marker in a quoted `${...}` operand: the + // reader keeps the backslash and the byte, as bash does. The + // double-quoted-span form is in + // `backslash_escaped_markers_take_the_ordinary_character_path`, + // because bashkit's backslash handling there already diverges + // from bash for every character. + format!(r#"unset x; printf '[%s]' "${{x:-A\{m}B}}""#), + // Quoted spans inside a `${...}` operand. The plain `'...'` span + // needs the literal sentinel; the ANSI-C `$'...'` span is decoded + // again downstream and must NOT get one, or a raw NUL leaks into + // the value. Both directions are regressions this pins. + format!(r#"unset x; printf '[%s]' "${{x:-'A{m}B'}}""#), + format!(r#"unset x; printf '[%s]' "${{x:-$'A{m}B'}}""#), + format!(r#"unset x; printf '[%s]' "${{x:-"A{m}B"}}""#), + format!(r#"unset x; printf '[%s]' ${{x:-'A{m}B'}}"#), + format!(r#"unset x; printf '[%s]' ${{x:-$'A{m}B'}}"#), + // Pattern and replacement operands around the byte. + format!(r#"x=aA{m}Bz; printf '[%s]' "${{x%%B{m}z}}""#), + format!(r#"x=A{m}B; printf '[%s]' "${{x/{m}/-}}""#), + format!(r#"x=A{m}B; printf '[%s]' "${{#x}}""#), + // A brace tail on a word carrying the byte (the unquoted-glob + // path). Extglob is deliberately not covered here: `shopt -s + // extglob` in the same `-c` string takes effect after bash has + // already parsed it, so the oracle would not agree with itself. + format!("printf '[%s]' A{m}{{1,2}}"), + // ANSI-C quoting, already protected; kept so a regression there + // fails here too. + format!("printf '[%s]' $'A{m}B'"), + // Through a variable, quoted and unquoted, and a `${...}` form. + format!("x=A{m}B; printf '[%s]' \"$x\""), + format!("x=A{m}B; printf '[%s]' $x"), + format!("x=A{m}B; printf '[%s]' \"${{x}}\""), + // Command substitution output is data, never rescanned for markers. + format!("printf '[%s]' \"$(printf 'A{m}B')\""), + // A nested body is copied verbatim and re-lexed when it runs, so a + // literal marker inside it survives that second pass. + format!("echo $(echo 'A{m}B')"), + format!("echo \"$(echo 'A{m}B')\""), + format!("echo `echo 'A{m}B'`"), + format!("echo $(printf '[%s]' \"A{m}B\")"), + // A word that also globs keeps the unquoted-glob path. + format!("printf '[%s]' A{m}B*"), + // Array element text. Subscripts are deliberately absent: see + // `subscript_text_keeps_its_pre_existing_shape` below. + format!("a=(A{m}B C); printf '[%s]' \"${{a[@]}}\""), + // Heredoc bodies go through `heredoc_body_escapes`. + format!("cat <1]=v` stores the key as `k1`, so `${m[k<1e>1]}` finds +/// nothing, and bash stores and reads `k<1e>1`. That is pre-existing, not a +/// consequence of `push_literal_char`: subscript text is handed to arithmetic +/// or associative-key expansion, which resolve quoting themselves, and +/// `try_parse_assignment` additionally recovers a marker-bearing subscript from +/// raw source. Escaping it in the lexer alone makes assignment and lookup +/// disagree, so the readers copy subscript text verbatim and this case is left +/// exactly as it was. Fixing it means teaching those three layers the sentinel +/// together. +/// +/// This test pins the current shape so the next change here is deliberate. +#[tokio::test] +async fn subscript_text_keeps_its_pre_existing_shape() { + let mut bash = Bash::new(); + let stored = bash + .exec("declare -A m; m[k\u{1e}1]=V; printf '[%s]' \"${!m[@]}\"") + .await + .unwrap(); + assert_eq!( + stored.stdout.to_string(), + "[k1]", + "a literal marker in a subscript is still dropped at assignment" + ); + let hit = bash + .exec("declare -A m; m[k\u{1e}1]=V; printf '[%s]' \"${m[k1]}\"") + .await + .unwrap(); + assert_eq!(hit.stdout.to_string(), "[V]", "under the normalized key"); + // The `$'...'` spelling has always worked and must keep working: it is the + // form anyone separating real data actually writes. + let ansi = bash + .exec("declare -A m; k=$'k\\x1e1'; m[$k]=V; printf '[%s]' \"${m[$k]}\"") + .await + .unwrap(); + assert_eq!(ansi.stdout.to_string(), "[V]"); +} + +/// Extglob group bodies keep the byte too. bashkit parses `@(...)` as a group +/// without `shopt -s extglob`, so the oracle runs with `-O extglob` to compare +/// like with like — plain `bash -c` makes `@(` a syntax error instead. +#[tokio::test] +#[cfg_attr(not(unix), ignore = "compares against host Unix bash")] +async fn extglob_group_bodies_keep_marker_bytes() { + if std::process::Command::new("bash") + .arg("--version") + .output() + .is_err() + { + eprintln!("skip: bash is not installed"); + return; + } + for m in ['\u{1e}', '\u{1f}'] { + for script in [ + format!("printf '[%s]' @(A{m}B)"), + format!("printf '[%s]' x@(A{m}B)y"), + format!("printf '[%s]' @(A{m}B|zz)"), + // Quoted spans inside the group go through `push_extglob_literal`. + format!("printf '[%s]' @('A{m}B')"), + format!("printf '[%s]' @(\"A{m}B\")"), + // A group after a quoted start is read by the continuation + // reader's own extglob loop, not `read_word_from`'s. + format!("printf '[%s]' \"x\"*@(A{m}B)"), + format!("printf '[%s]' 'p'*@(A{m}B)"), + ] { + let host = std::process::Command::new("bash") + .args(["--noprofile", "--norc", "-O", "extglob", "-c", &script]) + .env_clear() + .env("LC_ALL", "C") + .output() + .unwrap(); + let actual = Bash::new().exec(&script).await.unwrap(); + assert_eq!( + actual.stdout.as_bytes(), + host.stdout, + "stdout differs for {script:?}\n bashkit: {:?}\n bash: {:?}", + actual.stdout.to_string(), + String::from_utf8_lossy(&host.stdout), + ); + } + } +} + +/// Backslash-escaped markers in `${...}` operands survive and take exactly +/// the path an ordinary character takes. +/// +/// Not compared with bash: bashkit's backslash handling in these two readers +/// already diverges from bash for *every* character, not just these bytes — +/// `${x:-A\ZB}` unquoted is `A\ZB` here and `AZB` in bash, and +/// `"${x:-"A\ZB"}"` is `A\\ZB` here and `AZB` in bash. Those are +/// pre-existing and independent of marker handling, so what this pins is the +/// property this change is about: a marker byte is data like any other byte, +/// never silently deleted. +#[tokio::test] +async fn backslash_escaped_markers_take_the_ordinary_character_path() { + let mut bash = Bash::new(); + for (quoted_label, marker_script, plain_script) in [ + ( + "unquoted operand", + r#"unset x; printf '[%s]' ${x:-A\MB}"#, + r#"unset x; printf '[%s]' ${x:-A\ZB}"#, + ), + ( + "double-quoted span inside the operand", + r#"unset x; printf '[%s]' "${x:-"A\MB"}""#, + r#"unset x; printf '[%s]' "${x:-"A\ZB"}""#, + ), + ( + "backslash inside a continuation extglob group", + r#"printf '[%s]' "x"*@(A\MB)"#, + r#"printf '[%s]' "x"*@(A\ZB)"#, + ), + ] { + for m in ['\u{1e}', '\u{1f}'] { + let marked = marker_script.replace('M', &m.to_string()); + let got = bash.exec(&marked).await.unwrap().stdout.to_string(); + assert!( + got.contains(m), + "{quoted_label}: the byte must survive {marked:?}; got {got:?}" + ); + let plain = bash.exec(plain_script).await.unwrap().stdout.to_string(); + assert_eq!( + got.replace(m, "Z"), + plain, + "{quoted_label}: a marker must take the same path as any other character" + ); + } + } +} + +/// The literal sentinel must never reach a value. `push_literal_char` escapes +/// a marker byte for `parse_word`, but some readers hand their span to a +/// second decode that does not consume the sentinel — the ANSI-C `$'...'` span +/// inside `${...}` is one, where escaping turned +/// `"${x:-$'A<1f>B'}"` into `A\0<1f>B`. Any stray NUL in output means a +/// sentinel was added on a path that does not decode it. +#[tokio::test] +async fn the_literal_sentinel_never_leaks_into_a_value() { + let mut bash = Bash::new(); + for m in ['\u{1e}', '\u{1f}'] { + for script in [ + format!(r#"unset x; printf '[%s]' "${{x:-$'A{m}B'}}""#), + format!(r#"unset x; printf '[%s]' "${{x:-'A{m}B'}}""#), + format!(r#"unset x; printf '[%s]' "${{x:-"A{m}B"}}""#), + format!(r#"unset x; printf '[%s]' ${{x:-$'A{m}B'}}"#), + format!("printf '[%s]' $'A{m}B'"), + format!("printf '[%s]' \"A{m}B\""), + format!("printf '[%s]' @('A{m}B')"), + ] { + let out = bash.exec(&script).await.unwrap().stdout.to_string(); + assert!( + !out.contains('\0'), + "a literal sentinel leaked for {script:?}: {out:?}" + ); + assert!( + out.contains(m), + "the byte must survive for {script:?}: {out:?}" + ); + } + } +} + +/// TODO: a brace inside an ANSI-C operand of `${...}` still leaks the literal +/// sentinel. `"${x:-$'{a}'}"` yields `\0{a\0}` here where bash gives `{a}`. +/// +/// Pre-existing and unrelated to marker bytes — verified byte-for-byte +/// identical on `origin/main` — but the same shape as the marker leak fixed in +/// this change: the `{`/`}` NUL-escape in `read_param_expansion_into`'s quote +/// span is unconditional, and the ANSI-C span's second decode does not consume +/// the sentinel. It is not fixable the way the marker sentinel was, by simply +/// not adding it: that escape is load-bearing for the outer `${` brace +/// matching (`"${v-\}}"`), so the brace sentinel has to become decode-aware +/// instead. Left for its own change. +/// +/// Note the unquoted operand is already correct, so only the double-quoted +/// path leaks. This test pins both so the next change here is deliberate. +#[tokio::test] +async fn brace_in_an_ansi_c_operand_leaks_the_sentinel_a_known_divergence() { + let mut bash = Bash::new(); + let quoted = bash + .exec(r#"unset x; printf '[%s]' "${x:-$'{a}'}""#) + .await + .unwrap(); + assert_eq!( + quoted.stdout.to_string(), + "[\0{a\0}]", + "pinning the known leak; bash gives [{{a}}]" + ); + let unquoted = bash + .exec(r#"unset x; printf '[%s]' ${x:-$'{a}'}"#) + .await + .unwrap(); + assert_eq!( + unquoted.stdout.to_string(), + "[{a}]", + "the unquoted operand is already correct and must stay so" + ); +} diff --git a/knowledge/foundations/parser.md b/knowledge/foundations/parser.md index f8c4319d4..80b1ceda1 100644 --- a/knowledge/foundations/parser.md +++ b/knowledge/foundations/parser.md @@ -116,6 +116,36 @@ in `\x1e`/`\x1f`; `parse_word` turns them into `Word::part_quoted`, and field splitting protects quoted parts using markers it picks from characters absent from the data. No in-band marker reaches expansion, so a value holding any byte (`\x01`, `\x02` included) stays data. +Script text that spells a marker is data too. The lexer paths that copy a +literal source character into word text escape `\x1e`/`\x1f` with the NUL +sentinel (`push_literal_char`, and `heredoc_body_escapes` for here-document +bodies): unquoted and double-quoted word text, concatenated quoted segments, +backslash escapes, `${...}` operands outside subscripts, extglob group bodies, +bracket-pattern and compound-array words, and here-document bodies. So +`printf '[%s]' A$'\x1f'B`, `IFS=$'\x1f'` and an unquoted or double-quoted +literal separator all keep the byte. Unescaped it was read as a marker and +deleted, which also let a builtin diagnostic quote back text the script never +spelled — see +[builtin diagnostics and fuzzing](../security/security-testing.md#builtin-diagnostics-and-fuzzing). + +The sentinel is only safe where the text it guards is not decoded a second +time. An ANSI-C `$'...'` span inside `${...}` resolves its own escapes +downstream and that decode does not consume the sentinel, so the span's quote +arm escapes a marker only for a plain `'...'` span; escaping the ANSI-C one +leaked a raw NUL into the value. The `{`/`}` escape in the same arm is +unconditional and still leaks for that reason +(`"${x:-$'{a}'}"` is `\0{a\0}`, bash gives `{a}`); it cannot simply be dropped +because it is load-bearing for the outer `${` brace matching, so making it +decode-aware is left for its own change. Pinned by +`quote_marker_byte_tests::brace_in_an_ansi_c_operand_leaks_the_sentinel_a_known_divergence`. + +Two paths copy source verbatim instead. A nested `$(...)`, `$((...))`, `$[...]` +or backtick body is copied byte for byte and re-lexed when it runs, so its own +literal markers survive through that second pass. Subscript text is the +deliberate exception: it is handed to arithmetic or associative-key evaluation, +which resolve quoting themselves, so a literal marker in a subscript is still +dropped. Both shapes are pinned in +`crates/bashkit/tests/integration/quote_marker_byte_tests.rs`. The same markers are used when a single-quoted word continues with a double-quoted expansion (`'a'"$1"`, otherwise kept as one literal word) and when an empty quoted segment sits beside an expansion (`"$@"""`, `''"$@"`). diff --git a/knowledge/security/security-testing.md b/knowledge/security/security-testing.md index c180589b5..902b7f7d7 100644 --- a/knowledge/security/security-testing.md +++ b/knowledge/security/security-testing.md @@ -272,6 +272,20 @@ See the [threat model](threat-model.md) and the `bashkit::testing` rustdoc. A banned shape the executed script itself spells is an echo, not a leak, and `assert_fuzz_invariants` skips it for that script only (`script_explains`). A diagnostic that quotes its operand therefore needs no new strip template. +The echoed operand is a substring of the script and the diagnostic frames it +with its own punctuation, so attribution decomposes the *pattern*: it drops a +leading fragment the template's `: ` lead could supply and a trailing fragment +its `: ` trail could supply, then asks whether the remaining core is script +text. That is what excuses ` { code:` in `awk: cmd. line:1: { code:…` and in +`printf: { code:: invalid number`. Only the shapes starting with a space or +ending in a colon have a fragment to drop; the rest stay absolute, and an +empty core is never accepted, so a builtin format string that spells a shape +itself still fails. +Attribution compares against the raw script, so a lexer that rewrites word +text breaks it: dropped `\x1e`/`\x1f` bytes once turned +`tomlq 'target/debug/\x1f\x1f\x1fdeps/'` into a diagnostic quoting the banned +host path `target/debug/deps/`. See the +[parser design](../foundations/parser.md) on marker bytes in script text. `assert_no_leak` has no script to attribute against and stays absolute, so hand-written `no_leak_*` cases must not put a banned shape in their input. Replays of the inputs that turned nightly fuzz runs red live in