Cleaning Your Database After a SQL Injection Attack

If you have an older website that doesn't have the top-notch security that most Inetium websites have, you may be vulnerable to a SQL injection attack.  I wrote a SQL script to clean up a database that has been hit with a SQL injection attack.

It goes through the database and grabs all the string columns (ntext, text, varchar and nvarchar) from all the tables.  Then, it replaces some bad text that was added by the SQL injection attack - "[Text added via a SQL injection attack]" - with nothing.

Good luck cleaning your database!

DECLARE CleanDatabaseCursor CURSOR
READ_ONLY
FOR

SELECT o.name as [Object Name], c.name as [Column Name]
FROM syscolumns c INNER JOIN sysobjects o ON o.id = c.id
WHERE c.type in (35, 39) and o.xtype like 'U'

declare @query VARCHAR(8000)
declare @ObjectName varchar(8000)
declare @ColumnName varchar(8000)
declare @newValue varchar(8000)

select @ObjectName = ''
open CleanDatabaseCursor
fetch next from CleanDatabaseCursor into @ObjectName, @ColumnName

While @@FETCH_STATUS = 0
BEGIN

SET @query = 'UPDATE [' + @ObjectName + ']' + ' SET [' + @ColumnName + '] = REPLACE(CONVERT(varchar(8000), [' + @ColumnName + ']), ''[Text added via a SQL injection attack]'', '''')'
EXECUTE (@query)
FETCH NEXT FROM CleanDatabaseCursor INTO @ObjectName, @ColumnName

END
CLOSE CleanDatabaseCursor
DEALLOCATE CleanDatabaseCursor

Published Monday, August 04, 2008 12:05 PM by vbullinger