Sunday, June 24, 2012

SQL injection prevention

This was a research project for software security coursework which I am sharing here on my blog.

SQL injection vulnerability was reported as a top cybersecurity issue in 2010 and is considered to be accounting for 10% of total cybersecurity vulnerabilities since 2002. It is a known fact that using parameterized queries can mitigate SQL injection vulnerabilities to a large extent. This paper shows the underlying practical issues programmers encounter when using parameterized queries. It also shows how a plugin tool inside the developer’s integrated development environment (IDE) could help programmers in generating parameterized queries. Further, the usefulness and practicality of this helping tool are discussed.


SQL injection vulnerability (SQLIV) accounts for over 20% of input validation issues and 10% of the overall cybersecurity issues between 2002 and 2007. Further, it was reported as the second top cybersecurity vulnerability of the year 2010.  SQL injection vulnerability can lead to theft of confidential data, loss of money, loss of critical data, and affect the reputation of organizations.

Structured Query Language (SQL) is widely used as a standard method to interact with the relational databases from a webpage.  An SQL statement can call the database managing program, typically a database server to return a particular result set from the database table or to update the table. Typically SQL statements are not compiled until the request is made by the web page under execution. This is usually because the query would likely depend on user requests and may contain a user-entered input. An SQL injection happens when a malicious user persuades the user input in such a way that the developer-defined SQL query is modified undesirably. This is done by inserting code into the data part of the SQL query maliciously.

Several SQLIV mitigating mechanisms exist, of which the most effective one is the usage of a parameterized query, which is also known as prepared statements. Parameterized queries force the developer to define the code portion of the SQL query first and then clearly define the data portion of the query. In this way, the SQL compiler can safely distinguish between the code and the data portion of a query. It is interesting to note that parameterized queries were introduced a long period back; however, by contrast with the frequent occurrences of SQL injection attacks, we can conclude that they were not used by web developers, at least in some cases where attacks happened.

In this paper, we study the difficulties encountered in using parameterized queries. We developed a plugin tool namely SQLSecuritytool for Microsoft’s visual studio 2010 web development IDE that could aid web developers in ensuring the safety of SQL queries they use in server-side scripting. The findings, the practicality, and usefulness of this security tool are described in this paper. Section II discusses a brief background to understand this paper. Section III goes through the related work in mitigating SQL injection vulnerability. Section IV analyzes problems faced by web developers in using parameterized queries. Section V describes the tool we developed for replacing general SQL queries with parameterized queries. Finally, the security benefits and conclusion are discussed subsequently.


This section gives some background about SQL Structure, SQL injection attacks, and parameterized queries.

SQL statement

An SQL statement defines the operations performed or requested to the database and is usually defined by a database analyst in consultation with the web developer. An example SQL query used in login pages is described below:

Select password FROM usernames_table WHERE username = ‘name’

The code portion of the above statement is shown below.

Select password FROM usernames_table WHERE username =

The data portion of the SQL query is ‘name’. Typically the data portion is known only at runtime. Therefore web developers substitute that field with a variable name. For example, in the above query would be defined by the web developer as shown in figure 1.

Figure 1.   Typical SQL query in a webpage server-side script

Password hashes obtained from the database are used to validate the username in this case.  Typically the database is connected by using the driver provided. In this case, Oracle client driver for is used which requires importing a dynamic link library (DLL) provided by Oracle company to the project.

SQL Injection Attack

An SQL injection attack happens when the developer fails to properly define his program in such a way so that there is always a desired separation between code and the data portion for any user inputs at runtime. Or by using standard definitions, an SQLIV is caused by dynamic SQL statement code combined with inadequately-verified input, which allows the input to change the structure and logic of an SQL statement.  For example, a user input “111’ OR true#“ would create the following query which would retrieve all passwords.

SELECT password FROM usernames_table WHERE username = ‘name’ OR true#’

If the web application is expected to display the results in a table then all the password hashes will be displayed to the attacker. In addition to this example, several other SQL injection methods exist. Fortunately, all of them work by mixing the user input with actual SQL code.

Parameterized query

Parameterized queries are SQL statements that take a static structure unaltered at runtime. It defines the user input as parameters expected at the runtime. Therefore it clearly makes a distinction between the code and the data portion of the SQL query. The query described in figure 1 can be changed to a parameterized query as figure 2 shows.

Figure 2.   Typical parameterized SQL query in a server-side script

There are multiple ways to define parameterized queries and it depends on the language in which the web developer programs. When a large SQL query is used a number of parameters may be required to be defined carefully.

Web development issues

It is generally known among web developers that using parameterized queries can give maximum security against SQL injection vulnerability. It is being suggested and encouraged as a standard pattern to be followed by web developers. However, if the existing code is not written using parameterized queries, it would be a tedious effort for the developer to walk through and carefully scrutinize the code to rewrite them using parameterized queries. Existing frameworks in dot net do not provide any help for migration to parameterized queries. Further in many organizations, the task of writing SQL statements are assigned to DB analyst. In small organizations, a developer may take the role of the DB analyst. This reason in addition to the time constraints may force those developers in writing their code in the easiest way, by not using any security mitigating logic such as parameterized queries. Personally, this reason and our knowledge of the dotnet framework gave me the motivation to write an automated tool to assist the developers.  

Replacement tool

The replacement tool I developed basically works as a plugin to the Microsoft Visual Studio IDE. Upon enabling this plugin and running, the developer is given options to find vulnerable SQL queries in the current project. Also, it provides the parameterized form of the vulnerable query so the developer can replace the vulnerable SQL code. The plugin works by using the Microsoft DTE interface which gives an object-oriented interface for developing plugin extensions to visual studio. The source code is analyzed using regular expressions. These two design components are discussed below.

DTE interface

Microsoft has exposed some of the inbuilt classes of the Visual Studio IDE to the developer through the DTE interface. The DTE object-oriented model allows the programmer to access the project, code, and other components of the visual studio from a user-defined plugin. Static analysis of the code is possible by using this interface. There are two ways to do static analysis. One is by analyzing the code components of the project using the DTE model which uses the inbuilt lexer and parser. Another is to use regular expressions to find the desired pattern of code. Each has its own pros and cons. The former can do static analysis accurately however it needs in-depth knowledge of the DTE object model. The latter is less accurate since we assume to have a lot of code patterns in the program. However, it is faster and easy to write. For the sake of this short academic project and also due to time constraints I opted to develop the tool using regular expressions.

Regular Expressions

Regular expressions provide a fast and easy way to make static analyses of the program code. It requires some basic understanding of creating a pattern which we want to match from code. Further many languages have an inbuilt regular expression engine that allows extracting text programmatically. We used the regular expression library provided by Microsoft. For example, the following expression could find the SQL statements occurring on server-side page.


Basically, it looks for text that matches the word SQL or obj command followed by the SQL query and execution commands. This pattern was able to detect many of the vulnerable codes in the project. The reason for this being a good pattern is that it exploits the common syntax used in programs to define SQL codes. However, it would not definitely give a perfect match, because the program can take a different structure depending on the developer's coding style. However with carefully scrutinized patterns, one could expect an average matching rate of around 70%.

Developer Interface

The developer user interface made use of the windows forms framework provided by Microsoft. It has various options to find the next occurrence of the unsecured SQL query in the project. If the matching code file which contains such an unsecured SQL query is not yet opened by the developer, it will be automatically opened. Further, the present unsecured SQL query found will be selected and highlighted in the code window. Further manual editing of the generated query can be done by modifying the suggested parameterized SQL query. The sample user interface screenshot is shown in figure 3.

Figure 3. User Interface

Assumptions and limitations

This conversion tool assumes that all command lines in the program are removed by the programmer before running the application. This is because the regular expressions could mismatch the comments as source code. Further, there are different ways to define the SQL code inside a program, but I assumed only the widely used syntax of defining SQL code in the source code. However, these issues can be avoided using the DTE code model with the inbuilt lexer and parser or by defining more scrutinized regular expression patterns. However, I believe it is out of scope for this short project.


Since parameterized queries can guarantee protection against SQLIV the developed replacer tool is expected effective against most of the SQL injection vulnerability. We tested this tool against over ten different projects obtained from the internet and also from organizations. It showed a conversion rate of over 80% for those projects which used syntax similar to those defined in the regular expression pattern. Some of those queries were having over 40 parameters. However, this was not true in all the cases. There was an obvious failure in detecting the vulnerabilities in those projects that do not employ the defined matching pattern. By defining more and more patterns one may be able to achieve a detection and conversion rate of over 80%. However regular expressions cannot be used for those programs that employ complex logic inside the SQL query definition. For example, if a string builder was used to store the SQL query, with the query being added part by part, the matching pattern would be too difficult to write. In such situations analysis using the lexer and parser for dot net framework would provide accurate results.

SQL structure
Static SQL
Dynamic SQL
Conditional SQL
Batch queries
Nested SQL

Table 1. The effectiveness of the developed conversion tool.

Nevertheless, this project showed the power of regular expressions in doing static analysis to prevent SQL injection vulnerability. If an organization needs to quickly convert all its code to parameterized queries a tool like this with regular expression patterns defined by comparing the organization's standard legacy code structure would be very useful.


In this paper, I described the SQL injection vulnerability and ways to mitigate the issue practically by exploiting the security benefits of parameterized queries. The paper described a tool that could assist the developer in successfully converting the SQL statements to parameterized queries with minimal manual intervention. This study though was done specifically focusing dotnet framework, but it is virtually applicable to all kinds of environments. Further, the study showed that such a tool carefully designed would be very helpful for the developer and can mitigate the SQL injection vulnerability to a large extent. 

No comments:

Post a Comment