# SQL Injection

## Summary


SQL (Structured Query Language) is a language used to create, update and access data in a database. By carefully crafting SQL commands, a hacker can intentionally cause the application to fail, delete data, steal data or gain unauthorized access. This is what we call SQL injection or **SQL Injection Attack (SQLIA)**. SQL itself is a highly flexible language, which creates opportunities for hackers to acquire sensitive information such as credit card details, user passwords or user IDs. .

There are various methods and tools to attack an SQL database. This article gives an overview of SQL injection attacks and what hackers aim to achieve. We also cover the types and techniques of SQL injection attacks. We note some possible preventive measures towards more secure database-driven websites.

## Discussion

### Why do we need to worry about SQL injection?

CWE (Common Weakness Enumeration) is a system where all weaknesses and vulnerabilities are categorised concerning a particular system architecture, code, hardware or software. **CWE-89: SQL Injection** notes that any data-rich software is vulnerable to attack when user information is stored in an SQL-based database. An attack can lead to loss of data confidentiality, access control and data integrity. 

Many widely adopted databases are based on SQL including Oracle, MySQL, Microsoft SQL Server, PostgreSQL and SQLite. In April 2022, these were in the first, second, third, fourth and tenth positions respectively. SQLIA techniques may slightly differ across databases but all are vulnerable if not properly secured. 

In 2021, the Open Web Security Project (OWASP) tested 94% of applications under study for injection attacks. They found that 19% had at least one of instance of a vulnerability type (called incidence rate). Injection category was the third-most serious risk and includes 33 CWEs. On a ten-point scale, 7+ values for both exploit and impact shows the threat of SQLIA. In the years 2004/2007/2010/2013/2017, injection attacks were in positions 6/2/1/1/1 respectively.  


### Could you introduce SQL injection with a few examples?

The figure illustrates a few examples, each affecting the application in a different way. In all cases, inputs submitted by hackers are directly used to form queries without proper validation.

The first example possibly represents a user sign-up form where the user is expected to enter first name and last name. Instead, a hacker enters first name that includes a single quote. Since single quote is normally used by developers to enclose values, the extra quote in input causes execution error. The application will not respond correctly to the user. 

In the second example, the hacker submits the string `name' OR 'a'='a` for item name. In the resulting command, `'a'='a'` will match and return all records to the hacker. This is a serious data breach. 

In the third example, using semi-colons, we execute multiple commands, called batched queries. Comment syntax `--` is used to ignore characters after the delete command. This attack results in a serious data loss. 


### What's the nature of SQL injection attacks?

SQLIA can take many forms: identifying injectable parameters, performing database fingerprinting, determining database schema (table or column names, datatypes), adding/modifying/extracting data, performing denial of service (locking or dropping rows/tables/databases), evading detection, bypassing authentication, executing remote commands, performing privilege escalation, etc. In general, a hacker tries to gather information about the database, uses that information to handcraft attacking commands, and finally execute those commands. 

These attacks can be placed into four categories: 

    + **SQL Manipulation**: Modify SQL statements possibly by changing the `WHERE` clause.
    + **Code Injection**: Insert extra SQL statements after the exploitable SQL statement. This is possible on databases that support multiple SQL requests. Semi-colons typically separate multiple queries. `UNION` statements can be used provided the hacker knows the exact number columns and their data types returned by the exploited statement.
    + **Function Call Injection**: Insert function calls within the exploited SQL statement. This can not only manipulate data but also make operating system calls.
    + **Buffer Overflows**: A product of using a function call injection. Hacker exploits a weakness often found on unpatched servers.

### What are the different types of SQL injection attacks?

Different types of SQLIA have been documented:  

    + **Boolean-based**: Aka tautology attack. The use of `OR 2 = 2` within the `WHERE` clause makes other conditions in the clause redundant.
    + **UNION-based**: The `UNION` statements combines the results of separate queries. `' UNION SELECT username, password FROM users--` is an example injection. Where multiple columns have be retrieved within fewer columns, columns can be concatenated.
    + **Error-based**: Error messages can give information about database type. For example, a query that fails due to a `SUBSTRING` function call suggests that it's probably an Oracle database where the equivalent function is named `SUBSTR`.
    + **Batch Queries**: Aka piggyback attack. For example on SQL-Server 2005, `; INSERT INTO users VALUES (‘Abubakar’, ‘1234’);#` ends the original statement, appends another statement and comments out any trailing characters with `#` character.
    + **LIKE-based**: Similar to tautology attack but based on pattern matching using `LIKE` and wildcard operator `%`. An example is `OR username LIKE 'S%'`.
    + **Stored Procedure**: Hacker executes built-in stored procedures using malicious SQL code injections.

### What's a blind SQL injection?

A hacker typically submits an SQL query and gathers information from the response. Information can come back in the same channel (in-band) or in a separate channel such as email (out-of-band). But in blind SQL injection (aka inferential attack) the hacker obtains useful information even when no data or error message is returned to the hacker. The hacker does this by observing the behaviour. Blind injections can be Boolean-based or time-based.  

With **Boolean-based attacks**, the hacker sees that true and false evaluations result in different behaviour. He then exploits this, perhaps over many queries, to eventually learn sensitive information such as the administrator's password. 

With **time-based attacks**, the hacker can insert time delays into SQL command execution. These delays can be conditional or unconditional. Due to synchronous processing, these delays affect the HTTP response to the client. Based on the query, the response time gives the hacker clues to what's going on. For example, an observed delay can confirm that an injected condition was true; or adding `SLEEP(1)` to the `WHERE` clause can inform the number of matching records. 


### What's a second-order SQL injection?

Second-order SQL injection occurs when the injected inputs don't do immediate damage. They're simply stored in the database as data. When later retrieved, they end up causing malicious executions. Second-order injections are in a way sophisticated because they bypass prevention techniques that're employed when inputs are validated. However, similar stringent validation may be lacking when data is retrieved from the database.  

The figure shows an example in which a hacker creates a user account with name that hides within it an update command. The system may at best check for length, valid characters and uniqueness of username. But at a later time, when the hacker logs in with this handcrafted username, it executes the update command and changes the administrator password. This effectively gives the hacker much more power to cause serious damage. 

Second-order injections can be used to create tables or functions that can be exploited later when those constructs are triggered. Shared search criteria, website statistics and customer services are some app features that may be exploited to achieve second-order injections. 


### What evasion techniques do hackers use for advanced SQLIA?

There are Intrusion Detection Systems (IDSs) and tools to detect and protect against common injections. Hackers have therefore evolved techniques to achieve more sophisticated attacks that basic systems may not detect: 

    + **Encoding**: Instead of using plain ASCII characters, injections are URL-encoded. Alternatively, UTF-8 or hexadecimal encoding may be used. For example, `5' OR '5'='5` is encoded as `%35%27%20%4F%52%20%27%35%27%3D%27%35`; or `admin` is encoded as `char(97,100,109,105,110)`.
    + **White-spacing**: Whitespaces are not significant in SQL. Hackers therefore omit or insert extra whitespaces that may include line feeds, carriage returns and tabs. For example, `OR '5'='5'`, `OR '5'='5'` and `OR'5'='5'` are equivalent.
    + **Comment**: Using multiline comments, attackers can subvert detection techniques that attempt to match signatures. For example, a `SELECT` query can be written as `SELE/&ast;&ast;/CT` or `/&ast;&ast;/ SELECT/&ast;&ast;/`.
    + **Capitalization**: Where the database is configured to be case-insensitive, `AND` is same as `anD`.
    + **Variation**: Techniques in this group include concatenation, variables, and conversions. For example, `'UN'||'ION` is same as `UNION`. A statement is split into multiple variables and combined later for execution.

### Which tools help in detection and prevention of SQLIA?

The figure show tools to either detect or prevent SQLIA, and their handling of different attack types. A 2017 study noted that SQLCheck, SQLIPA, DB IDS, AMNESIA, SQLDOM and WebSSARI all achieve better than 90% protection. 

SQLrand is a proxy server between the web server and the database server. It receives randomized SQL from application and submits standard SQL to the database. All user inputs are treated as non-keywords. AMNESIA does static analysis of application code, constructs a model of valid queries and validates queries at runtime. WebSARRI is another tool that combines static analysis and runtime inspection. 

SQLDOM creates strongly-typed classes based on the database schema. These classes are used to generate SQL statements. It’s an object model as it's used with the help of object-oriented languages. SQLCheck focuses on grammar and policy that are created and stored on the web server. User inputs are augmented with metacharacters and then passed to the checker for validation. 


### What should developers do to protect against SQLIA?

While a production system may employ tools to detect and prevent SQLIA, there are some best practices that can developers can adopt to mitigate the possibility of SQLIA in the first place. Give users only limited database privileges. Application code probably never needs to drop or truncate tables. Configure web server properly so that verbose error messages are not shown to users. 

Never trust user inputs. Don't rely only on client-side validation since they can be bypassed with curl, postman or similar tools. Do server-side validation. Adopt safe coding practices. Put quotes around input strings. Replace single quote with two single quotes. Where numbers are expected, check that indeed only digits are present. 

Even better is to avoid using raw SQL statements formed from raw input strings. Use custom stored procedures and pass user inputs as parameters into these procedures. Many SQL databases support the `PREPARE` statement and pass in user inputs as parameters to such a statement. This avoids the unsafe practice of concatenating raw inputs to form queries. 

Read OWASP SQL Injection Prevention Cheat Sheet and OWASP Query Parameterization Cheat Sheet. 

## Milestones

Dec  
1998

Jeff Forristal (alias rain.forest.puppy) writes about SQL injection in the Phrack magazine. He notes that MS SQL Server 6.5 allows execution of **batch commands** and gives many examples to exploit this. He concludes,

> Don't assume user's input is ok for SQL queries.

2003

As more and more web applications emerge, there's a need to find loopholes that may endanger the user's security. In this context, *WAVES (Web Application Vulnerability and Error Scanner)* is first introduced. WAVES is a project developed by Hunag et al. to create a platform to assess web application security based on vulnerabilities such as SQL injection and cross-site scripting. 

2008

A hacker obtains access to 100 million debit and credit cards by hacking into the Heartland Payment System. As a result, Heartland pays around $140 million in fines and penalties. 

2011

Multiple attacks targeting Sony through Sony Pictures, Sony Music Japan and Sony Playstation Network occur. Personal information of 100 million users is leaked, causing a loss of $171 million. The attacks on Sony Pictures and Sony Music Japan used SQL injection. 

Mar  
2011

As many as 47 MySQL databases on Apache web server get hacked. Hackers publicly post usernames, database schemas and passwords that they gathered using **blind SQL injection**. The breach includes hashed passwords of administrative accounts of webmaster, WordPress, root and forums. 

2013

**OWASP Top 10** is published stating how injection attacks take top spot among all types of attacks. This top spot is maintained in a subsequent survey in 2017. The report notes that injection attacks are easy while the impact is severe. 

2017

In a survey paper, Alwan and Younis mention two recent types of SQLIA called Fast Flux SQLIA and Compounded SQLIA. The latter is a combination of many attack techniques including DDoS attack, DNS hijacking, Cross-Site Scripting (XSS), and more. 

Jun  
2019

Lewis of NCC Group shares a proof-of-concept of using **Machine Learning to detect SQLIA** vulnerabilities. They use real-world vulnerability data (though limited in size) and limit their study to only MySQL. They use SVM-Multiclass. In 2021, Erdodi et al. propose using Reinforcement Learning instead with Markov decision process as the model for SQLIA. These are just two examples to illustrate the use of machine learning in SQLIA.

2020

Abikoye et al. use the **Knuth-Morris-Pratt (KMP) string matching algorithm** to detect and prevent SQLIA. Based on syntactic analysis of various types of attacks, parse trees are designed. KMP algorithm is then used to compare user inputs against the known attack patterns.