1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
//! # Entity Mapper & XXE Security Guard
//!
//! Provides predefined entity mapping (`&`, `<`, `>`, `"`, `'`), numeric reference decoding (`A`, `A`), and recursive expansion limits.
use crate::alloc_prelude::*;
use crate::error::{Result, XmlError};
#[cfg(not(feature = "std"))]
use alloc::collections::BTreeMap as HashMap;
#[cfg(feature = "std")]
use std::collections::HashMap;
/// Standard XML 1.0 predefined entity table mappings `(name, replacement)`.
pub const PREDEFINED_ENTITIES: &[(&str, &str)] = &[
("lt", "<"),
("gt", ">"),
("amp", "&"),
("quot", "\""),
("apos", "'"),
];
/// Entity table mapping entity reference names to replacement text with depth recursion and byte size tracking.
#[derive(Debug, Clone)]
pub struct EntityMapper {
entities: HashMap<String, String>,
max_depth: usize,
max_expansion_size: usize,
pub allow_undeclared: bool,
}
impl Default for EntityMapper {
fn default() -> Self {
let mut map = HashMap::new();
for &(name, value) in PREDEFINED_ENTITIES {
map.insert(name.into(), value.into());
}
Self {
entities: map,
max_depth: 512,
max_expansion_size: 10 * 1024 * 1024,
allow_undeclared: false,
}
}
}
impl EntityMapper {
/// Instantiates a new [`EntityMapper`] with a given max recursion depth limit.
pub fn new(max_depth: usize) -> Self {
let mut s = Self::default();
s.max_depth = max_depth;
s
}
/// Instantiates a new [`EntityMapper`] with custom recursion depth and total expansion size limits.
pub fn with_limits(max_depth: usize, max_expansion_size: usize) -> Self {
let mut s = Self::default();
s.max_depth = max_depth;
s.max_expansion_size = max_expansion_size;
s
}
/// Registers a custom entity reference name and replacement value.
/// Per XML 1.0 §4.2, the first declaration of an entity is binding.
pub fn register(&mut self, name: impl Into<String>, value: impl Into<String>) {
let name_str = name.into();
self.entities
.entry(name_str)
.or_insert_with(|| value.into());
}
/// Looks up an entity reference replacement value by name.
pub fn get(&self, name: &str) -> Option<&String> {
self.entities.get(name)
}
/// Expands entity references and numeric character references within input string slice.
///
/// # Errors
/// Returns [`XmlError::SecurityLimitExceeded`] if expansion depth or total expansion size exceeds configured thresholds (XML bomb guard).
pub fn expand(&self, input: &str) -> Result<String> {
if !input.contains('&') {
return Ok(input.to_string());
}
let mut total_expanded = 0;
self.expand_with_depth(input, 0, &mut total_expanded)
}
fn expand_with_depth(
&self,
input: &str,
depth: usize,
total_expanded: &mut usize,
) -> Result<String> {
if depth > self.max_depth {
return Err(XmlError::SecurityLimitExceeded(
"Maximum entity expansion depth exceeded (possible XML Bomb/Billion Laughs)".into(),
));
}
let mut result = String::with_capacity(input.len());
let mut pos = 0;
let bytes = input.as_bytes();
while pos < bytes.len() {
if bytes[pos..].starts_with(b"<![CDATA[") {
if let Some(cdata_end) = input[pos..].find("]]>") {
let end_idx = pos + cdata_end + 3;
result.push_str(&input[pos..end_idx]);
pos = end_idx;
continue;
}
}
if bytes[pos] == b'&' {
if let Some(semi_offset) = input[pos..].find(';') {
let semi_idx = pos + semi_offset;
let entity_ref = &input[pos + 1..semi_idx];
if entity_ref.starts_with('#') {
// Numeric reference (dec or hex)
let code_str = &entity_ref[1..];
let codepoint = if let Some(hex_digits) = code_str.strip_prefix('x') {
if hex_digits.is_empty() {
return Err(XmlError::EntityError(
"Empty hex character reference".into(),
));
}
u32::from_str_radix(hex_digits, 16)
} else if code_str.starts_with('X') {
return Err(XmlError::EntityError(format!(
"Malformed numeric entity reference, uppercase 'X' forbidden: &{entity_ref};"
)));
} else {
if code_str.is_empty() {
return Err(XmlError::EntityError(
"Empty numeric character reference".into(),
));
}
code_str.parse::<u32>()
};
match codepoint {
Ok(cp) => {
if let Some(ch) = char::from_u32(cp) {
// XML 1.0 §4.1 [66] WFC: Legal Character
if !crate::io::char_utils::is_valid_xml_char(ch) {
return Err(XmlError::EntityError(format!(
"Forbidden XML character in character reference: &#x{cp:x};"
)));
}
*total_expanded += ch.len_utf8();
if *total_expanded > self.max_expansion_size {
return Err(XmlError::SecurityLimitExceeded(format!(
"Maximum cumulative entity expansion size of {} bytes exceeded",
self.max_expansion_size
)));
}
result.push(ch);
} else {
return Err(XmlError::EntityError(format!(
"Invalid character reference code point: {code_str}"
)));
}
}
Err(_) => {
return Err(XmlError::EntityError(format!(
"Malformed numeric entity reference: &{entity_ref};"
)));
}
}
} else {
// XML 1.0 §4.1 [68] EntityRef ::= '&' Name ';'
let mut name_chars = entity_ref.chars();
let is_valid_name = match name_chars.next() {
Some(first) => {
crate::io::char_utils::is_xml_name_start(first)
&& name_chars.all(crate::io::char_utils::is_xml_name_char)
}
None => false,
};
if !is_valid_name {
return Err(XmlError::EntityError(format!(
"Malformed entity reference with invalid name: &{entity_ref};"
)));
}
// Named reference
match entity_ref {
"lt" => {
*total_expanded += 1;
result.push('<');
}
"gt" => {
*total_expanded += 1;
result.push('>');
}
"amp" => {
*total_expanded += 1;
result.push('&');
}
"quot" => {
*total_expanded += 1;
result.push('"');
}
"apos" => {
*total_expanded += 1;
result.push('\'');
}
_ => {
if let Some(val) = self.entities.get(entity_ref) {
let expanded_val =
self.expand_with_depth(val, depth + 1, total_expanded)?;
result.push_str(&expanded_val);
} else if self.allow_undeclared {
result.push('&');
result.push_str(entity_ref);
result.push(';');
} else {
return Err(XmlError::EntityError(format!(
"Undeclared entity reference: &{entity_ref};"
)));
}
}
}
if *total_expanded > self.max_expansion_size {
return Err(XmlError::SecurityLimitExceeded(format!(
"Maximum cumulative entity expansion size of {} bytes exceeded",
self.max_expansion_size
)));
}
}
pos = semi_idx + 1;
} else {
return Err(XmlError::EntityError(
"Unterminated entity reference missing ';'".into(),
));
}
} else {
let ch = input[pos..].chars().next().ok_or_else(|| {
XmlError::EntityError(
"Unexpected EOF reading character in entity expansion".into(),
)
})?;
*total_expanded += ch.len_utf8();
if *total_expanded > self.max_expansion_size {
return Err(XmlError::SecurityLimitExceeded(format!(
"Maximum cumulative entity expansion size of {} bytes exceeded",
self.max_expansion_size
)));
}
result.push(ch);
pos += ch.len_utf8();
}
}
Ok(result)
}
}