SQL Injection

SQL injection is probably the most common vector used to attack SQL Server. This is because web applications are typically deployed as Internet-facing and, if written in-house, their code will probably not have been subject to the same stringent security auditing as commercial software. SQL Server is also particularly vulnerable to this type of attack because of its verbose error messages. SQL Server's error messages can be viewed in the sysmessages table in the master database.

SQL injection occurs when information submitted by a browser to a web application is inserted into a database query without being properly checked. An example of this is an HTML form that receives posted data from the user and passes it to an Active Server Pages (ASP) script running on Microsoft's IIS web server. The two data items passed are a username and password, and they are checked by querying a SQL Server database. The schema of the users table in the backend database is as follows:

sername varchar(255)
password varchar(255)

The query executed is

SELECT * FROM users WHERE username = '[username]' AND password =
'[password]';

However, the ASP script builds the query from user data using the following line:

var query = “SELECT * FROM users WHERE username = '” + username +”' AND
password = '” + password + “'”;

If the username is a single-quote character (') the effective query becomes

SELECT * FROM users WHERE username = ''' AND password = '[password]';

This is invalid SQL syntax ...

Get The Database Hacker's Handbook: Defending Database Servers now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.