8000 Keep deeply nested form and report Blobs from overflowing the stack by dominion525 · Pull Request #156 · dominion525/jetdb · GitHub
[go: up one dir, main page]

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 72 additions & 6 deletions crates/jetdb/src/form.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1025,6 +1025,12 @@ fn parse_blob(data: &[u8]) -> Result<(Vec<BlobProperty>, Vec<BlobControl>), File
/// of the form or report, of its pages and of its groups.
const SECTIONS: std::ops::RangeInclusive<u16> = 0x98..=0x9E;

/// How deep the nodes of the tree a Blob keeps may nest, in both formats.
/// The reading, the listing and the drop of the tree recur on each level,
/// and a file can nest them deep enough to use up the stack, which is 1 MB
/// in Wasm. Forms and reports Access makes nest a few levels.
pub(crate) const MAX_TREE_DEPTH: usize = 256;

/// A node of the tree a Blob keeps: a default control, a section or a
/// control, with the nodes in it.
struct BlobNode {
Expand All @@ -1038,7 +1044,7 @@ struct BlobNode {
/// that ended with `end`, in the order of the Blob: each section followed by
/// its controls. `None` when the bytes do not read to the end as a tree.
fn controls_of_tree(data: &[u8], mut pos: usize, end: u32) -> Option<Vec<BlobControl>> {
let nodes = parse_nodes(data, &mut pos, end)?;
let nodes = parse_nodes(data, &mut pos, end, 0)?;
if pos != data.len() {
return None;
}
Expand All @@ -1065,7 +1071,8 @@ fn push_with_children(node: BlobNode, out: &mut Vec<BlobControl>) {
/// for 253, one for 254, and a count (u16) of them for 255. Each node is its
/// type (u16), 4 bytes jetdb does not use, a group of entries, and the nodes
/// that follow it: the controls of a section, the pages of a tab control.
fn parse_nodes(data: &[u8], pos: &mut usize, end: u32) -> Option<Vec<BlobNode>> {
/// `depth` is the number of nodes the nodes are in.
fn parse_nodes(data: &[u8], pos: &mut usize, end: u32, depth: usize) -> Option<Vec<BlobNode>> {
let count = match end {
253 => 0,
254 => 1,
Expand All @@ -1078,17 +1085,22 @@ fn parse_nodes(data: &[u8], pos: &mut usize, end: u32) -> Option<Vec<BlobNode>>
// The count comes from the file: grow as nodes are read.
let mut nodes = Vec::new();
for _ in 0..count {
nodes.push(parse_node(data, pos)?);
nodes.push(parse_node(data, pos, depth)?);
}
Some(nodes)
}

fn parse_node(data: &[u8], pos: &mut usize) -> Option<BlobNode> {
/// The node at `pos`, in `depth` nodes; `None` when that would nest the
/// nodes deeper than [`MAX_TREE_DEPTH`].
fn parse_node(data: &[u8], pos: &mut usize, depth: usize) -> Option<BlobNode> {
if depth == MAX_TREE_DEPTH {
return None;
}
let b = data.get(*pos..*pos + 6)?;
let type_code = u16::from_le_bytes([b[0], b[1]]);
let (properties, next, end) = parse_group(data, *pos + 6, data.len());
*pos = next;
let children = parse_nodes(data, pos, end?)?;
let children = parse_nodes(data, pos, end?, depth + 1)?;
Some(BlobNode {
type_code,
properties,
Expand Down Expand Up @@ -1253,7 +1265,7 @@ fn parse_section_props(data: &[u8], start: usize, end: usize) -> Vec<BlobPropert
// ---------------------------------------------------------------------------

#[cfg(test)]
mod tests {
pub(crate) mod tests {
use super::*;
use crate::save_as_text;
use std::collections::HashMap;
Expand Down Expand Up @@ -1947,6 +1959,60 @@ mod tests {
}
}

/// Runs `f` on a thread with the stack of Wasm, 1 MB; in Wasm, which has
/// no threads, on its own stack.
pub(crate) fn on_small_stack<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> T {
if cfg!(target_family = "wasm") {
return f();
}
std::thread::Builder::new()
.stack_size(1 << 20)
.spawn(f)
.unwrap()
.join()
.unwrap()
}

/// A Blob whose tree nests `depth` nodes, one in each: a section, and
/// controls in it and in each other.
fn nested_blob(depth: usize) -> Vec<u8> {
let last = |end: u32| {
let mut value = vec![0x01];
value.extend_from_slice(&end.to_le_bytes());
make_entry(0x0029, 0x01, 1, 1, &value)
};
let mut data = make_blob(&last(254));
for level in 1..=depth {
let type_code: u16 = if level == 1 { 0x98 } else { 0x64 };
data.extend_from_slice(&type_code.to_le_bytes());
data.extend_from_slice(&[0; 4]);
data.extend(last(if level == depth { 253 } else { 254 }));
}
data
}

#[test]
fn a_tree_nests_up_to_the_limit() {
// Within the limit, each node is a control; deeper, the tree is not
// read, and no control is found by its name.
let (props, controls) =
on_small_stack(|| parse_blob(&nested_blob(MAX_TREE_DEPTH)).unwrap());
assert_eq!(props.len(), 1);
assert_eq!(controls.len(), MAX_TREE_DEPTH);
let (props, controls) =
on_small_stack(|| parse_blob(&nested_blob(MAX_TREE_DEPTH + 1)).unwrap());
assert_eq!(props.len(), 1);
assert!(controls.is_empty());
}

#[test]
fn deep_nesting_is_not_read_as_a_tree_rather_than_overflowing_the_stack() {
// 100,000 levels, which would use up the stack reading the tree and
// dropping it.
let (_, controls) = on_small_stack(|| parse_blob(&nested_blob(100_000)).unwrap());
assert!(controls.is_empty());
}

#[test]
fn controls_of_an_empty_type_info_have_the_types_of_the_tree() {
// Made by VBA, the report Shared has an empty TypeInfo; its sections
Expand Down
45 changes: 39 additions & 6 deletions crates/jetdb/src/form2000.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@

use crate::data::format_guid;
use crate::encoding;
use crate::form::{BlobProperty, BlobValue, ControlProperties};
use crate::form::{BlobProperty, BlobValue, ControlProperties, MAX_TREE_DEPTH};

/// The first byte of the Blob of a form or report in the Access 2000 format.
pub(crate) const VERSION: u8 = 0x13;
Expand Down Expand Up @@ -128,7 +128,8 @@ impl Reader<'_> {
}
}

fn list(&mut self) -> Option<Vec<Entry>> {
/// The entries of a list in `depth` entries.
fn list(&mut self, depth: usize) -> Option<Vec<Entry>> {
let count = match self.byte()? {
0xFF => self.u16()?,
0xFE => 1,
Expand All @@ -137,19 +138,24 @@ impl Reader<'_> {
// The count comes from the file: grow as entries are read.
let mut entries = Vec::new();
for _ in 0..count {
entries.push(self.entry()?);
entries.push(self.entry(depth)?);
}
Some(entries)
}

fn entry(&mut self) -> Option<Entry> {
/// An entry in `depth` entries; `None` when that would nest the entries
/// deeper than [`MAX_TREE_DEPTH`].
fn entry(&mut self, depth: usize) -> Option<Entry> {
if depth == MAX_TREE_DEPTH {
return None;
}
let type_code = self.u16()?;
let props = self.props()?;
let children = if self.data.get(self.pos) == Some(&0xFD) {
self.pos += 1;
None
} else {
Some(self.list()?)
Some(self.list(depth + 1)?)
};
Some(Entry {
type_code,
Expand All @@ -166,7 +172,7 @@ pub(crate) fn read(data: &[u8]) -> Option<(Vec<BlobProperty>, Vec<ControlPropert
// The properties of the object follow its type, at 8.
let mut reader = Reader { data, pos: 10 };
let object = reader.props()?;
let entries = reader.list()?;
let entries = reader.list(0)?;
if reader.pos != data.len() {
return None;
}
Expand Down Expand Up @@ -996,6 +1002,7 @@ const TYPE_156: Table = &[(0xDF, 0x0014, Kind::Text), (0xE7, 0x0178, Kind::Guid)
#[cfg(test)]
mod tests {
use super::*;
use crate::form::tests::on_small_stack;
use crate::form::{
list_forms, read_form_properties_of_type, read_form_stream_of_type, FormObjectType,
StreamKind,
Expand Down Expand Up @@ -1087,6 +1094,32 @@ mod tests {
assert!(read(&blob(&[], &[0xFF, 0, 0, 0x00])).is_none());
}

/// A Blob whose tree nests `depth` entries, one in each list (FE): a
/// section, and controls in it and in each other, the last ending (FD).
fn nested_blob(depth: usize) -> Vec<u8> {
let mut rest = vec![0xFE, 152, 0];
for _ in 1..depth {
rest.extend([0xFE, 100, 0]);
}
rest.push(0xFD);
blob(&[], &rest)
}

#[test]
fn entries_nest_up_to_the_limit() {
let read_nested = |depth| on_small_stack(move || read(&nested_blob(depth)));
let (_, controls) = read_nested(MAX_TREE_DEPTH).unwrap();
assert_eq!(controls.len(), MAX_TREE_DEPTH);
assert!(read_nested(MAX_TREE_DEPTH + 1).is_none());
}

#[test]
fn deep_nesting_is_none_rather_than_a_stack_overflow() {
// 100,000 levels, which would use up the stack reading the tree and
// dropping it.
assert!(on_small_stack(|| read(&nested_blob(100_000))).is_none());
}

/// The names of the forms and reports of the Access 2000 format in
/// `file`, with their Blobs.
fn blobs(file: &std::path::Path) -> Vec<(String, Vec<u8>)> {
Expand Down
Loading
0