Union-based SQL Injection is a type of SQL Injection that uses the UNION operator to combine the results of two or more SELECT statements. Attackers use this technique to retrieve data from other tables or databases.
How Union-based SQL Injection Works
- Attackers identify a vulnerable input field and inject a UNION operator.
- The application runs the original query and the injected query, combining the results.
- Attackers analyze the combined results to retrieve sensitive data.
Example:
SQL
http://example.com/products.php?id=1 UNION SELECT username, password FROM users -- In this example, the attacker injects a UNION operator and a SELECT statement to retrieve usernames and passwords from the users table.
Requirements for Union-based SQL Injection
- The application must use a UNION operator.
- The number of columns in the original query must match the number of columns in the injected query.
- The data types of the columns must be compatible.
Exploiting Union-based SQL Injection
- Identify the number of columns in the original query using
ORDER BYorLIMITclauses. - Use
UNION SELECTto inject a query with the same number of columns. - Retrieve sensitive data by injecting queries that select specific columns.
Example:
SQL
http://example.com/products.php?id=1 UNION SELECT 1, 2, 3, 4, 5 -- In this example, the attacker injects a UNION SELECT statement with 5 columns to match the original query.
Preventing Union-based SQL Injection
- Use Prepared Statements (PS)
- Validate user input
- Use an ORM (Object-Relational Mapping)
- Limit database privileges to the application user