SQL Injection
SQL Injection
SQL injection is an attack in which malicious code is inserted into strings that are later passed to an
instance of the SQL Server Database Engine for parsing and execution. Any procedure that constructs
SQL statements should be reviewed for injection vulnerabilities, because the Database Engine executes
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 then concatenated
into a dynamic SQL command, the malicious code is executed.
The injection process works by prematurely terminating a text string and appending a new command.
Because the inserted command might have extra strings appended to it before it executes, the
malefactor terminates the injected string with a comment mark --. Subsequent text is ignored at
execution time.
The following script shows a simple SQL injection. The script builds a SQL query by concatenating hard-
coded strings together with a string entered by the user:
var ShipCity;
var sql = "select * from OrdersTable where ShipCity = '" + ShipCity + "'";
The user is prompted to enter the name of a city. If they enter Redmond, the query assembled by the
script looks similar to the following example:
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's executed by the server. When the Database Engine processes this statement, it
first selects all records in OrdersTable where ShipCity is Redmond. Then, the Database Engine
drops OrdersTable.
As long as injected SQL code is syntactically correct, tampering can't be detected programmatically.
Therefore, you must validate all user input and carefully review code that executes constructed SQL
commands in the server that you use. Coding best practices are described in the following sections in
this article.