# SQL Truncation

It's an attack that **no longer works** in the latest MySQL versions.

{% embed url="<http://resources.infosecinstitute.com/sql-truncation-attack/>" %}

## Overview

**Prerequisites**:

* MySQL database backend

A SQL Truncation attack takes advantage of two features in MySQL to subvert application logic. These features are:

1. If the length of a VARCHAR is exceeded, then the rest of it is simply cut off (truncated) - **this is no longer a feature of MySQL**.
2. By default, MySQL ignores trailing whitespace when making comparisons ([MySQL Loose Comparisons)](https://heinosass.gitbook.io/leet-sheet/server-attacks/loose-comparisons#mysql)

*Note: This attack doesn't work in newer MySQL versions and other databases like PostgreSQL because an error is thrown when the length of a VARCHAR is exceeded.*

## Attack Walkthrough

Let's say there's a website with a MySQL backend and a users table, where the username is of type `VARCHAR(20)`. Let's also say that there is an admin account

Register the following user:

* username: `admin (lots of spaces in between)And then whatever`
* password: `mypassword123`

It produces the following SQL query:

```
INSERT INTO users (name, password) VALUES ('admin                         (lots of spaces in between)And then whatever', 'mypassword123');
```

Because of SQL truncation to 20 characters, the above is effectively the same as:

```
INSERT INTO users (name, password) VALUES ('admin               ', 'mypassword123');
```

When you later try to log in with `admin:mypassword123`, then that produce the following query:

```
SELECT * FROM users WHERE username='admin               ' AND password='mypassword123' 
```

Because of [MySQL loose comparisons](https://heinosass.gitbook.io/leet-sheet/server-attacks/loose-comparisons#mysql), `admin` is the same as `admin` and you can log in as the admin user.


---

# Agent Instructions: 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://heinosass.gitbook.io/leet-sheet/web-app-hacking/interesting-outdated-attacks/sql-truncation.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.
