What is SQL Injection (SQLi)?

SQL Injections are critical attack vectors in which a web application directly includes unsanitized user-provided data in SQL queries.

The frameworks we use today to develop web applications have preventative mechanisms in place to protect against SQL Injection attacks. However, we still come across SQL injection vulnerabilities because sometimes raw SQL queries are used, sometimes the framework has an inherent SQL injection vulnerability, or the framework is not used properly.

Types of SQL Injections

There are 3 types of SQL Injection. These are:

  1. In-band SQLi (Classic SQLi): When an SQL query is sent and responded to on the same channel, we call this in-band SQLi. This is easier for attackers to exploit than other categories of SQLi.
  2. Inferential SQLi (Blind SQLi): SQL queries that receive a response that cannot be seen are called Inferential SQLi. They are also called "Blind SQLi" because the response cannot be seen.
  3. Out-of-band SQLi: If the response to an SQL query is communicated through another channel, this type of SQLi is called "out-of-band SQLi". For example, if the attacker receives replies to the SQL queries via DNS, this is called out-of-band SQLi.

How Does SQL Injection Work?

Today, most standard web applications receive data from a user and use that data to display specific content. The login page is where most SQL injection attacks occur. Let's look at how SQL injections work through an example.

A user is usually expected to enter their username and password on the login page. Then, on the other side, the web application will use this username and password information to create an SQL query like the one below:

SELECT * FROM users WHERE username = 'USERNAME’ AND password = 'USER_PASSWORD'

The meaning of this SQL query is "Bring me all the information about the user from the user's table whose name is USERNAME and whose password is USER_PASSWORD". If the web application finds a matching user, it will authenticate the user, if it cannot find a user after executing the query, the login will fail.

Let's say your username is "john" and your password is "supersecretpassword". When you enter this information and click the 'Login' button, the SQL query shown below will be queried and you will be able to log in because a match was found after the SQL query.

SELECT * FROM users WHERE username = ‘john’ AND password = 'supersecretpassword'

So what if we do not use this system as it was designed and we put an apostrophe (') in the username field? The SQL query will look like this and the error will be excluded from the database because the query was incorrect.

SELECT * FROM users WHERE username = ‘john’’ AND password = 'supersecretpassword'