Meritshot Tutorials

  1. Home
  2. »
  3. SQL Injection in Cyber Security

Cyber Security Tutorial

SQL Injection

SQL injection (SQLi) is a web security vulnerability that allows an attacker to interfere with the queries that an application makes to its database. This can allow an attacker to view data that they are not normally able to retrieve. This might include data that belongs to other users, or any other data that the application can access. In many cases, an attacker can modify or delete this data, causing persistent changes to the application’s content or behavior.

In some situations, an attacker can escalate a SQL injection attack to compromise the underlying server or other back-end infrastructure. It can also enable them to perform denial-of-service attacks.

What is the impact of a successful SQL injection attack?

A successful SQL injection attack can lead to unauthorized access to sensitive information, including:

  • Passwords
  • Credit card details
  • Personal user data

Over the years, SQL injection has been a key factor in numerous high-profile data breaches, causing significant reputational harm and hefty regulatory penalties. In some cases, attackers can establish a persistent backdoor into an organization’s systems, resulting in long-term compromises that may remain undetected for extended periods.

How to detect SQL injection vulnerabilities

You can detect SQL injection manually using a systematic set of tests against every entry point in the application. To do this, you would typically submit:

  • The single quote character ‘ and look for errors or other
  • Some SQL-specific syntax that evaluates to the base (original) value of the entry point, and to a different value, and look for systematic differences in the application responses.
  • Boolean conditions such as OR 1=1 and OR 1=2, and look for differences in the application’s responses.
  • Payloads designed to trigger time delays when executed within a SQL query, and look for differences in the time taken to respond.
  • OAST payloads designed to trigger an out-of-band network interaction when executed within a SQL query, and monitor any resulting interactions.

Alternatively, you can find the majority of SQL injection vulnerabilities quickly and reliably using Burp Scanner.

SQL injection in different parts of the query

Most SQL injection vulnerabilities occur within the WHERE clause of a SELECT query. Most experienced testers are familiar with this type of SQL injection.

However, SQL injection vulnerabilities can occur at any location within the query, and within different query types. Some other common locations where SQL injection arises are:

  • In UPDATE statements, within the updated values or the WHERE
  • In INSERT statements, within the inserted
  • In SELECT statements, within the table or column
  • In SELECT statements, within the ORDER BY

SQL injection examples

SQL injection vulnerabilities, attacks, and techniques can occur in various scenarios. Some common examples include:

Retrieving hidden data: Modifying a SQL query to display additional results that are typically concealed.

Altering application logic: Changing a query to disrupt the application’s intended behavior.

UNION attacks: Using the UNION operator to extract data from other tables in the database.

Blind SQL injection: Executing queries where the application does not directly display query results but provides indirect clues through behavior or output.

How does a SQL injection attack work?

While there are different types of SQL injection (SQLi), the fundamental vulnerability remains the same: a SQL query field intended to accept specific data, like a number, is instead fed unexpected input, such as a command. This input, when executed, bypasses its intended constraints, enabling potentially harmful actions. These query fields are often populated using data entered into forms on a webpage.

Here’s a simple comparison between normal and malicious SQL statements:

Normal Query:

In this normal SQL query, the studentId string is passed into a SQL statement. The goal is to look through the list of students for a student that matches the studentId entered. Once found, that student’s record will be returned. Put simply, the command says “go find this user and give me their data”.

The code might look something like this:

studentId = getRequestString(“studentId”);

lookupStudent   = “SELECT * FROM students WHERE studentId = ” + studentId

If a student enters a student ID of 117 inside a webpage form labeled ‘Please enter your student ID number’

cyber-web

the resulting SQL query will look like:

SELECT * FROM students WHERE studentId = 117;

This command will return the record for the particular student with a studentId, which is what the developer who wrote the API expects to have happened.

SQL Injection query:

In this example, an attacker instead enters a SQL command or conditional logic into the input field, he enters a student ID number of:

Where normally the query would search the database table for the matching ID, it now looks for an ID or tests to see if 1 is equal to 1. As you might expect, the statement is always true for every student in the column, and as a result, the database will return all data from the students table back to the attacker making the query.

SELECT * FROM students WHERE studentId = 117 OR 1=1;

SQLi works by targeting a vulnerable Application Programming Interface or API. An API in this case is the software interface through which a server receives and responds to requests.

Commonly used tools exist that allow a malicious actor to automatically search through a website looking for forms, and then attempt to input various SQL queries that may generate a response that the website’s software developers did not intend in order to exploit the database.

SQL injections are easy to implement, and interestingly, also fairly easy to prevent given the proper development practices. The reality is more murky, as tight deadlines, inexperienced developers, and legacy code often result in variable code quality and security practices. A single vulnerable field on any form or API

endpoint across a website that has access to a database may be sufficient to expose a vulnerability.

How to Prevent SQL Injection Attacks

Several strategies can help minimize the risk of a SQL injection-based data breach. Best practices involve using multiple layers of protection. Below are some of the most effective methods:

1.  Use Prepared Statements (with Parameterized Queries)

This approach ensures that database inputs are sanitized by requiring developers to define all SQL code in advance and then supply parameters separately. By explicitly limiting the scope of input data, it prevents malicious commands from being executed. Prepared statements distinguish between data input and executable code, regardless of the input type. Many object-relational mapping (ORM) libraries include features to automatically sanitize inputs.

2.  Escape User-Supplied Input

Certain characters and keywords in SQL, such as `*` (wildcard) or `OR` (logical operator), have special meanings. If users enter these accidentally or intentionally in input fields, it can lead to vulnerabilities. Escaping user input ensures that special characters are treated as literal text rather than commands, protecting the database from parsing them incorrectly.

3.  Use Stored Procedures

While not a standalone solution, stored procedures can reduce SQL injection risks when properly configured. These procedures limit database permissions, ensuring that even if application code is vulnerable, the attacker cannot manipulate unrelated database tables. Stored procedures can also validate input types, rejecting data that doesn’t match the expected format. However, dynamic SQL queries within stored procedures should generally be avoided.

4.  Enforce Least Privilege

The principle of least privilege ensures that database accounts have only the minimum permissions necessary to perform their functions. For example, administrative accounts should never execute SQL commands originating from unverified API calls. Limiting permissions narrows the potential impact of SQL injection attacks, especially for dynamic SQL queries.

By combining these techniques, organizations can significantly reduce their exposure to SQL injection vulnerabilities and better protect their data.