Skip to content

Commit ea46c34

Browse files
committed
enabling security/saefty features in parsers
1 parent 155870b commit ea46c34

38 files changed

Lines changed: 2711 additions & 4148 deletions

‎Cargo.lock‎

Lines changed: 23 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎l5x/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,3 +18,4 @@ quick-xml = { version = "0.37", features = ["serialize", "overlapped-lists"] }
1818
serde = { version = "1.0", features = ["derive"] }
1919
winnow = "0.6"
2020
iecst = { path = "../iecst", version = "0.3" }
21+
thiserror = "1.0"

‎l5x/src/lib.rs‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ use quick_xml::de::from_str as xml_from_str;
3232
use quick_xml::se::to_string as xml_to_string;
3333
use serde::{Deserialize, Serialize};
3434

35+
// Security validation and limits
36+
pub mod security;
37+
pub use security::{SecurityLimits, SecurityError, validate_xml};
38+
3539
// RLL (Relay Ladder Logic) parser
3640
pub mod rll;
3741

@@ -47,6 +51,39 @@ pub fn from_str<'a, T: Deserialize<'a>>(xml: &'a str) -> Result<T, quick_xml::De
4751
xml_from_str(xml)
4852
}
4953

54+
/// Parse L5X XML string with security validation.
55+
///
56+
/// Validates input against security limits before parsing to protect
57+
/// against XML bombs, entity expansion, and other attacks.
58+
///
59+
/// # Example
60+
/// ```ignore
61+
/// use l5x::{Project, SecurityLimits, from_str_secure};
62+
///
63+
/// let xml = std::fs::read_to_string("project.L5X")?;
64+
/// let project: Project = from_str_secure(&xml, &SecurityLimits::strict())?;
65+
/// ```
66+
pub fn from_str_secure<'a, T: Deserialize<'a>>(
67+
xml: &'a str,
68+
limits: &SecurityLimits,
69+
) -> Result<T, SecureParseError> {
70+
// First validate against security limits
71+
validate_xml(xml.as_bytes(), limits)?;
72+
73+
// Then parse if validation passed
74+
xml_from_str(xml).map_err(SecureParseError::ParseError)
75+
}
76+
77+
/// Combined error type for secure parsing
78+
#[derive(Debug, thiserror::Error)]
79+
pub enum SecureParseError {
80+
#[error("Security validation failed: {0}")]
81+
SecurityError(#[from] SecurityError),
82+
83+
#[error("XML parsing failed: {0}")]
84+
ParseError(quick_xml::DeError),
85+
}
86+
5087
/// Serialize a structure to L5X XML string.
5188
pub fn to_string<T: Serialize>(value: &T) -> Result<String, quick_xml::SeError> {
5289
xml_to_string(value)

‎l5x/src/security.rs‎

Lines changed: 244 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,244 @@
1+
//! Security limits and protections for L5X parsing
2+
//!
3+
//! Protects against:
4+
//! - XML bombs (billion laughs attack)
5+
//! - Entity expansion attacks
6+
//! - Deep nesting attacks
7+
//! - Memory exhaustion
8+
//! - External entity injection
9+
10+
use quick_xml::Reader;
11+
use quick_xml::events::Event;
12+
use std::io::BufRead;
13+
14+
/// Security limits for parsing L5X files
15+
#[derive(Debug, Clone)]
16+
pub struct SecurityLimits {
17+
/// Maximum XML file size in bytes
18+
pub max_file_size: usize,
19+
20+
/// Maximum depth of nested XML elements
21+
pub max_nesting_depth: usize,
22+
23+
/// Maximum number of attributes per element
24+
pub max_attributes_per_element: usize,
25+
26+
/// Maximum attribute name/value length
27+
pub max_attribute_length: usize,
28+
29+
/// Maximum text content length
30+
pub max_text_length: usize,
31+
32+
/// Maximum number of elements in document
33+
pub max_elements: usize,
34+
35+
/// Maximum buffer size for quick-xml
36+
pub max_buffer_size: usize,
37+
}
38+
39+
impl Default for SecurityLimits {
40+
fn default() -> Self {
41+
SecurityLimits {
42+
max_file_size: 100 * 1024 * 1024, // 100 MB
43+
max_nesting_depth: 100, // 100 levels
44+
max_attributes_per_element: 100, // 100 attributes
45+
max_attribute_length: 10_000, // 10 KB
46+
max_text_length: 10 * 1024 * 1024, // 10 MB
47+
max_elements: 1_000_000, // 1M elements
48+
max_buffer_size: 10 * 1024 * 1024, // 10 MB buffer
49+
}
50+
}
51+
}
52+
53+
impl SecurityLimits {
54+
/// Conservative limits for untrusted input
55+
pub fn strict() -> Self {
56+
SecurityLimits {
57+
max_file_size: 10 * 1024 * 1024, // 10 MB
58+
max_nesting_depth: 32, // 32 levels
59+
max_attributes_per_element: 50, // 50 attributes
60+
max_attribute_length: 1_000, // 1 KB
61+
max_text_length: 1 * 1024 * 1024, // 1 MB
62+
max_elements: 100_000, // 100K elements
63+
max_buffer_size: 1 * 1024 * 1024, // 1 MB buffer
64+
}
65+
}
66+
67+
/// Relaxed limits for trusted input
68+
pub fn relaxed() -> Self {
69+
SecurityLimits {
70+
max_file_size: 500 * 1024 * 1024, // 500 MB
71+
max_nesting_depth: 256, // 256 levels
72+
max_attributes_per_element: 500, // 500 attributes
73+
max_attribute_length: 100_000, // 100 KB
74+
max_text_length: 100 * 1024 * 1024, // 100 MB
75+
max_elements: 10_000_000, // 10M elements
76+
max_buffer_size: 100 * 1024 * 1024, // 100 MB buffer
77+
}
78+
}
79+
}
80+
81+
/// Validate XML input against security limits before parsing
82+
pub fn validate_xml<R: BufRead>(
83+
reader: R,
84+
limits: &SecurityLimits,
85+
) -> Result<(), SecurityError> {
86+
let mut xml_reader = Reader::from_reader(reader);
87+
88+
// Configure quick-xml security settings
89+
xml_reader
90+
.config_mut()
91+
.expand_empty_elements = false; // Don't expand empty elements
92+
93+
xml_reader
94+
.config_mut()
95+
.trim_text(true); // Trim whitespace to save memory
96+
97+
// Set buffer size limit
98+
xml_reader
99+
.config_mut()
100+
.max_buffer_size(limits.max_buffer_size);
101+
102+
let mut buf = Vec::new();
103+
let mut depth = 0;
104+
let mut element_count = 0;
105+
106+
loop {
107+
match xml_reader.read_event_into(&mut buf) {
108+
Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
109+
depth += 1;
110+
element_count += 1;
111+
112+
// Check nesting depth
113+
if depth > limits.max_nesting_depth {
114+
return Err(SecurityError::NestingTooDeep {
115+
depth,
116+
limit: limits.max_nesting_depth,
117+
});
118+
}
119+
120+
// Check element count
121+
if element_count > limits.max_elements {
122+
return Err(SecurityError::TooManyElements {
123+
count: element_count,
124+
limit: limits.max_elements,
125+
});
126+
}
127+
128+
// Check attributes
129+
let attrs: Vec<_> = e.attributes().collect();
130+
if attrs.len() > limits.max_attributes_per_element {
131+
return Err(SecurityError::TooManyAttributes {
132+
count: attrs.len(),
133+
limit: limits.max_attributes_per_element,
134+
});
135+
}
136+
137+
for attr_result in attrs {
138+
let attr = attr_result.map_err(|e| SecurityError::XmlError(e.to_string()))?;
139+
140+
// Check attribute key length
141+
if attr.key.as_ref().len() > limits.max_attribute_length {
142+
return Err(SecurityError::AttributeTooLong {
143+
length: attr.key.as_ref().len(),
144+
limit: limits.max_attribute_length,
145+
});
146+
}
147+
148+
// Check attribute value length
149+
if attr.value.len() > limits.max_attribute_length {
150+
return Err(SecurityError::AttributeTooLong {
151+
length: attr.value.len(),
152+
limit: limits.max_attribute_length,
153+
});
154+
}
155+
}
156+
}
157+
Ok(Event::End(_)) => {
158+
if depth > 0 {
159+
depth -= 1;
160+
}
161+
}
162+
Ok(Event::Text(e)) => {
163+
let text = e.unescape().map_err(|e| SecurityError::XmlError(e.to_string()))?;
164+
if text.len() > limits.max_text_length {
165+
return Err(SecurityError::TextTooLong {
166+
length: text.len(),
167+
limit: limits.max_text_length,
168+
});
169+
}
170+
}
171+
Ok(Event::Eof) => break,
172+
Err(e) => return Err(SecurityError::XmlError(e.to_string())),
173+
_ => {}
174+
}
175+
176+
buf.clear();
177+
}
178+
179+
Ok(())
180+
}
181+
182+
/// Security validation errors
183+
#[derive(Debug, thiserror::Error)]
184+
pub enum SecurityError {
185+
#[error("XML nesting too deep: {depth} levels (limit: {limit})")]
186+
NestingTooDeep { depth: usize, limit: usize },
187+
188+
#[error("Too many XML elements: {count} (limit: {limit})")]
189+
TooManyElements { count: usize, limit: usize },
190+
191+
#[error("Too many attributes: {count} (limit: {limit})")]
192+
TooManyAttributes { count: usize, limit: usize },
193+
194+
#[error("Attribute too long: {length} bytes (limit: {limit})")]
195+
AttributeTooLong { length: usize, limit: usize },
196+
197+
#[error("Text content too long: {length} bytes (limit: {limit})")]
198+
TextTooLong { length: usize, limit: usize },
199+
200+
#[error("File too large: {size} bytes (limit: {limit})")]
201+
FileTooLarge { size: usize, limit: usize },
202+
203+
#[error("XML parsing error: {0}")]
204+
XmlError(String),
205+
}
206+
207+
#[cfg(test)]
208+
mod tests {
209+
use super::*;
210+
211+
#[test]
212+
fn test_valid_xml() {
213+
let xml = r#"<Project><Controller Name="Test"></Controller></Project>"#;
214+
let result = validate_xml(xml.as_bytes(), &SecurityLimits::default());
215+
assert!(result.is_ok());
216+
}
217+
218+
#[test]
219+
fn test_deep_nesting() {
220+
let mut xml = String::from("<a>");
221+
for _ in 0..200 {
222+
xml.push_str("<b>");
223+
}
224+
for _ in 0..200 {
225+
xml.push_str("</b>");
226+
}
227+
xml.push_str("</a>");
228+
229+
let result = validate_xml(xml.as_bytes(), &SecurityLimits::strict());
230+
assert!(matches!(result, Err(SecurityError::NestingTooDeep { .. })));
231+
}
232+
233+
#[test]
234+
fn test_too_many_attributes() {
235+
let mut xml = String::from("<Element ");
236+
for i in 0..200 {
237+
xml.push_str(&format!("attr{}='value' ", i));
238+
}
239+
xml.push_str("/>");
240+
241+
let result = validate_xml(xml.as_bytes(), &SecurityLimits::strict());
242+
assert!(matches!(result, Err(SecurityError::TooManyAttributes { .. })));
243+
}
244+
}

0 commit comments

Comments
 (0)