Search code examples
phppostgresqlpdosql-injection

Create a PHP application vulnerable to multi-statement SQL injections


I am trying to create an application in PHP using PDO that is deliberately vulnerable to SQL injection for educational purposes. The underlying database is Postgres.

With pdo->query I can demonstrate ' OR 1=1; -- style injections easily enough with something like:

$stmt = $pdo->query("SELECT amount FROM client.transactions WHERE clientid='". $id ."' ORDER BY amount DESC");

But if I try to piggyback a second statement with something like '; UPDATE client.transactions SET amount=50000000 WHERE id=1; -- it does not work as the statement is sent as a prepared statement after $id is appended, and Postgres gives:

SQLSTATE[42601]: Syntax error: 7 ERROR: cannot insert multiple commands into a prepared statement

Ideally the code would be fairly natural as I would like to share and compare with a version using pdo->prepare. What I guess I would need is something like mysqli::multi_query but that I could run on Postgres, or any way to execute an SQL query/statement that is not prepared.


Solution

  • I found a solution using pg_query rather than PDOs.

    $conn = pg_connect("host = ... port = ... dbname = ... user = ... password = ...");
    $stmt = pg_query($conn, "SELECT amount FROM client.transactions WHERE clientid='". $id ."' ORDER BY amount DESC");
    while ($row = pg_fetch_assoc($result))
    {
       // ...
    }
    

    This is vulnerable to '; UPDATE client.transactions SET amount=50000000 WHERE id=1; -- style attacks.