Tuesday, November 17, 2009

SQL Injection

SQL injection is an attack in which malicious code is inserted into strings that are later passed to an instance of SQL Server for parsing and execution. Any procedure that constructs SQL statements should be reviewed for injection vulnerabilities because SQL Server will execute all syntactically valid queries that it receives. Even parameterized data can be manipulated by a skilled and determined attacker.

The primary form of SQL injection consists of direct insertion of code into user-input variables that are concatenated with SQL commands and executed. A less direct attack injects malicious code into strings that are destined for storage in a table or as metadata. When the stored strings are subsequently concatenated into a dynamic SQL command, the malicious code is executed.

UserID = Request.form ("userid");
var sql = "select * from UserTable where ID= '" + UserID + "'";
The user is prompted to enter the User ID. If she or he enters "jack", the query assembled by the script looks similar to the following:

select * from UserTable where ID = 'jack'

However, assume that the user enters the following:

jack; drop table UserTable--

In this case, the following query is assembled by the script:

select * from UserTable where ID = 'jack''; drop table UserTable--'

The semicolon (;) denotes the end of one query and the start of another. The double hyphen (--) indicates that the rest of the current line is a comment and should be ignored. If the modified code is syntactically correct, it will be executed by the server. When SQL Server processes this statement, SQL Server will first select all records in UserTable where ID is jack. Then, SQL Server will drop UserTable.

Input characterMeaning in Transact-SQL


Query delimiter.


Character data string delimiter.


Comment delimiter.

/* ... */

Comment delimiters. Text between /* and */ is not evaluated by the server.


Used at the start of the name of catalog-extended stored procedures, such as xp_cmdshell.