content top

Sunday, September 4, 2011

SQL Injection Tutorial

SQL injection hacks are performed on servers that do not have the necessary secure programming. These are usually accomplished on servers where the web-page code uses inline SQL, which means the query is in the web-page code rather than located in a stored procedure. Knowing how a SQL injection hack works helps website owners protect customer data and secure the web pages.
http://www.clearskies.net/images/header-code_02.jpg

The Form Variable

# The first step in understanding how an SQL injection attack is created is by replicating the problem. SQL injection attacks are accomplished through form variables in an HTML page. Creating the form enables the webmaster to simulate and test the security of the web server. Below is an example of a form object used to create a SQL injection attack.



Although this is a simple form textbox, it's all that is needed to accomplish an SQL injection.


The Hacker Code


# When SQL statements are made, the application builds SQL code that is sent to the database. When a string is sent to the database, the code looks something like the below text:

select * from myTable where name='myVariableFromtheForm'

The tick mark signifies the end of the SQL code, and this is where hackers target. When a textbox like the one created in Section 1 is used to build a string, a hacker can enter something like the following into the textbox:

' or 1=1; --

This might look like gibberish, but in fact it injects code into the database that is run by the server. When "myVariableFromtheForm" is replaced by the code above, the statement run by the server actually looks like the following:

select * from myTable where name=' ' or 1=1 --'

The "--" is the comments code for SQL server, so the last terminating tick is ignored. The string is empty and the hacker injects the code "1=1" into the statement. What that does is return every row from the table to the hacker. This is how an unscrupulous person steals private information from database servers.

Fixing the Problem



The best way to fix the problem in code that is susceptible to an SQL injection hack is to use the "Replace" function in every instance where text is entered from users. For instance, in ASP code, the following line of code replaces the single tick mark with two. When a SQL Server runs code with two tick marks, it reads them as a literal and the string is not terminated.

string.Replace(" ' ", " '' ");

The code above replaces all instances of a single tick mark with two, removing the vulnerability of an SQL injection attack.

No comments:

Post a Comment

content top