Skip to main content

security_rust/injection/
sql_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"(?i)UNION\s+(?:ALL\s+)?SELECT").unwrap(),
10        Regex::new(r"(?i)SELECT\s+.*\s+FROM\s+").unwrap(),
11        Regex::new(r"(?i)/\*!.*?\*/").unwrap(),
12        Regex::new(r"(?i)sleep\s*\(").unwrap(),
13        Regex::new(r"(?i)benchmark\s*\(").unwrap(),
14        Regex::new(r"(?i)pg_sleep\s*\(").unwrap(),
15        Regex::new(r"(?i)information_schema").unwrap(),
16        Regex::new(r"(?i)exec\s+(?:sp_|xp_)").unwrap(),
17        Regex::new(r"(?i)WAITFOR\s+DELAY").unwrap(),
18        Regex::new(r"(?i)'\s*OR\s*'1'\s*=\s*'1").unwrap(),
19        Regex::new(r"(?i)'\s*OR\s*1\s*=\s*1\s*--").unwrap(),
20        Regex::new(r"(?i)LOAD_FILE\s*\(").unwrap(),
21        Regex::new(r"(?i)INTO\s+(?:OUT|DUMP)FILE").unwrap(),
22        Regex::new(r"(?i)OUTFILE\s+").unwrap(),
23        Regex::new(r"(?i)SELECT\s+\*").unwrap(),
24        Regex::new(r"(?i)DROP\s+TABLE").unwrap(),
25        Regex::new(r"(?i)INSERT\s+INTO").unwrap(),
26    ]
27});
28
29pub struct SqlInjectionDetector;
30
31impl Detector for SqlInjectionDetector {
32    fn name(&self) -> &'static str {
33        "sql_injection"
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: "sql_injection".into(),
41                    category: AttackCategory::Injection,
42                    severity: Severity::Critical,
43                    matched_pattern: m.as_str().to_string(),
44                    offset: m.start(),
45                    message: "SQL injection detected".into(),
46                });
47            }
48        }
49        None
50    }
51}