> For the complete documentation index, see [llms.txt](https://csyclub-iiitk.gitbook.io/ctf-guide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://csyclub-iiitk.gitbook.io/ctf-guide/web-exploitation/intro-to-sqli/union-based-attacks.md).

# Union Based Attacks

## Introduction

Union-Based SQL Injection is a type of SQL injection attack that leverages the SQL UNION operator to combine the results of two or more SELECT queries into a single result set. This method can be used by attackers to extract data from a database by adding their own queries to the original query, which the application executes.

## Table of Contents

* [SQL Injection: Union-Based SQL Injection](#sql-injection-union-based-sql-injection)
  * [Introduction](#introduction)
  * [Table of Contents](#table-of-contents)
  * [How to identify](#how-to-identify)
  * [Code/tools/websites](#codetoolswebsites)
    * [Code Snippets](#code-snippets)
    * [Tools](#tools)
    * [Websites](#websites)
  * [Sample problem](#sample-problem)
    * [Problem Statement](#problem-statement)
    * [Solution](#solution)
  * [References](#references)
  * [Conclusion](#conclusion)

## How to identify

To identify Union-Based SQL Injection vulnerabilities, look for inputs that are used directly in SQL queries without proper sanitization. Typical indicators include:

1. **Unexpected Behavior:** When inputting SQL syntax (like single quotes, double quotes, or UNION SELECT statements) causes unusual behavior in the application.
2. **Manual Testing:** Try injecting `UNION SELECT NULL` and incrementally increase the number of `NULL` values until the number of columns matches the original query.

```sql
http://somewebsite.com/products.php?id=1 UNION SELECT NULL,NULL
```

3. Sometimes you might be given the source code of the website with php in it. Here is an example of a vulnerable PHP code snippet:

```php
<?php
$id = $_GET['id'];
$query = "SELECT name, price FROM products WHERE id = '$id'";
$result = mysqli_query($conn, $query);
?>
```

## Code/tools/websites

### Code Snippets

The UNION keyword lets you execute one or more additional SELECT queries and append the results to the original query. For example:

```SQL
SELECT a, b FROM table1 UNION SELECT c, d FROM table2
```

We can use this to add additional queries to the one sent from the website.

### Tools

* **SQLMap:** An automated tool for SQL injection and database takeover.
* **Burp Suite:** A web vulnerability scanner with tools for manual testing.
* **Havij:** An automated SQL injection tool.

### Websites

> [Zixem's 10 Challenges](https://www.zixem.altervista.org/SQLi/)
>
> <https://ctflearn.com/challenge/149> (Hard)

## Sample problem

### Problem Statement

You are given access to a web application with a products category filter feature. The task is to identify if the application is vulnerable to Union-Based SQL Injection and extract all usernames and passwords in the database.

[Link to lab](https://portswigger.net/web-security/sql-injection/union-attacks/lab-retrieve-data-from-other-tables)

### Solution

<details>

<summary>Click to reveal the solution</summary>

First and foremost, you can see that when you click on any of the categories, the URL of the page changes. This means that the page sends the category as [params](https://www.semrush.com/blog/url-parameters/) in the URL.

We can try to add random characters at the end of URL to see what happens; doing so gives us a internal server error, indicating that the param's value is directly being used in the code.

Knowing this we can now continue with our SQL injection.

1. Determine the number of columns that are being returned by the query and which columns contain text data. Verify that the query is returning two columns, both of which contain text, using a payload like the following in the category parameter:

```
'+UNION+SELECT+'abc','def'--
```

2. Use the following payload to retrieve the contents of the users table:

```
'+UNION+SELECT+username,+password+FROM+users--
```

3. The list of passwords and usernames will be visible on the web page now.

Note: Zixen website has some great problems on this topic, consider doing them to hone your skill :)

</details>

## References

* [OWASP SQL Injection](https://owasp.org/www-community/attacks/SQL_Injection)
* [PortSwigger Web Security Academy](https://portswigger.net/web-security/sql-injection/union-attacks)
* [SQLMap Documentation](https://sqlmap.org/)

## Conclusion

Union-Based SQL Injection is a powerful technique for extracting data from vulnerable applications. Identifying such vulnerabilities requires understanding the behavior of SQL queries and using appropriate tools and manual testing methods. By practicing with tools like SQLMap and platforms like PortSwigger Web Security Academy, you can enhance your skills in exploiting and securing web applications against SQL injection attacks.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://csyclub-iiitk.gitbook.io/ctf-guide/web-exploitation/intro-to-sqli/union-based-attacks.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
