Skip to content

PdfCraft: An open-source PDF reader and editor written by scratch in pure Rust

fix(xfa): bound the bytes a data import copies out of its file

aionggbac0e610db7a
diff --git a/crates/xfa/src/data.rs b/crates/xfa/src/data.rs
index 87db6b998..21c12a58b 100644
--- a/crates/xfa/src/data.rs
+++ b/crates/xfa/src/data.rs
@@ -801,19 +801,52 @@ pub struct ImportNode {
/// Deepest data an import keeps.
const MAX_IMPORT_DEPTH: usize = MAX_DEPTH;
-/// `n` as an [`ImportNode`], counting nodes against `budget`; `None` past the depth or node
-/// limits.
-fn import_node(n: roxmltree::Node, depth: usize, budget: &mut usize) -> Option<ImportNode> {
- if depth > MAX_IMPORT_DEPTH || *budget == 0 {
- return None;
+/// Most bytes of names, namespaces, attributes and text an import copies out of its file: a
+/// namespace declared once is copied into every element and attribute that inherits it.
+pub(crate) const MAX_IMPORT_BYTES: usize = 4 * MAX_IMPORT;
+
+/// What an import may still copy: nodes and bytes.
+struct ImportBudget {
+ nodes: usize,
+ bytes: usize,
+}
+
+impl ImportBudget {
+ fn new() -> ImportBudget {
+ ImportBudget { nodes: MAX_NODES as usize, bytes: MAX_IMPORT_BYTES }
+ }
+
+ fn take_bytes(&mut self, n: usize) -> Result<(), XfaError> {
+ self.bytes = self
+ .bytes
+ .checked_sub(n)
+ .ok_or_else(|| XfaError::TooLarge(format!("the data file expands to more than {} MB", MAX_IMPORT_BYTES >> 20)))?;
+ Ok(())
+ }
+}
+
+/// `n` as an [`ImportNode`], counting nodes and copied bytes against `budget`; `TooLarge` past
+/// the depth or either budget.
+fn import_node(n: roxmltree::Node, depth: usize, budget: &mut ImportBudget) -> Result<ImportNode, XfaError> {
+ if depth > MAX_IMPORT_DEPTH {
+ return Err(XfaError::TooLarge(format!("the data file nests more than {MAX_IMPORT_DEPTH} levels deep")));
+ }
+ budget.nodes = budget.nodes.checked_sub(1).ok_or_else(|| XfaError::TooLarge("the data file holds too many nodes".into()))?;
+ let name = n.tag_name().name();
+ let ns = n.tag_name().namespace();
+ budget.take_bytes(name.len().saturating_add(ns.map_or(0, str::len)))?;
+ let mut attrs = Vec::new();
+ for a in n.attributes().filter(|a| a.name() != "xmlns" && a.namespace() != Some("http://www.w3.org/2000/xmlns/")) {
+ budget.take_bytes(a.namespace().map_or(0, str::len).saturating_add(a.name().len()).saturating_add(a.value().len()))?;
+ attrs.push((a.namespace().map(str::to_string), a.name().to_string(), a.value().to_string()));
}
- *budget -= 1;
let mut children = Vec::new();
let mut text = String::new();
for c in n.children() {
if c.is_element() {
children.push(import_node(c, depth + 1, budget)?);
} else if let Some(t) = c.text() {
+ budget.take_bytes(t.len())?;
text.push_str(t);
}
}
@@ -821,17 +854,7 @@ fn import_node(n: roxmltree::Node, depth: usize, budget: &mut usize) -> Option<I
if !children.is_empty() && text.trim().is_empty() {
text.clear();
}
- Some(ImportNode {
- name: n.tag_name().name().to_string(),
- ns: n.tag_name().namespace().map(str::to_string),
- attrs: n
- .attributes()
- .filter(|a| a.name() != "xmlns" && a.namespace() != Some("http://www.w3.org/2000/xmlns/"))
- .map(|a| (a.namespace().map(str::to_string), a.name().to_string(), a.value().to_string()))
- .collect(),
- text,
- children,
- })
+ Ok(ImportNode { name: name.to_string(), ns: ns.map(str::to_string), attrs, text, children })
}
/// `nodes` as markup for a packet whose XFA data namespace prefix is `xfa` (declared where
@@ -1379,15 +1402,14 @@ pub fn parse_data_file(text: &str, expect_root: Option<&str>) -> Result<Vec<Impo
{
return Err(XfaError::Malformed(format!("the data file's root is <{local}>; this form's data root is <{want}>")));
}
- let mut budget = MAX_NODES as usize;
- let node = import_node(root, 0, &mut budget).ok_or_else(|| XfaError::TooLarge("the data file holds too many nodes".into()))?;
+ let node = import_node(root, 0, &mut ImportBudget::new())?;
return Ok(vec![node]);
}
};
- let mut budget = MAX_NODES as usize;
+ let mut budget = ImportBudget::new();
let mut out = Vec::new();
for c in data.children().filter(|c| c.is_element()) {
- out.push(import_node(c, 1, &mut budget).ok_or_else(|| XfaError::TooLarge("the data file holds too many nodes".into()))?);
+ out.push(import_node(c, 1, &mut budget)?);
}
Ok(out)
}
diff --git a/crates/xfa/src/tests.rs b/crates/xfa/src/tests.rs
index 9aebee5bf..bf8872ad5 100644
--- a/crates/xfa/src/tests.rs
+++ b/crates/xfa/src/tests.rs
@@ -2742,3 +2742,19 @@ fn added_instances_are_queued_once_each() {
assert!(queued <= 200_000, "{queued} instance nodes queued");
assert!(r.warnings.iter().any(|w| w.contains("instances")), "{r:?}");
}
+
+/// A namespace declared once and inherited by many imported elements is not copied into each
+/// past the import's byte budget.
+#[test]
+fn an_inherited_namespace_does_not_multiply_an_import() {
+ use crate::data::parse_data_file;
+ let uri = format!("urn:{}", "n".repeat(70_000));
+ let xml = format!("<form1 xmlns:p=\"{uri}\">{}</form1>", "<p:a/>".repeat(1_000));
+ fn ns_bytes(nodes: &[crate::data::ImportNode]) -> usize {
+ nodes.iter().map(|n| n.ns.as_ref().map_or(0, String::len) + ns_bytes(&n.children)).sum()
+ }
+ match parse_data_file(&xml, None) {
+ Ok(nodes) => assert!(ns_bytes(&nodes) <= crate::data::MAX_IMPORT_BYTES, "{} bytes of namespaces copied", ns_bytes(&nodes)),
+ Err(e) => assert!(matches!(e, XfaError::TooLarge(_)), "{e:?}"),
+ }
+}