use crate::{AttackCategory, DetectionResult, Detector, Severity, regex_detect};
use regex::Regex;
use std::sync::LazyLock;
static PATTERNS: LazyLock<Regex> = LazyLock::new(|| {
Regex::new(concat!(
r#""(?i:\$ne"\s*:)"#,
r#"|'(?i:\$ne'\s*:)"#,
r#"|"(?i:\$gt"\s*:)"#,
r#"|"(?i:\$gte"\s*:)"#,
r#"|"(?i:\$lt"\s*:)"#,
r#"|"(?i:\$lte"\s*:)"#,
r#"|"(?i:\$regex"\s*:)"#,
r#"|"(?i:\$where"\s*:)"#,
r#"|"(?i:\$or"\s*:)"#,
r#"|(?i:["']?\$(?:eq|nin)["']?\s*:)"#,
))
.unwrap()
});
pub struct NoSqlInjectionDetector;
impl Detector for NoSqlInjectionDetector {
fn name(&self) -> &'static str {
"nosql_injection"
}
fn detect(&self, input: &str) -> Option<DetectionResult> {
regex_detect(
std::slice::from_ref(&*PATTERNS),
self.name(),
AttackCategory::Injection,
Severity::Critical,
"NoSQL injection detected",
input,
)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn det() -> NoSqlInjectionDetector {
NoSqlInjectionDetector
}
fn assert_hit(input: &str) {
crate::test_helpers::assert_detected(
&det(),
input,
AttackCategory::Injection,
Severity::Critical,
);
}
#[test]
fn name_is_nosql_injection() {
assert_eq!(det().name(), "nosql_injection");
}
#[test]
fn detects_common_payloads() {
for input in [
r#"{"username": {"$ne": ""}}"#,
r#"{"$gt": ""}"#,
r#"{"user": {"$regex": "^admin"}}"#,
r#"{"$or": [{"role": "admin"}]}"#,
r#"{'$ne': ''}"#,
r#"{"pass": {"$nin": ["a"]}}"#,
r#"db.users.find({"$where": "sleep(5000)"})"#,
] {
assert_hit(input);
}
}
#[test]
fn gt_authentication_bypass_still_caught_by_operator_pattern() {
let r = det().detect(r#"{"$gt": ""}"#).expect("应该命中");
assert_eq!(r.matched_pattern, r#""$gt":"#);
assert_eq!(r.offset, 1);
assert!(det().detect(r#"{ "$gt" : "" }"#).is_some());
}
#[test]
fn eq_and_nin_require_key_position() {
for input in [
r#"{"$eq": 1}"#,
r#"{"pass": {"$nin": ["a"]}}"#,
r#"{$nin: [1, 2]}"#, r#"{ "$eq" : "x" }"#,
] {
assert_hit(input);
}
for input in [
"Use `$eq` for equality and `$nin` to exclude a set of values.",
"The $eq operator matches documents where the field equals the value.",
] {
assert!(det().detect(input).is_none(), "false positive: {input}");
}
}
#[test]
fn ignores_realistic_json_and_prose() {
for input in [
r#"{"user": "dana", "roles": ["admin", "dev"], "active": true}"#,
r#"{"count": 42, "tags": {"a": 1, "b": 2}, "note": "hello"}"#,
"MongoDB 文档:用 $where / $regex 之前先看查询计划,别直接拼字符串",
"The invoice total is $250 and the tax is $19.99.",
"SELECT * FROM users WHERE age > 18 ORDER BY name",
"{\"a\": {\"b\": {\"c\": 1}}}",
] {
assert!(det().detect(input).is_none(), "false positive: {input}");
}
}
#[test]
fn benign_inputs_not_detected() {
for input in [
r#"{"name": "John", "age": 30, "city": "New York"}"#,
r#"{"price": "$5.99"}"#,
"The total cost is $100 and the discount is 10%",
"The equation is simple to solve",
] {
assert!(det().detect(input).is_none(), "false positive: {input}");
}
}
#[test]
fn edge_cases() {
assert!(det().detect("").is_none());
assert!(det().detect(" \t ").is_none());
assert!(det().detect("你好世界 こんにちは").is_none());
assert!(det().detect(r#"{"$ne"}"#).is_none());
assert!(det().detect(r#"{"ne": ""}"#).is_none());
assert!(det().detect("age > 18").is_none());
}
#[test]
fn obfuscated_variants_detected() {
for input in [r#"{"$NE": ""}"#, r#"{"$GTE": 5}"#, r#"{"$REGEX": "^a"}"#] {
assert_hit(input);
}
}
}