Skip to main content

guard_core_engine/semantic/
patterns.rs

1use regex::Regex;
2
3/// Compiled structural regexes that detect attack syntax (HTML tags, function
4/// calls, command chains, path traversal, URLs).
5///
6/// Used by [`super::extract_suspicious_patterns`] and token extraction.
7/// Construct with `Default::default()` for the built-in pattern set.
8pub struct AttackStructures {
9    named: Vec<(&'static str, Regex)>,
10}
11
12impl AttackStructures {
13    /// Named (category, regex) pairs.
14    #[must_use]
15    pub fn named(&self) -> &[(&'static str, Regex)] {
16        &self.named
17    }
18
19    /// Iterate compiled regexes only (no category names).
20    pub fn compiled(&self) -> impl Iterator<Item = &Regex> {
21        self.named.iter().map(|(_, re)| re)
22    }
23}
24
25impl Default for AttackStructures {
26    fn default() -> Self {
27        let definitions: &[(&str, &str)] = &[
28            ("tag_like", r"<[^>]+>"),
29            ("function_call", r"\w+\s*\([^)]*\)"),
30            ("command_chain", r"[;&|]{1,2}"),
31            ("path_traversal", r"\.{2,}[/\\]"),
32            ("url_pattern", r"[a-z]+://"),
33        ];
34
35        let named = definitions
36            .iter()
37            .map(|&(name, pat)| {
38                let re = Regex::new(&format!("(?i){pat}")).expect("static pattern must compile");
39                (name, re)
40            })
41            .collect();
42
43        Self { named }
44    }
45}