From f97261ff6718b52ca75c84ddb0a33177ba51cf5e Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 26 Nov 2026 10:02:19 +0000 Subject: [PATCH 1/6] fix(parser): keep literal 0x1e/0x1f bytes as word data The 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. Single-quoted segments already escaped a marker byte that came from the script behind the NUL literal sentinel, but unquoted text, double-quoted text, `${...}` operands, backslash escapes and here-document bodies did not, so the byte was silently deleted: `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, so reaching this needed no adversarial input. Every lexer path that copies a literal source character now goes through `push_literal_char`, and `heredoc_body_escapes` does the same for bodies. A new bash-oracle test covers both bytes across every quoting context. Subscript text is deliberately left verbatim: it is handed to arithmetic or associative-key expansion, which resolve quoting themselves, and `try_parse_assignment` also recovers a marker-bearing subscript from raw source, so escaping it in the lexer alone makes assignment and lookup disagree. That pre-existing divergence is pinned by a test and recorded as a TODO. Dropping the bytes 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 never spelled. The same nightly run tripped a second, independent gap in that attribution. `script_explains` compared the whole script, padded only at its ends, against a banned shape, so a shape spelled across the *interior* join between a diagnostic's template and its echoed operand looked unexplained: `awk: cmd. line:1: { code:...` and `printf: { code:: invalid number` both render ` { code:` from the template's `: ` plus an operand the script does spell. Attribution now decomposes the pattern instead, dropping only the fragments the `: ` pads could supply and requiring a non-empty core to appear in the script, so the shapes with no such fragment stay absolute and a format string that spells a shape itself still fails. Replays of all three crash units join the existing ones in `tests/fuzz_crash_regressions.rs`. --- .../bashkit/fuzz/fuzz_targets/printf_fuzz.rs | 8 +- crates/bashkit/src/parser/lexer.rs | 93 ++++++--- crates/bashkit/src/parser/mod.rs | 9 +- crates/bashkit/src/testing.rs | 128 ++++++++++++- .../bashkit/tests/fuzz_crash_regressions.rs | 76 ++++++++ crates/bashkit/tests/integration/main.rs | 1 + .../integration/quote_marker_byte_tests.rs | 178 ++++++++++++++++++ knowledge/foundations/parser.md | 8 + knowledge/security/security-testing.md | 14 ++ 9 files changed, 481 insertions(+), 34 deletions(-) create mode 100644 crates/bashkit/tests/integration/quote_marker_byte_tests.rs 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..98cefa4bb 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 { @@ -1478,7 +1505,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 +1681,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 +1758,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())); } @@ -1771,7 +1798,7 @@ impl<'a> Lexer<'a> { if matches!(ch, '*' | '?' | '[' | '{') { flags.has_unquoted_glob = true; } - content.push(ch); + push_literal_char(content, ch); self.advance(); } _ => break, @@ -1966,7 +1993,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 +2034,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(()) @@ -2373,7 +2403,7 @@ impl<'a> Lexer<'a> { } _ => { content.push('\\'); - content.push(next); + push_literal_char(content, next); self.advance(); } } @@ -2401,7 +2431,7 @@ impl<'a> Lexer<'a> { } '`' => self.read_dquote_backtick_into(content), _ => { - content.push(ch); + push_literal_char(content, ch); self.advance(); } } @@ -2653,8 +2683,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()); @@ -2705,7 +2750,7 @@ impl<'a> Lexer<'a> { content.push('\x00'); content.push(q); } - _ => content.push(q), + _ => push_literal_char(content, q), } } } @@ -2721,7 +2766,7 @@ impl<'a> Lexer<'a> { if matches!(q, '{' | '}') { content.push('\x00'); } - content.push(q); + push_literal_char(content, q); if ansi_c && q == '\\' { if let Some(n) = self.peek_char() { self.advance(); @@ -2792,7 +2837,11 @@ impl<'a> Lexer<'a> { } } _ => { - content.push(c); + if subscript > 0 { + content.push(c); + } else { + push_literal_char(content, c); + } self.advance(); } } @@ -2875,7 +2924,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 +2940,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..68fdb1380 --- /dev/null +++ b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs @@ -0,0 +1,178 @@ +//! 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}}""#), + // 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 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]"); +} diff --git a/knowledge/foundations/parser.md b/knowledge/foundations/parser.md index f8c4319d4..2ffe6f584 100644 --- a/knowledge/foundations/parser.md +++ b/knowledge/foundations/parser.md @@ -116,6 +116,14 @@ 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: every lexer path that copies a +literal source character escapes `\x1e`/`\x1f` with the NUL sentinel +(`push_literal_char`, and `heredoc_body_escapes` for 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 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 From 3e336c98000c2d03fc15c250502ae7a4ddefd3ad Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 26 Nov 2026 10:25:16 +0000 Subject: [PATCH 2/6] fix(deps): cap markkit below 0.3.2 to hold the 1.96 consumer floor The required `msrv` job resolves a fresh external consumer on Rust 1.96.0, deliberately ignoring this repository's Cargo.lock, so it catches dependency floor drift the locked graph hides. markkit 0.3.2 (published today 04:57 UTC, 0.3.3 at 05:57) moved from `mail-parser ^0.11` to `^1.0`, and every mail-parser 1.x declares `rust-version = 1.98`. A fresh resolve therefore picked markkit 0.3.3 -> mail-parser 1.0.2 and the job stopped at `rustc 1.96.0 is not supported by the following package: mail-parser@1.0.2 requires rustc 1.98`. This is time-based, not diff-based: the same job passed on main at 03:06 UTC and `scripts/check-msrv-consumer.py --profile all` fails identically on an unmodified checkout. Cap markkit and markkit-cli below 0.3.2, in lockstep because markkit-cli 0.3.3 requires `markkit ^0.3.3`. The workspace lock already pinned 0.3.1, so Cargo.lock is unchanged and only fresh resolution is constrained. markkit is an optional, off-by-default feature, which is why only the `all` consumer profile was affected. With the cap, `check-msrv-consumer.py --profile all` resolves markkit 0.3.1 and mail-parser 0.11.9 and completes `cargo check` on 1.96.0. The alternative is to raise the consumer floor to 1.98, which drops Rust 1.96 and 1.97 consumers. AGENTS.md says to preserve that floor, so this takes the conservative option; lift the cap when the floor moves on purpose or when markkit's mail-parser dependency supports 1.96 again. --- crates/bashkit/Cargo.toml | 17 +++++++++++++++-- 1 file changed, 15 insertions(+), 2 deletions(-) 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 } From 9e04a0ddfaad30f3f79fceb2a80e08700a5f43a7 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 26 Nov 2026 10:48:32 +0000 Subject: [PATCH 3/6] fix(parser): keep marker bytes in extglob bodies and ${...} backslash escapes Review on #3022 found two more raw-copy paths in the same bug class, both confirmed against real bash before fixing: - Extglob group bodies copied literal source bytes bare, so `@(A<1f>B)` lexed as `@(AB)`. `bash -O extglob` prints `[@(A<1f>B)]`; plain `bash -c` makes `@(` a syntax error, which is why the new test runs the oracle with `-O extglob`. Both the group loop in `read_word_from` and the one embedded in a bracket-pattern word are fixed. A marker is never `(`, `)`, a quote or a backslash, so depth counting, `extglob_escaped` and the `word.pop()` arms are unaffected. - Four backslash arms in the `${...}` readers kept the backslash but pushed the escaped character bare, so `${x:-A\<1f>B}` lost the byte where the `read_dquote_body` analogue now keeps it. Fixed in `read_unquoted_param_body`'s unquoted and double-quote-span arms and `read_param_expansion_into`'s double-quote-span and escape-fallthrough arms, each gated on subscript depth so subscript text stays verbatim. A third finding, markers deleted inside nested `$(...)`/`$((...))`/backtick bodies, did not reproduce: those bodies are copied verbatim and re-lexed when they run, so the second pass escapes their markers. `echo $(echo 'a<1f>b')` already printed `a<1f>b`, matching bash. Added to the oracle test rather than changed. Two divergences deliberately left alone, because bashkit treats *every* character that way and not just these bytes: an unquoted `${x:-A\ZB}` keeps the backslash (bash drops it), and `"${x:-"A\ZB"}"` doubles it. The new test asserts a marker takes the same path as an ordinary character instead of comparing those shapes with bash. Also scope the parser knowledge entry, which claimed "every lexer path" escapes markers. It now lists the covered paths and records the two that copy source verbatim: nested substitution bodies (re-lexed, so markers survive) and subscripts (the deliberate exception). --- crates/bashkit/src/parser/lexer.rs | 27 ++++-- .../integration/quote_marker_byte_tests.rs | 93 +++++++++++++++++++ knowledge/foundations/parser.md | 17 +++- 3 files changed, 127 insertions(+), 10 deletions(-) diff --git a/crates/bashkit/src/parser/lexer.rs b/crates/bashkit/src/parser/lexer.rs index 98cefa4bb..2abe74a98 100644 --- a/crates/bashkit/src/parser/lexer.rs +++ b/crates/bashkit/src/parser/lexer.rs @@ -1440,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, @@ -1457,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(); } @@ -1941,7 +1944,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('\\'), }, @@ -1979,7 +1986,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; } @@ -2734,7 +2741,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('{') => { @@ -2812,7 +2819,11 @@ impl<'a> Lexer<'a> { } _ => { content.push('\\'); - content.push(esc); + if subscript > 0 { + content.push(esc); + } else { + push_literal_char(content, esc); + } self.advance(); } } @@ -2904,7 +2915,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, diff --git a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs index 68fdb1380..9a4ff8e81 100644 --- a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs +++ b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs @@ -42,6 +42,13 @@ fn marker_cases() -> Vec { // 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}}""#), // 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 @@ -56,6 +63,12 @@ fn marker_cases() -> Vec { 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 @@ -176,3 +189,83 @@ async fn subscript_text_keeps_its_pre_existing_shape() { .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)"), + ] { + 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"}""#, + ), + ] { + 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" + ); + } + } +} diff --git a/knowledge/foundations/parser.md b/knowledge/foundations/parser.md index 2ffe6f584..50aaf7130 100644 --- a/knowledge/foundations/parser.md +++ b/knowledge/foundations/parser.md @@ -116,14 +116,25 @@ 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: every lexer path that copies a -literal source character escapes `\x1e`/`\x1f` with the NUL sentinel -(`push_literal_char`, and `heredoc_body_escapes` for here-document bodies), so +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). + +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 (`"$@"""`, `''"$@"`). From 3e7b5e0d1dee9f41aa22ad6ac87c2b8e7c6eae86 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 26 Nov 2026 11:06:00 +0000 Subject: [PATCH 4/6] fix(parser): keep marker bytes in extglob quoted spans and continuation groups Follow-up review on #3022 found two more raw-copy paths, both confirmed against `bash -O extglob` before fixing: - `push_extglob_literal` NUL-shielded only `$` and backtick, so a quoted span inside a group lost the byte while the unquoted group fixed in the last commit kept it: `@('A<1f>B')` and `@("A<1f>B")` lexed as `@(AB)` where bash gives `[@(A<1f>B)]`. Its final push now goes through `push_literal_char`, which adds the sentinel without the backslash a marker does not need. - `read_continuation_into` has its own extglob loop, separate from the `read_word_from` twin, so a group after a quoted start went through the unfixed copy: `"x"*@(a<1f>b)` and `'p'*@(a<1f>b)` lexed as `*@(ab)` where bash keeps the byte. A third item in that review, the `$'...'` ANSI-C backslash arm, is not a bug: `$'A\<1f>B'` already yields `A\<1f>B`, matching bash, because `push_literal_with_escaped_dollar` covers that path. Left alone. `"x"*@(A\<1f>B)` is covered by the character-equivalence test rather than the bash oracle: bashkit keeps the backslash where bash drops it, for every character and not just these bytes, so comparing it with bash would bake an unrelated pre-existing divergence into an expectation. --- crates/bashkit/src/parser/lexer.rs | 14 +++++++++++--- .../tests/integration/quote_marker_byte_tests.rs | 12 ++++++++++++ 2 files changed, 23 insertions(+), 3 deletions(-) diff --git a/crates/bashkit/src/parser/lexer.rs b/crates/bashkit/src/parser/lexer.rs index 2abe74a98..07d001b8f 100644 --- a/crates/bashkit/src/parser/lexer.rs +++ b/crates/bashkit/src/parser/lexer.rs @@ -1773,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, @@ -1787,7 +1790,7 @@ impl<'a> Lexer<'a> { } '\\' => { if let Some(e) = self.peek_char() { - content.push(e); + push_literal_char(content, e); self.advance(); } } @@ -2280,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('\\'); @@ -2287,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 { diff --git a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs index 9a4ff8e81..43dda6723 100644 --- a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs +++ b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs @@ -209,6 +209,13 @@ async fn extglob_group_bodies_keep_marker_bytes() { 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]) @@ -252,6 +259,11 @@ async fn backslash_escaped_markers_take_the_ordinary_character_path() { 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()); From 864da2d737938af3e9a77a868b67523a1625521f Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 26 Nov 2026 11:15:41 +0000 Subject: [PATCH 5/6] fix(parser): stop the literal sentinel leaking out of an ANSI-C span Self-review regression. The previous commits escaped marker bytes in `read_param_expansion_into`'s single-quote span, but that arm serves two spans with opposite needs, and the `ansi_c` flag already distinguishes them: - A plain `'...'` span is not decoded again, so it needs the sentinel. Without it `"${x:-'A<1f>B'}"` yielded `'AB'` where bash gives `'A<1f>B'`. - An ANSI-C `$'...'` span resolves its own escapes downstream, and that decode does not consume the sentinel, so escaping there leaked a raw NUL into the value: `"${x:-$'A<1f>B'}"` became `A\0<1f>B` where bash and the pre-change behavior both give `A<1f>B`. The second was a regression this branch introduced on a path that already worked, and a leaked NUL is worse than the dropped byte it was meant to fix. No test covered the shape, which is why 7616 passing tests said nothing about it. Swept the whole area instead of reasoning case by case: 26 distinct `${...}`, quoting, extglob and here-document shapes across both marker bytes, each diffed against real bash and each checked for a stray NUL. All 26 match with no leaked sentinel. That sweep is what caught the plain-span case still dropping the byte after the first revert. Both directions are now pinned, including `the_literal_sentinel_never_leaks_into_a_value`, since a leaked sentinel is a distinct failure mode from a dropped byte and nothing guarded it. --- crates/bashkit/src/parser/lexer.rs | 14 +++++- .../integration/quote_marker_byte_tests.rs | 45 +++++++++++++++++++ 2 files changed, 58 insertions(+), 1 deletion(-) diff --git a/crates/bashkit/src/parser/lexer.rs b/crates/bashkit/src/parser/lexer.rs index 07d001b8f..19d2c20d1 100644 --- a/crates/bashkit/src/parser/lexer.rs +++ b/crates/bashkit/src/parser/lexer.rs @@ -2781,7 +2781,19 @@ impl<'a> Lexer<'a> { if matches!(q, '{' | '}') { content.push('\x00'); } - push_literal_char(content, 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(); diff --git a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs index 43dda6723..5f21e280f 100644 --- a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs +++ b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs @@ -49,6 +49,19 @@ fn marker_cases() -> Vec { // 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 @@ -281,3 +294,35 @@ async fn backslash_escaped_markers_take_the_ordinary_character_path() { } } } + +/// 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:?}" + ); + } + } +} From 7bc3317086db6b5be8a513cbb501097f2361e7e9 Mon Sep 17 00:00:00 2001 From: Mykhailo Chalyi Date: Thu, 26 Nov 2026 11:27:20 +0000 Subject: [PATCH 6/6] test(parser): pin the pre-existing brace sentinel leak in ANSI-C operands Review on #3022 flagged the `{`/`}` NUL-escape in `read_param_expansion_into`'s quote span. It is a real bug, pre-existing (byte-for-byte identical with `origin/main`'s lexer swapped in), and the failure mode is not the predicted truncation but the same leak the previous commit fixed for markers: "${x:-$'{a}'}" -> \0{a\0} bash: {a} "${x:-$'{a'}" -> \0{a bash: {a ${x:-$'{a}'} -> {a} bash: {a} (unquoted already correct) `read_dollar_single_quoted_content` does truncate at NUL (`$'x\0y'` is `x`), but that is not the decode this path takes; the NULs survive into the value. Not fixed here. It is brace escaping rather than marker handling, and unlike the marker sentinel it cannot be fixed by not adding it: that escape is load-bearing for the outer `${` brace matching (`"${v-\}}"`), so it has to become decode-aware instead. Pinned with bash's values in the assertion messages, and the knowledge entry now states the sentinel-vs-second-decode contract for this span, why the brace escape still violates it, and why dropping it is not the fix. --- .../integration/quote_marker_byte_tests.rs | 37 +++++++++++++++++++ knowledge/foundations/parser.md | 11 ++++++ 2 files changed, 48 insertions(+) diff --git a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs index 5f21e280f..fc5f9ec17 100644 --- a/crates/bashkit/tests/integration/quote_marker_byte_tests.rs +++ b/crates/bashkit/tests/integration/quote_marker_byte_tests.rs @@ -326,3 +326,40 @@ async fn the_literal_sentinel_never_leaks_into_a_value() { } } } + +/// 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 50aaf7130..80b1ceda1 100644 --- a/knowledge/foundations/parser.md +++ b/knowledge/foundations/parser.md @@ -128,6 +128,17 @@ 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