top of page

💉 SQL INJECTION ☠ : Your Database is MINE! 😈

Cyber Morans đŸ’Ș

I'll explain what SQL injection (SQLi) is, walk you through some common examples, explain how to find and exploit 😈 various kinds of SQL injection vulnerabilities, and summarize how to prevent SQL injection 😋

☠SQL Injection (SQLi) ☠ is a type of an injection attack that makes it possible to execute malicious SQL statements. These statements control a database server behind a web application. Attackers can use SQL Injection vulnerabilities to bypass application security measures. They can go around authentication and authorization of a web page or web application and retrieve the content of the entire SQL database. They can also use SQL Injection to add, modify, and delete records in the database. In some situations, an attacker can escalate an SQL injection attack to compromise the underlying server or other back-end infrastructure, or perform a denial-of-service attack 😋

This attack was even used in the year 2100 against the Starship Entreprise in the depths of space đŸ€­ by a very advanced Alien colony -- according to star trek tv show 2019 😂😂

It is very dangerous to a point humans havent solved it in over 100 years into the futuređŸ€­đŸ€­


This vulnerability may affect any website or web application that uses an SQL database such as MySQL, Oracle, SQL Server, or others. Criminals may use it to gain unauthorized access to your sensitive data: customer information, personal data, trade secrets, intellectual property, and more. SQL Injection attacks are one of the oldest, most prevalent, and most dangerous web application vulnerabilities.

 

Impacts of a successful SQL injection attack

A successful SQL injection attack can result in unauthorized access to sensitive data, such as passwords, credit card details, or personal user information. Many high-profile data breaches in recent years have been the result of SQL injection attacks, leading to reputational damage and regulatory fines. In some cases, an attacker can obtain a persistent backdoor into an organization's systems, leading to a long-term compromise that can go unnoticed for an extended period.

 

SQL injection examples 💉💉

There are a wide variety of SQL injection vulnerabilities, attacks, and techniques, which arise in different situations. Some common SQL injection techniques and examples include:

👉 1. Retrieving hidden data 😈

where I can modify an SQL query to return additional results.

Consider a shopping application like JUMIA or JIJI that displays products in different categories. When the user clicks on the Toys category, their browser requests the URL:

https://website.com/products?category=Toys

This causes the application to make an SQL query to retrieve details of the relevant products from the database:

SELECT * FROM products WHERE category = 'Toys' AND released = 1

This SQL query asks the database to return:

  • all details (*)

  • from the products table

  • where the category is Toys

  • and released is 1.

The restriction released = 1 is being used to hide products that are not released. For unreleased products, presumably released = 0.

The application doesn't implement any defenses against SQL injection attacks, so I can construct an attack like 😋:

https://website.com/products?category=Toys'--

This results in the SQL query:

SELECT * FROM products WHERE category = 'Toys'--' AND released = 1

The key thing here is that the double-dash sequence -- is a comment indicator in SQL, and means that the rest of the query is interpreted as a comment. This effectively removes the remainder of the query, so it no longer includes AND released = 1. This means that all products are displayed, including unreleased products.

Going further, I can cause the application to display all the products in any category, including categories that I don't know about:

https://website.com/products?category=Toys'+OR+1=1--

This results in the SQL query:

SELECT * FROM products WHERE category = 'Toys' OR 1=1--' AND released = 1

The modified query will return all items where either the category is Toys, or 1 is equal to 1. Since 1=1 is always true, the query will return all items.

👉 2. Subverting application logic 😈

where I can change a query to interfere with the application's logic.

Consider an application like Equity Bank E-banking Portal that lets users log in with a username and password. If a user submits the username chip and the password 12345678, the application checks the credentials by performing the following SQL query:

SELECT * FROM users WHERE username = 'chip' AND password = '12345678'

If the query returns the details of a user, then the login is successful. Else it failed.

Here, I can log in as any user without a password simply by using the SQL comment sequence -- to remove the password check from the WHERE clause of the query.

por eJemplo,

submitting the username admin'-- and a blank password results in the following query:

SELECT * FROM users WHERE username = 'admin'--' AND password = ''
This query returns the user whose username is 'admin' and successfully 😈 logs me in as that user 😋

👉 3. UNION attacks 😈

where I can retrieve data from different database tables. where the results of an SQL query are returned within the application's responses, an attacker can leverage an SQL injection vulnerability to retrieve data from other tables within the database. This is done using the UNION keyword, which lets you execute an additional SELECT query and append the results to the original query.

Por ejemplo, an application executes the following query containing the user input "Toys":

SELECT name, description FROM products WHERE category = 'Toys'

then I can submit the input:

' UNION SELECT username, password FROM users--

This will cause the application to return all usernames and passwords along with the names and descriptions of products 😋

👉 4. Examining the database 😈

where I can extract information about the version and structure of the database. it is generally useful to obtain some information about the database itself. This information can often pave the way for further exploitation.

I can query the version details for the database. The way that this is done depends on the database type, so you can infer the database type from whichever technique works. For example, on Oracle I can execute:

SELECT * FROM v$version

I can also determine what database tables exist, and which columns they contain.

Por ejemplo, on most databases you can execute the following query to list the tables:

SELECT * FROM information_schema.tables

👉 5. Blind SQL injection 😈

Where the results of a query I control are not returned in the application's responses. Many instances of SQL injection are blind vulnerabilities. This means that the application does not return the results of the SQL query or the details of any database errors within its responses. Blind vulnerabilities can still be exploited to access unauthorized data, but the techniques involved are generally more complicated and difficult to perform.

Depending on the nature of the vulnerability and the database involved, the following techniques can be used to exploit blind SQL injection vulnerabilities:

  • change the logic of the query to trigger a detectable difference in the application's response depending on the truth of a single condition. This might involve injecting a new condition into some Boolean logic, or conditionally triggering an error such as a divide-by-zero.

  • conditionally trigger a time delay in the processing of the query, allowing you to infer the truth of the condition based on the time that the application takes to respond.

  • trigger an out-of-band network interaction, using OAST techniques. This technique is extremely powerful and works in situations where the other techniques do not. Often, you can directly exfiltrate data via the out-of-band channel, for example by placing the data into a DNS lookup for a domain that you control.

 

How to detect SQL injection vulnerabilities

The majority of SQL injection vulnerabilities can be found quickly and reliably using Burp Suite's web vulnerability scanner.

SQL injection can be detected manually by using a systematic set of tests against every entry point in the application. This typically involves:

  • 👉 Submitting the single quote character ' and looking for errors or other anomalies.

  • 👉 Submitting some SQL-specific syntax that evaluates to the original value of the entry point, and to a different value, and looking for systematic differences in the resulting application responses.

  • 👉 Submitting Boolean conditions such as OR 1=1 and OR 1=2, and looking for differences in the application's responses.

  • 👉 Submitting payloads designed to trigger time delays when executed within an SQL query, and looking for differences in the time taken to respond.

 

SQL injection in parts of a query

Most SQL injection vulnerabilities arise within the WHERE clause of a SELECT query. This type of SQL injection is generally well-understood by experienced testers.

But SQL injection vulnerabilities can in principle occur at any location within the query, and within different query types. The most common other locations where SQL injection arises are:

  • 👉 UPDATE statements, within the updated values or the WHERE clause.

  • 👉 INSERT statements, within the inserted values.

  • 👉 SELECT statements, within the table or column name.

  • 👉 SELECT statements, within the ORDER BY clause.

SQL injection in specific contexts

so far, I've used the query string to inject malicious SQL payload. However, it's important to note that you can perform SQL injection attacks using any controllable input that is processed as a SQL query by the application. For example, some websites take input in JSON or XML format and use this to query the database.

These different formats may even provide alternative ways for you to obfuscate attacks that are otherwise blocked due to WAFs and other defense mechanisms. Weak implementations often just look for common SQL injection keywords within the request, so you may be able to bypass these filters by simply encoding or escaping characters in the prohibited keywords.

Por ejemplo, the following XML-based SQL injection uses an XML escape sequence to encode the S character in SELECT:

<stockCheck>
     <productId>
            ' &#x53;ELECT * FROM information_schema.tables--
    </productId>
      <storeId>         
      123     
      </storeId> 
</stockCheck>

This will be decoded server-side before being passed to the SQL interpreter.


 

Second-order SQL injection

First-order SQL injection arises where the application takes user input from an HTTP request and, in the course of processing that request, incorporates the input into an SQL query in an unsafe way.

In second-order SQL injection also known as stored SQL injection, the application takes user input from an HTTP request and stores it for future use. This is usually done by placing the input into a database, but no vulnerability arises at the point where the data is stored. Later, when handling a different HTTP request, the application retrieves the stored data and incorporates it into an SQL query in an unsafe way 😋


Database-specific factors

Some core features of the SQL language are implemented in the same way across popular database platforms, and so many ways of detecting and exploiting SQL injection vulnerabilities work identically on different types of database.

However, there are also many differences between common databases. These mean that some techniques for detecting and exploiting SQL injection work differently on different platforms. For example:

  • Syntax for string concatenation.

  • Comments.

  • Batched (or stacked) queries.

  • Platform-specific APIs.

  • Error messages.

 

How to prevent SQL injection


👉 1. Most instances of SQL injection can be prevented by using parameterized queries (also known as prepared statements) instead of string concatenation within the query.

The following code is vulnerable to SQL injection because the user input is concatenated directly into the query:

String query = "SELECT * FROM products WHERE category = '"+ input + "'"; Statement statement = connection.createStatement(); ResultSet resultSet = statement.executeQuery(query);

This code can be easily rewritten in a way that prevents the user input from interfering with the query structure:

PreparedStatement statement = connection.prepareStatement("SELECT * FROM products WHERE category = ?"); statement.setString(1, input); ResultSet resultSet = statement.executeQuery();

Parameterized queries can be used for any situation where untrusted input appears as data within the query, including the WHERE clause and values in an INSERT or UPDATE statement. They can't be used to handle untrusted input in other parts of the query, such as table or column names, or the ORDER BY clause. Application functionality that places untrusted data into those parts of the query will need to take a different approach, such as white-listing permitted input values, or using different logic to deliver the required behavior.

👉 2. Use whitelists, not blacklists

Don’t filter user input based on blacklists. A clever attacker will almost always find a way to circumvent your blacklist. If possible, verify and filter user input using strict whitelists only.

👉 3. Adopt the latest technologies

Older web development technologies don’t have SQLi protection. Use the latest version of the development environment and language and the latest technologies associated with that environment/language. For example, in PHP use PDO instead of MySQLi.

👉 4. Scan regularly

SQL Injections may be introduced by your developers or through external libraries, modules and software. You should regularly scan your web applications using a web vulnerability scanner such as Burpsuit

 

Conclusion

Subscribe to receive notifications of similar posts 😋 where we will be reverse engineering malware and the technical aspect of vulnerabilities as well as how an attacker may use this vulnerability as an attack vector and other Infosec stuff...😋


Thank you for your time, Like and leave a comment/review and as always, stay awesome! 😋👊 đŸ’Ș

101 views0 comments

Recent Posts

See All
Post: Blog2_Post
bottom of page