views:

266

answers:

5

I have some old databases i was handed that use SQL Server 2000 and they are getting SQL Injected with javascript script tags at the end of certain database fields. I need a trigger to strip out the injected on update until I have time to fix the front end that is allowing this.

I am a SQL Server novice - please help!

A: 

something like:

UPDATE table
SET field = REPLACE(field, '</script>', REPLACE(field, '<script>',''))
WHERE table.pk IN (SELECT pk FROM inserted WHERE field LIKE '%script>')

?

le dorfier
I don't think you can update the virtual tables directly. Instead, I think you need to join to the actual tables and update those.
Michael Haren
Right - it's been a while - I've pretty much forgone triggers. :)
le dorfier
A: 

Is there any regex like functionality in SQL Server 2000? The content of the script tags constantly changes.

Slee
SQl Server 2000 has no regex functionality other than the sort of replace shown in the responses. Can you restore the db from just before the attack?
HLGEM
A: 

There's a large scale attack that's been going on since way back in April, and if that's what getting you then you'd have to add a trigger for every table in the database. This script modifies the original attack code to clean up everything in one swoop, assuming <script isn't valid text anywhere in the db:

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+']=LEFT(['+@C+'], CHARINDEX(''<script'', ['+@C+'])-1)
WHERE CHARINDEX(''<script'', ['+@C+']) >0')
FETCH NEXT FROM Table_Cursor INTO @T,@C 
END 
CLOSE Table_Cursor 
DEALLOCATE Table_Cursor

Additionally, I've heard you may have luck stopping this attack by removing SELECT permissions for the application user on syscolumns or sysobjects, if that's an option for you. You still need to fix your vulnerabilities in preparation for the next attack.

Joel Coehoorn
+3  A: 
Frustrating Developments
It is better, but has the downside where code that used to always succeed now could throw an exception.
Joel Coehoorn
yes, I just thought of that and came back to comment on it. It doesn't really matter though, anyone who is putting that kind of content into your site doesn't need any good feedback. ;-)
Frustrating Developments
This is simple and working perfectly - thank you!
Slee
A: 

once your data is fixed you will need to find and fix the way the injections are getting into your datbase. I presume you are probably using dynamic SQl. This article will help you fix it so that injections won't be a problem http://www.sommarskog.se/dynamic_sql.html

HLGEM