Track down the source of SQL Injection

A SQL Injection attack is a malicious technique used to attack databases through a website.  It adds portions of SQL statements into the URL from a page that accepts user input.  The attack is successful when there are vulnerabilities in a website where user input is not filtered and validated.

Studies claim that on average an application experiences dozens of attempts per hour.  That doesn’t surprise me as I frequently see evidence of these attempts in the application event logs on a web server.  In light of the continual ongoing attacks against sites around the world, you should make sure that your application is secured.

What if you’ve been the victim of a SQL injection attack?  I’ll help you track down the page or pages that the attacker used to compromise your database so you can secure them against future attacks.  Securing the pages and validating the data is beyond the scope of this post.  You can find many resources on the Internet with that information.

The place to find the pages that were compromised are in your website’s log files.  We can easily scour these log files and get meaningful output by using Log Parser.  You can download it from Microsoft here.  I’ll provide you with a Log Parser query to get you started. You will want to change the path to the log files for your site.  You will also note that my query includes a wildcard for the log files.  In the example, it will look through all available log files for July 2012.

logparser.exe -i:iisw3c -o:Datagrid -rtp:100 “select date, time, c-ip, cs-uri-stem, cs-uri-query, time-taken, sc-status from C:\wwwlogs\W3SVCXXX\u_ex1207*.log where cs-uri-query like ‘%declare%'”

The section that you should note the most in the Log Parser query is the %declare% string.  Two of the most common commands that are used to inject information into your SQL database are ‘cast’ and ‘declare.’  Two other less commonly used are ‘convert’ and ‘execute.’  Fortunately most of the time these are sent in plain text in the query so that makes it easier to find the entries in the log.  The percent signs on either side of the declare term are just wild cards making it easier for log parser to effectively find the log entries.  You will want to run the query against your log files multiple times replacing %declare% with the other words.

The output from the query will display in a datagrid showing you the page that was exploited as well as some other information that I have included.  You can use this information to secure that page or pages on your site saving countless hours of potentially going through hundreds or thousands of pages on your site trying to find the point of entry.

Rick is a Senior Support Lead at OrcsWeb, a hosted server company providing managed hosting solutions.