FilmCraft: An open-source, nonlinear video editor written by scratch in pure Rust
security(captions): bound malformed text processing (#2879)
Earl Co2d0382320a15
diff --git a/crates/captions/src/mcc.rs b/crates/captions/src/mcc.rsindex 3004872bb..ffc155df9 100644--- a/crates/captions/src/mcc.rs+++ b/crates/captions/src/mcc.rs@@ -344,6 +344,8 @@ struct Win {defined: bool,visible: bool,rows: Vec<String>,+ max_rows: usize,+ max_cols: usize,}struct Dec708 {@@ -416,8 +418,9 @@ impl Dec708 {fn put(&mut self, c: char) {let w = self.w();match w.rows.last_mut() {- Some(row) => row.push(c),- None => w.rows.push(c.to_string()),+ Some(row) if row.chars().count() < w.max_cols => row.push(c),+ None if w.max_rows > 0 && w.max_cols > 0 => w.rows.push(c.to_string()),+ _ => {}}}fn bitmap(&mut self, m: u8, f: impl Fn(&mut Win)) {@@ -441,7 +444,8 @@ impl Dec708 {}}0x0c => self.w().rows = vec![String::new()],- 0x0d => self.w().rows.push(String::new()),+ 0x0d if self.w().rows.len() < self.w().max_rows => self.w().rows.push(String::new()),+ 0x0d => {}0x0e => {if let Some(r) = self.w().rows.last_mut() {r.clear();@@ -500,11 +504,24 @@ impl Dec708 {0x98..=0x9f => {let n = (c - 0x98) as usize;let vis = arg(i) & 0x20 != 0;+ let max_rows = (arg(i + 3) & 0x0f) as usize + 1;+ let max_cols = (arg(i + 4) & 0x3f) as usize + 1;let w = &mut self.win[n];if !w.defined {- *w = Win { defined: true, visible: vis, rows: vec![String::new()] };+ *w = Win { defined: true, visible: vis, rows: vec![String::new()], max_rows, max_cols };} else {w.visible = vis;+ w.max_rows = max_rows;+ w.max_cols = max_cols;+ w.rows.truncate(max_rows);+ for row in &mut w.rows {+ if let Some((at, _)) = row.char_indices().nth(max_cols) {+ row.truncate(at);+ }+ }+ if w.rows.is_empty() {+ w.rows.push(String::new());+ }}self.cur = n;i += 6;@@ -699,4 +716,12 @@ mod tests {assert_eq!(got, vec![(60, 120, "Hello, world!"), (120, 200, "Second caption\nwith two lines"), (260, 300, "Café “q” ♪")]);assert!(parse("garbage").is_err());}++ #[test]+ fn decoder_keeps_708_text_within_declared_window_dimensions() {+ let mut decoder = Dec708::new();+ // Define window 0 with one row and one column, then try to overflow both.+ decoder.service_data(&[0x98, 0, 0, 0, 0, 0, 0, b'A', b'B', 0x0d, b'C']);+ assert_eq!(decoder.win[0].rows, ["A"]);+ }}diff --git a/crates/captions/src/scc.rs b/crates/captions/src/scc.rsindex 9fe275ed6..e894e17cf 100644--- a/crates/captions/src/scc.rs+++ b/crates/captions/src/scc.rs@@ -304,7 +304,12 @@ pub fn wrap_rows(text: &str) -> Vec<String> {for line in text.lines() {let mut cur = String::new();for word in line.split_whitespace() {- let mut word = word.to_string();+ if rows.len() == 15 {+ return rows;+ }+ // SCC can emit at most 15 32-column rows. Do not repeatedly copy an unbounded word+ // only to discard all but that small prefix below.+ let mut word: String = word.chars().take(COLS * (15 - rows.len())).collect();loop {let need = if cur.is_empty() { word.chars().count() } else { cur.chars().count() + 1 + word.chars().count() };if need <= COLS {@@ -316,11 +321,17 @@ pub fn wrap_rows(text: &str) -> Vec<String> {}if !cur.is_empty() {rows.push(std::mem::take(&mut cur));+ if rows.len() == 15 {+ return rows;+ }continue;}let head: String = word.chars().take(COLS).collect();word = word.chars().skip(COLS).collect();rows.push(head);+ if rows.len() == 15 {+ return rows;+ }if word.is_empty() {break;}@@ -541,6 +552,13 @@ mod tests {assert_eq!(rows.join(" "), "the quick brown fox jumps over the lazy dog and keeps running far away");}+ #[test]+ fn wrapping_discards_an_unrepresentable_word_without_quadratic_copying() {+ let rows = wrap_rows(&"x".repeat(100_000));+ assert_eq!(rows.len(), 15);+ assert!(rows.iter().all(|row| row.len() == COLS));+ }+#[test]fn cue_at_zero_is_delayed_not_lost() {let doc = Document { cues: vec![cue(0, 60, "Start")], ..Default::default() };diff --git a/crates/captions/src/stl.rs b/crates/captions/src/stl.rsindex da49f3b10..5b0e9eeff 100644--- a/crates/captions/src/stl.rs+++ b/crates/captions/src/stl.rs@@ -212,9 +212,13 @@ fn encode_text(text: &str) -> Vec<u8> {let mut out = Vec::new();let mut rest = text;while let Some(ch) = rest.chars().next() {- if ch == '<'- && let Some(end) = rest.find('>')- {+ let is_tag_start = ch == '<'+ && rest+ .get(1..)+ .and_then(|tail| tail.strip_prefix('/').or(Some(tail)))+ .and_then(|name| name.as_bytes().first())+ .is_some_and(u8::is_ascii_alphabetic);+ if is_tag_start && let Some(end) = rest.find('>') {let tag = &rest[1..end];// Only a syntactically plausible tag is markup. Comparisons such as// "2 < 3 > 1" and "x < y > z" must not lose their middle text.@@ -232,6 +236,18 @@ fn encode_text(text: &str) -> Vec<u8> {continue;}}+ if is_tag_start && !rest.contains('>') {+ // This cannot become markup later. Encode the remaining literal text in one pass+ // instead of searching the shrinking suffix after every opening bracket.+ for ch in rest.chars() {+ if ch == '\n' {+ out.push(0x8a);+ } else {+ out.extend(encode_6937(ch).unwrap_or_else(|| vec![b'?']));+ }+ }+ break;+ }if ch == '\n' {out.push(0x8a);} else {@@ -474,6 +490,14 @@ mod tests {assert_eq!(encode_text("<i >Hi</i >"), vec![0x80, b'H', b'i', 0x81]);}+ #[test]+ fn unterminated_markup_is_encoded_in_one_pass() {+ let text = format!("<i{}", "<".repeat(10_000));+ let encoded = encode_text(&text);+ assert_eq!(encoded.len(), text.len());+ assert_eq!(encoded[0], b'<');+ }+#[test]fn programme_start_is_subtracted() {let doc = Document {