Skip to main content

security_rust/injection/
command_injection.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"`[^`]+`").unwrap(),
10        Regex::new(r"\$\([^)]+\)").unwrap(),
11        Regex::new(r"\|[\s]*\w+").unwrap(),
12        Regex::new(r"\|\|[\s]*\w+").unwrap(),
13        Regex::new(r"&&\s*\w+").unwrap(),
14        Regex::new(r"/dev/tcp[/\w]*").unwrap(),
15        Regex::new(r"(?i)passthru\s*\(").unwrap(),
16        Regex::new(r"(?i)shell_exec\s*\(").unwrap(),
17        Regex::new(r"(?i)system\s*\(").unwrap(),
18        Regex::new(r"(?i)exec\s*\(").unwrap(),
19        Regex::new(r"(?i)popen\s*\(").unwrap(),
20        Regex::new(r"(?i)pcntl_exec\s*\(").unwrap(),
21        Regex::new(r"(?i)cmd\.exe").unwrap(),
22        Regex::new(r"(?i)powershell").unwrap(),
23        Regex::new(r">/dev/null").unwrap(),
24    ]
25});
26
27pub struct CommandInjectionDetector;
28
29impl Detector for CommandInjectionDetector {
30    fn name(&self) -> &'static str {
31        "command_injection"
32    }
33
34    fn detect(&self, input: &str) -> Option<DetectionResult> {
35        for re in PATTERNS.iter() {
36            if let Some(m) = re.find(input) {
37                return Some(DetectionResult {
38                    attack_type: "command_injection".into(),
39                    category: AttackCategory::Injection,
40                    severity: Severity::Critical,
41                    matched_pattern: m.as_str().to_string(),
42                    offset: m.start(),
43                    message: "Command injection detected".into(),
44                });
45            }
46        }
47        None
48    }
49}