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, regex_detect};
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        regex_detect(
38            &PATTERNS,
39            self.name(),
40            AttackCategory::Injection,
41            Severity::Critical,
42            "XSS cross-site scripting detected",
43            input,
44        )
45    }
46}
47
48#[cfg(test)]
49mod tests {
50    use super::*;
51
52    fn det() -> XssDetector {
53        XssDetector
54    }
55
56    fn assert_hit(input: &str) {
57        crate::test_helpers::assert_detected(
58            &det(),
59            input,
60            AttackCategory::Injection,
61            Severity::Critical,
62        );
63    }
64
65    #[test]
66    fn name_is_xss() {
67        assert_eq!(det().name(), "xss");
68    }
69
70    #[test]
71    fn detects_common_payloads() {
72        for input in [
73            "<script>alert(1)</script>",
74            "<img src=x onerror=alert(1)>",
75            "javascript:alert(document.cookie)",
76            "<svg onload=alert(1)>",
77            "eval('alert(1)')",
78            "<iframe src=\"//evil.com\"></iframe>",
79            "data:text/html,<script>alert(1)</script>",
80        ] {
81            assert_hit(input);
82        }
83    }
84
85    #[test]
86    fn benign_inputs_not_detected() {
87        for input in [
88            "Hello, this is a normal text input. Nothing suspicious here.",
89            "The weather today is sunny with a high of 25 degrees.",
90            "Please call the office at 555-1234 for assistance.",
91            "Welcome to our website, please enjoy your stay.",
92        ] {
93            assert!(det().detect(input).is_none(), "false positive: {input}");
94        }
95    }
96
97    #[test]
98    fn edge_cases() {
99        assert!(det().detect("").is_none());
100        assert!(det().detect("   \t\n  ").is_none());
101        assert!(det().detect("こんにちは世界 你好").is_none());
102        // near misses: keyword present but not the payload form
103        assert!(det().detect("script alert(1)").is_none());
104        assert!(det().detect("javascript alert(1)").is_none());
105        assert!(det().detect("evaluate this expression carefully").is_none());
106    }
107
108    #[test]
109    fn obfuscated_variants_detected() {
110        for input in [
111            "<SCRIPT>alert(1)</SCRIPT>",
112            "<img src=x OnErRoR=alert(1)>",
113            "JaVaScRiPt:alert(1)",
114            "<SVG/onload=alert(1)>",
115        ] {
116            assert_hit(input);
117        }
118    }
119}