Introduction

In the era of digitalization, data security has become a paramount concern. Every day, countless businesses and organizations rely on the seamless flow of information between applications and databases. However, this convenience comes with a price – vulnerability to malicious attacks. This blog delves into the intricate world of SQL Injection vulnerabilities (SQLi), offering a comprehensive guide on what SQLi is, its types, real-world examples, detection methods, and the significant impact it can have. By the end, you’ll not only understand the threat but also have a strong foundation for safeguarding your digital assets.

Understanding SQL: The Backbone of Databases

It is Structural Query Language which is used to store, retrieve, and manipulate data in relational databases. User can perform activities by communicating with database and do tasks like create, update, modify and delete.
SQL serves as the universal language for interacting with databases. Its user-friendliness and versatility make it accessible across various platforms. It acts as a bridge between applications and databases, making data retrieval, modification, and insertion seamless.
To put it simply, SQL is the magic wand that developers wave to extract valuable information from databases. With SQL, you can create, read, update, and delete data – the core operations of database interaction.
Let’s understand the meaning of injection , in which it allows an attacker to relay malicious code through an application to another system. This can include compromising both backend systems as well as other clients connected to the vulnerable application.

Unveiling SQL Injection (SQLi)

Now, let’s explore SQL Injection, often abbreviated as SQLi. SQLi is a critical web security vulnerability that empowers attackers to manipulate an application’s database queries. By injecting malicious SQL code, unauthorized access to data, record alteration, and even system compromise become possible.
Imagine you have a website with a search bar. Users input a keyword, and the application fetches relevant data from the database. However, if the application isn’t vigilant, a malicious user can craft input in such a way that it tricks the system into revealing more data than intended.
SQLi is not a new threat; it’s been around since the early days of web development. But it’s still as relevant as ever, if not more so, in today’s interconnected digital world.

SQL utilizes a series of commands for data manipulation within databases

Use of SQLi

SQL utilizes a series of commands for data manipulation within databases. Here are some examples:
•SQL Insert: This command is utilized for incorporating data into database tables.
•SQL Select: It is used to retrieve data from database tables.
•SQL Update: This command is used to alter existing database records.

Type of SQL Injection (SQLi)

SQL injection isn’t a one-size-fits-all exploit. It comes in various forms, each with its unique set of qualities. Let’s explore these different manifestations:

1. First-Order SQLi: This is the most straightforward type of SQLi. It arises when an application directly incorporates user input from an HTTP request into an SQL query without proper validation. In other words, it blindly trusts whatever the user provides.
2. Second-Order SQLi: Also known as stored SQL injection, this occurs when an application stores user input for future use. Later, during a different HTTP request, the application retrieves the stored data and includes it in an SQL query in an insecure manner. This means that the injected code may not have an immediate effect but could cause damage later.
3. In-Band (Error based) SQLi: Attackers exploit error messages produced by the database to gather information about its structure. This is often a clue for hackers to understand the database better and refine their attacks.
4. Union-Based SQLi: This technique leverages the UNION SQL operator to combine select statements, generating a single HTTP response that may contain exploitable data. Think of it as merging two data sets – the attacker’s data and the legitimate data from the database.
5. Inferential (Blind) SQLi: Attackers send data payloads to the server, closely observing its response and behavior to deduce information about the database’s structure. This method is known as blind SQLi because the attacker doesn’t receive explicit error messages but rather infers from the server’s behavior.
6. Boolean-Based SQLi: In this method, an attacker sends an SQL query to the database, prompting the application to return a result based on whether the query is true or false. Depending on the result, the HTTP response is modified or remains unchanged, allowing the attacker to discern the outcome.
7. Time-Based SQLi: Attackers send an SQL query to the database, forcing it to wait for a specified period before responding. By measuring the response time, the attacker can determine whether the query is true or false, ultimately revealing valuable information. It’s a bit like a game of chess – a strategic move followed by waiting to see the opponent’s response.
8. Out-of-Band SQLi: This technique is employed when the attacker cannot use the same channel for both launching the attack and collecting information. It relies on the server’s capability to generate DNS or HTTP requests to transmit data. Essentially, it’s about getting creative with how data flows.

Real-World Example of SQL Injections and Techniques

How To Detect And Examine Database

Detect And Examine Database

Now that you’re acquainted with the various flavours of SQLi, let’s dive into some real-world scenarios and techniques for identifying and exploiting SQLi vulnerabilities.

1.SQL Injection Vulnerability in the WHERE Clause

Explore the website and take note of its content. You’ll find that there are just three products available in the category, as depicted in Figure 1 below.

Home page for products

Figure 1: Home page for products
By manipulating the category parameter to ‘ or 1=1– ‘or 1=1–, an attacker can gain unauthorized access to other products. This technique is an excellent example of first-order SQLi, where the malicious input directly influences the query’s execution

Successfully access to other products using sqli

Figure 2: Successfully access to other products using sqli

2. SQL Injection Allowing Login Bypass

In another scenario, an attacker intercepts the login page, manipulating the password field with an SQLi payload, successfully bypassing the login page. Here, we’re dealing with a situation where the SQL injection occurs on a different page (the login page) but affects the application’s behavior on another page (the main dashboard). This is second-order SQLi in action.

Access the login page using the default username and password, and take note of the response, as illustrated in Figure 3 below.

Login Page Request

Figure 3: Login Page Request

As shown in Figure 4 below, you’ll notice a login page with two input fields: one for the username and another for the password. By manipulating the password field and inserting the SQL injection (SQLi) payload, the login page is effectively circumvented.

Login Bypass Using SQLi

Figure 4: Login Bypass Using SQLi

3. SQL Injection UNION Attack: Counting Columns

Injection UNION Attack Counting Columns

Adjust the category parameter by inserting ‘+UNION+SELECT+NULL– as its value. Take note that this adjustment triggers an error.

Using Union Function to check number of columns

Figure 6: Using Union Function to check number of columns

Alter the category parameter to include an extra column, where you set it as ‘+UNION+SELECT+NULL,NULL—, introducing a null value.

Successfully determined the columns

Figure 7: Successfully determined the columns

Continue with the process of including null values until the error is addressed, and the response showcases expanded content that contains these null values.

4. SQL Injection UNION Attack: Locating a Text-Containing Column

Identify the quantity of columns being retrieved by the query and validate that the query indeed returns three columns. This can be achieved by implementing the provided payload within the category parameter: ‘+UNION+SELECT+NULL,NULL,NULL—.

Using Union function to check text in columns

Figure 8: Using Union function to check text in columns

Replace each null with a lab-provided random value, like ‘+UNION+SELECT+’BmRLnF’,NULL,NULL–. If there’s an error, proceed to the next null and use it.

Successfully columns contains text

Figure 9: Successfully columns contains text

5. SQL Injection UNION Attack: Fetching Data from Different Tables

Determine the number of columns returned by the query and identify which ones hold text. Verify that the query yields two columns, both containing text, using a payload like this in the category parameter: ‘+UNION+SELECT+’abc’,’def’—.

Determining the column with text

Figure 10: Determining the column with text

Utilize the provided payload to access the data within the users table: ‘+UNION+SELECT+username,+password+FROM+users–. Verify that the application’s response indeed includes usernames and passwords.

Retrieve the username Passwords using union

Figure 11: Retrieve the username & Passwords using union

6. SQL Injection UNION Attack: Extracting Multiple Values within a Single Column

Identify the count of columns returned by the query and pinpoint those containing text data. Ensure that the query returns two columns, with only one of them containing text, by employing a payload similar to this in the category parameter: ‘+UNION+SELECT+NULL,’abc’—’.

SQL Injection UNION Attack Counting Columns

Figure 12: Using Union function to determine columns with text

Use the following payload to extract data from the users table: ‘+UNION+SELECT+NULL,username||’~’||password+FROM+users–. Verify that the application’s response shows usernames and passwords.

Username and Password Retrieve

Figure 13: Username and Password Retrieve

7. SQL Injection Attack: Inquiring About Database Type and Version for MySQL and Microsoft

Let’s Find out how many columns the query is returning and identify which of these columns contain text data. Confirm that the query indeed returns two columns, both of which are filled with text, by using a payload similar to this one in the category parameter: ‘+UNION+SELECT+’abc’,’def’#’.

Information of column retrieve

Figure 14: Information of column retrieve

Use the following payload to display the database version:’+UNION+SELECT+@@version,+NULL#

Successfully retrieve the database version

Figure 15: Successfully retrieve the database version

Statistics: The Alarming Reality
SQL injection attacks remain a significant threat in the cybersecurity landscape, constituting 42% of hacker attempts on public-facing web applications. Alarmingly, 21% of organizations continue to exhibit vulnerabilities to SQL threats. One stark example of the potential damage inflicted by SQL injection is the largest known attack in history, where over 1 billion user IDs and passwords were
pilfered. In another instance, hackers successfully exploited SQL injection to steal 130 million card details, highlighting the dire consequences of this attack vector.

Impact of SQL Injection

Understanding the potential consequences of SQL Injection vulnerabilities is essential for realizing the importance of prevention. SQL Injection vulnerabilities can have dire consequences:
Confidentiality: SQL Injection vulnerabilities often compromise data confidentiality. Consider the nightmare scenario of a security breach exposing customer credit card data or confidential medical records.
Authentication: Inadequate SQL commands used for user authentication may enable unauthenticated access without knowledge of passwords. Attackers can essentially impersonate other users within the system.
Authorization: SQL Injection can manipulate authorization data in SQL databases, potentially granting unauthorized access to specific areas or functions of an application.
Integrity: SQL Injection attacks can not only access sensitive data but also alter or delete it. Imagine the chaos an attacker could cause by tampering with critical information.
Availability: SQL injection attacks can disrupt the availability of a system or database by causing denial-of-service (DoS) or distributed denial-of-service (DDoS) attacks. By exploiting vulnerabilities in the SQL queries, attackers can execute resource-intensive queries or inject malicious code that consumes system resources, leading to system slowdowns, crashes, or complete unavailability, thereby affecting legitimate users’ access to the system or database.

SQL Injection Prevention: Best Practices

Given the potential devastation of SQL Injection vulnerabilities, it’s crucial to adopt best practices for prevention:
Input Validation: Always validate and sanitize user inputs to ensure they meet expected criteria. Do not accept inputs that deviate from these standards.

Parameterized Statements and Stored Procedures: Use prepared statements/parameterized and
queries provided by your programming language or framework. This approach ensures that user inputs are treated as data, not executable code.

Escaping User Inputs: If you can’t use prepared statements, employ escaping mechanisms specific to your database technology. Escaping data means encoding it in such a way that it can’t be interpreted as SQL code.
Least Privilege: Follow the principle of least privilege when configuring database user roles. Limit permissions to the minimum necessary for operations, reducing the potential impact of a breach.

Regular Updates: Keep your software, frameworks, and libraries up to date. Developers frequently issue security patches to resolve identified vulnerabilities.
Web Application Firewalls (WAFs): Implement a WAF to filter out malicious requests before they reach your application. These tools can detect and block SQLi attempts in real-time.
Security Audits: Regularly conduct security audits and penetration testing to identify vulnerabilities in your application. Professional testing can help you find weaknesses before malicious actors do.

Conclusion

In an ever-evolving digital landscape, SQL Injection vulnerabilities remain a persistent threat. Understanding the intricacies of SQLi and adopting proactive security measures is paramount. Secure coding practices, robust defences, and a vigilant cybersecurity approach can help safeguard data and fortify the digital realm against these pervasive vulnerabilities.
As technology continues to advance, the battle between defenders and attackers rages on. By equipping yourself with knowledge and staying one step ahead, you can contribute to a safer, more secure digital ecosystem for everyone. Remember, prevention is not just a best practice; it’s a responsibility.

Reference:

10 SQL Injection Attacks Statistics To Know in 2023 (securityescape.com)

https://portswigger.net/web-security/sql-injection

https://www.imperva.com/learn/application-security/sql-injection-sqli/#:~:text=The%20impact%20SQL%20injection%20can,highly%20detrimental%20to%20a%20business

SQL Injection Prevention – OWASP Cheat Sheet Series

https://www.alibabacloud.com/blog/what-is-sql-injection-vulnerability-and-how-to-avoid-it_599990#:~:text=Regular%20Security%20Audits%20and%20Updates,address%20any%20discovered%20vulnerabilities%20promptly