> For the complete documentation index, see [llms.txt](https://davidjosearaujo.gitbook.io/notes-mcs/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://davidjosearaujo.gitbook.io/notes-mcs/analysis-and-exploration-of-vulnerabilities/injection/using-sql.md).

# Using SQL

Form provides two fields: **username** and **password**.

* Both are controlled by external entities (users).

Objective:

* Check if the username and password provided exist in the database.
* Obtain the user data if it exists, and move to authorization phase.
* Otherwise, do not authenticate and provide an error.

Vulnerable validation code (PHP):

```sql
$result = mysql_query(“SELECT * FROM Users WHERE(username=‘$username’ AND password=‘$password’);”);
```

## Exploiting SQLi

```sql
$result = mysql_query(“ SELECT * FROM Users WHERE(username=‘john’ AND password=‘abc’);”);
```

It will fail because the \<username,password> don’t match and no result is provided.

```sql
$result = mysql_query(“ SELECT * FROM Users WHERE(username=‘john’ or 1=1); -- ’ AND password=‘abc’);”);
```

It will be successful because 1=1 is always true.

* The username is ignored because the second part is always true.
* The remaining of the query is ignored due to the comment.

```sql
$result = mysql_query(“ SELECT * FROM Users WHERE(username=‘’ or 1=1);DROP TABLE Users; --’ AND password=‘a’);”);
```

Two queries may be executed:

* SELECT which returns all users.
* DROP TABLE Users, which effectively deletes the Table.
