security_rust/injection/
nosql_injection.rs1use crate::{AttackCategory, DetectionResult, Detector, Severity, regex_detect};
4use regex::Regex;
5use std::sync::LazyLock;
6
7static PATTERNS: LazyLock<Regex> = LazyLock::new(|| {
12 Regex::new(concat!(
13 r#""(?i:\$ne"\s*:)"#,
14 r#"|'(?i:\$ne'\s*:)"#,
15 r#"|"(?i:\$gt"\s*:)"#,
16 r#"|"(?i:\$gte"\s*:)"#,
17 r#"|"(?i:\$lt"\s*:)"#,
18 r#"|"(?i:\$lte"\s*:)"#,
19 r#"|"(?i:\$regex"\s*:)"#,
20 r#"|"(?i:\$where"\s*:)"#,
21 r#"|"(?i:\$or"\s*:)"#,
22 r#"|(?i:["']?\$(?:eq|nin)["']?\s*:)"#,
27 ))
30 .unwrap()
31});
32
33pub struct NoSqlInjectionDetector;
34
35impl Detector for NoSqlInjectionDetector {
36 fn name(&self) -> &'static str {
37 "nosql_injection"
38 }
39
40 fn detect(&self, input: &str) -> Option<DetectionResult> {
41 regex_detect(
42 std::slice::from_ref(&*PATTERNS),
43 self.name(),
44 AttackCategory::Injection,
45 Severity::Critical,
46 "NoSQL injection detected",
47 input,
48 )
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 fn det() -> NoSqlInjectionDetector {
57 NoSqlInjectionDetector
58 }
59
60 fn assert_hit(input: &str) {
61 crate::test_helpers::assert_detected(
62 &det(),
63 input,
64 AttackCategory::Injection,
65 Severity::Critical,
66 );
67 }
68
69 #[test]
70 fn name_is_nosql_injection() {
71 assert_eq!(det().name(), "nosql_injection");
72 }
73
74 #[test]
75 fn detects_common_payloads() {
76 for input in [
77 r#"{"username": {"$ne": ""}}"#,
78 r#"{"$gt": ""}"#,
79 r#"{"user": {"$regex": "^admin"}}"#,
80 r#"{"$or": [{"role": "admin"}]}"#,
81 r#"{'$ne': ''}"#,
82 r#"{"pass": {"$nin": ["a"]}}"#,
83 r#"db.users.find({"$where": "sleep(5000)"})"#,
84 ] {
85 assert_hit(input);
86 }
87 }
88
89 #[test]
91 fn gt_authentication_bypass_still_caught_by_operator_pattern() {
92 let r = det().detect(r#"{"$gt": ""}"#).expect("应该命中");
93 assert_eq!(r.matched_pattern, r#""$gt":"#);
94 assert_eq!(r.offset, 1);
95 assert!(det().detect(r#"{ "$gt" : "" }"#).is_some());
97 }
98
99 #[test]
101 fn eq_and_nin_require_key_position() {
102 for input in [
103 r#"{"$eq": 1}"#,
104 r#"{"pass": {"$nin": ["a"]}}"#,
105 r#"{$nin: [1, 2]}"#, r#"{ "$eq" : "x" }"#,
107 ] {
108 assert_hit(input);
109 }
110 for input in [
111 "Use `$eq` for equality and `$nin` to exclude a set of values.",
112 "The $eq operator matches documents where the field equals the value.",
113 ] {
114 assert!(det().detect(input).is_none(), "false positive: {input}");
115 }
116 }
117
118 #[test]
120 fn ignores_realistic_json_and_prose() {
121 for input in [
122 r#"{"user": "dana", "roles": ["admin", "dev"], "active": true}"#,
123 r#"{"count": 42, "tags": {"a": 1, "b": 2}, "note": "hello"}"#,
124 "MongoDB 文档:用 $where / $regex 之前先看查询计划,别直接拼字符串",
125 "The invoice total is $250 and the tax is $19.99.",
126 "SELECT * FROM users WHERE age > 18 ORDER BY name",
127 "{\"a\": {\"b\": {\"c\": 1}}}",
128 ] {
129 assert!(det().detect(input).is_none(), "false positive: {input}");
130 }
131 }
132
133 #[test]
134 fn benign_inputs_not_detected() {
135 for input in [
136 r#"{"name": "John", "age": 30, "city": "New York"}"#,
137 r#"{"price": "$5.99"}"#,
138 "The total cost is $100 and the discount is 10%",
139 "The equation is simple to solve",
140 ] {
141 assert!(det().detect(input).is_none(), "false positive: {input}");
142 }
143 }
144
145 #[test]
146 fn edge_cases() {
147 assert!(det().detect("").is_none());
148 assert!(det().detect(" \t ").is_none());
149 assert!(det().detect("你好世界 こんにちは").is_none());
150 assert!(det().detect(r#"{"$ne"}"#).is_none());
152 assert!(det().detect(r#"{"ne": ""}"#).is_none());
153 assert!(det().detect("age > 18").is_none());
154 }
155
156 #[test]
157 fn obfuscated_variants_detected() {
158 for input in [r#"{"$NE": ""}"#, r#"{"$GTE": 5}"#, r#"{"$REGEX": "^a"}"#] {
159 assert_hit(input);
160 }
161 }
162}