Skip to main content

security_rust/injection/
nosql_injection.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
7/// 10 条分支合并成 1 条 alternation —— `regex_detect` 对列表里每条 `Regex` 各跑一次
8/// `find`,干净输入下 10 次全文扫描变 1 次。分支顺序 = 原 vec 顺序(同一位置上取最左
9/// 分支;与「按列表顺序取第一条命中的模式」相比偏移量可能不同,档位不变)。
10/// 内联 flag 一律裹进 `(?i:…)` —— 裸 `(?i)` 的作用域会蔓延到它后面拼进来的分支。
11static 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        // `$eq` / `$nin` 只有处在**键位置**(后面跟 `:`)才是查询操作符。
23        // 裸词形在正常文档里满地都是:「用 `$eq` 判断相等、`$nin` 排除一组值」
24        // 这类 MongoDB/Node 说明曾被判 Critical。与上面九条的形态保持一致,
25        // 只是引号可选(JS 对象字面量里可以写 `{$nin: [...]}`)。
26        r#"|(?i:["']?\$(?:eq|nin)["']?\s*:)"#,
27        // 曾有 `\{\s*"\$gt"\s*:\s*""\s*\}`——永远匹配不到:凡是命中它的输入,
28        // 上面第 3 条的 `"\$gt"\s*:` 都已经先命中(find 取第一条命中的模式)。
29    ))
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    /// 删掉那条死模式后,认证绕过形态仍必须由 `"$gt"\s*:` 命中(README 承诺的行为)。
90    #[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        // 空格变体同理
96        assert!(det().detect(r#"{ "$gt" : "" }"#).is_some());
97    }
98
99    /// `$eq` / `$nin` 收紧后:键位置(带 `:`)仍报,文档里提到操作符名不报。
100    #[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]}"#, // JS 对象字面量:引号可选
106            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    /// 真实语料:普通 JSON、账单散文、文档里的裸操作符名都不该报。
119    #[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        // near misses: operator without colon or without dollar sign
151        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}