Skip to main content

security_rust/injection/
xss.rs

1// Copyright (c) 2026 erik <erik@erik.xyz> — https://erik.xyz
2
3use crate::{AttackCategory, DetectionResult, Detector, Severity};
4use regex::Regex;
5use std::sync::LazyLock;
6
7static PATTERNS: LazyLock<Vec<Regex>> = LazyLock::new(|| {
8    vec![
9        Regex::new(r"(?i)<script[\s/>]").unwrap(),
10        Regex::new(r"(?i)on(?:error|load|click|mouse(?:over|out|down|up|move)|key(?:down|up|press)|focus|blur|change|submit|reset|scroll|resize|abort|select|start|drag|drop|play|pause|ended|volumechange|animationstart|animationend|transitionend|touchstart|touchend|pointerdown|pointerup|wheel|auxclick|canplay|canplaythrough|close|cuechange|dblclick|durationchange|emptied|fullscreenchange|gotpointercapture|input|invalid|loadeddata|loadedmetadata|loadstart|lostpointercapture|offline|online|pagehide|pageshow|popstate|progress|ratechange|securitypolicyviolation|seeked|seeking|show|stalled|suspend|timeupdate|toggle|waiting)\s*=").unwrap(),
11        Regex::new(r"(?i)javascript\s*:").unwrap(),
12        Regex::new(r"(?i)<svg[\s/>]").unwrap(),
13        Regex::new(r"(?i)expression\s*\(").unwrap(),
14        Regex::new(r"(?i)<iframe[\s/>]").unwrap(),
15        Regex::new(r"(?i)<embed[\s/>]").unwrap(),
16        Regex::new(r"(?i)<object[\s/>]").unwrap(),
17        Regex::new(r"(?i)vbscript\s*:").unwrap(),
18        Regex::new(r"(?i)data\s*:\s*text/html").unwrap(),
19        Regex::new(r"(?i)<link[\s/>]").unwrap(),
20        Regex::new(r"(?i)<meta[\s/>]").unwrap(),
21        Regex::new(r"(?i)eval\s*\(").unwrap(),
22        Regex::new(r"(?i)fromCharCode\s*\(").unwrap(),
23        Regex::new(r"(?i)document\.cookie").unwrap(),
24        Regex::new(r"(?i)document\.write\s*\(").unwrap(),
25        Regex::new(r"(?i)window\.location").unwrap(),
26    ]
27});
28
29pub struct XssDetector;
30
31impl Detector for XssDetector {
32    fn name(&self) -> &'static str {
33        "xss"
34    }
35
36    fn detect(&self, input: &str) -> Option<DetectionResult> {
37        for re in PATTERNS.iter() {
38            if let Some(m) = re.find(input) {
39                return Some(DetectionResult {
40                    attack_type: "xss".into(),
41                    category: AttackCategory::Injection,
42                    severity: Severity::Critical,
43                    matched_pattern: m.as_str().to_string(),
44                    offset: m.start(),
45                    message: "XSS cross-site scripting detected".into(),
46                });
47            }
48        }
49        None
50    }
51}