security_rust/injection/
nosql_injection.rs1use 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)\$ne"\s*:"#).unwrap(),
10 Regex::new(r#"'(?i)\$ne'\s*:"#).unwrap(),
11 Regex::new(r#""(?i)\$gt"\s*:"#).unwrap(),
12 Regex::new(r#""(?i)\$gte"\s*:"#).unwrap(),
13 Regex::new(r#""(?i)\$lt"\s*:"#).unwrap(),
14 Regex::new(r#""(?i)\$lte"\s*:"#).unwrap(),
15 Regex::new(r#""(?i)\$regex"\s*:"#).unwrap(),
16 Regex::new(r#""(?i)\$where"\s*:"#).unwrap(),
17 Regex::new(r#""(?i)\$or"\s*:"#).unwrap(),
18 Regex::new(r"(?i)\$eq").unwrap(),
19 Regex::new(r"(?i)\$nin").unwrap(),
20 Regex::new(r#"\{\s*"\$gt"\s*:\s*""\s*\}"#).unwrap(),
21 ]
22});
23
24pub struct NoSqlInjectionDetector;
25
26impl Detector for NoSqlInjectionDetector {
27 fn name(&self) -> &'static str {
28 "nosql_injection"
29 }
30
31 fn detect(&self, input: &str) -> Option<DetectionResult> {
32 regex_detect(
33 &PATTERNS,
34 self.name(),
35 AttackCategory::Injection,
36 Severity::Critical,
37 "NoSQL injection detected",
38 input,
39 )
40 }
41}
42
43#[cfg(test)]
44mod tests {
45 use super::*;
46
47 fn det() -> NoSqlInjectionDetector {
48 NoSqlInjectionDetector
49 }
50
51 fn assert_hit(input: &str) {
52 crate::test_helpers::assert_detected(
53 &det(),
54 input,
55 AttackCategory::Injection,
56 Severity::Critical,
57 );
58 }
59
60 #[test]
61 fn name_is_nosql_injection() {
62 assert_eq!(det().name(), "nosql_injection");
63 }
64
65 #[test]
66 fn detects_common_payloads() {
67 for input in [
68 r#"{"username": {"$ne": ""}}"#,
69 r#"{"$gt": ""}"#,
70 r#"{"user": {"$regex": "^admin"}}"#,
71 r#"{"$or": [{"role": "admin"}]}"#,
72 r#"{'$ne': ''}"#,
73 r#"{"pass": {"$nin": ["a"]}}"#,
74 r#"db.users.find({"$where": "sleep(5000)"})"#,
75 ] {
76 assert_hit(input);
77 }
78 }
79
80 #[test]
81 fn benign_inputs_not_detected() {
82 for input in [
83 r#"{"name": "John", "age": 30, "city": "New York"}"#,
84 r#"{"price": "$5.99"}"#,
85 "The total cost is $100 and the discount is 10%",
86 "The equation is simple to solve",
87 ] {
88 assert!(det().detect(input).is_none(), "false positive: {input}");
89 }
90 }
91
92 #[test]
93 fn edge_cases() {
94 assert!(det().detect("").is_none());
95 assert!(det().detect(" \t ").is_none());
96 assert!(det().detect("你好世界 こんにちは").is_none());
97 assert!(det().detect(r#"{"$ne"}"#).is_none());
99 assert!(det().detect(r#"{"ne": ""}"#).is_none());
100 assert!(det().detect("age > 18").is_none());
101 }
102
103 #[test]
104 fn obfuscated_variants_detected() {
105 for input in [r#"{"$NE": ""}"#, r#"{"$GTE": 5}"#, r#"{"$REGEX": "^a"}"#] {
106 assert_hit(input);
107 }
108 }
109}