SQL injection
Introduction
SQL injection involves unscrupulous people and criminals adding or 'injecting' SQL commands to SQL statements via data input boxes on a web page in a web site. These injected SQL commands can alter and compromise the security of the database behind the web site. In the worst case, the database can be completely stolen or destroyed.
How does SQL injection work
Some websites are designed to allow users to enter in data into data input boxes. This might be to log in to the website or might be so that the user can search for data e.g. search for a product in a business's online catalogue. Once data has been entered into the data input boxes. the web site's server constructs an SQL command which incorporates the data input and gets back information from an underlying database. Data input is made up of plain text, and SQL statements are also made up of plain text and it is therefore easy to write a small program to access the database in ways that weren't intended.
Examples of SQL injection
EXAMPLE 1
Suppose an authorised user typed the following into a web page to get back a specific student's details:
SELECT * FROM students WHERE StudentID = 34298
This would get back all of the details for student 34298. Now imagine an unauthorised user got access to the website and typed this in:
SELECT * FROM students WHERE StudentID = 34298 or 1 = 1
This would get back everyone's details, because 1 = 1 is always TRUE.
EXAMPLE 2
You can use the technique shown in example 1 in a number of ways. Suppose a user has to log in to a website.
The code on the server to verify the user could be this:
uName = getRequestString("UserName");
uPass = getRequestString("UserPass");
sql = "SELECT * FROM Members WHERE Name = ' "uName + " ' AND Pass = ' " uPass + " ' "
If you injected the word OR into the right place, the SQL code would become:
SELECT * FROM Members WHERE NAME = "" or ""="" AND PASS = "" or ""=""
The WHERE part of the statement will always be TRUE so all of the users in the database could be accessed along with their passwords.
Countermeasures
One way to stop SQL injection is to restrict the SQL commands, the types of data and the characters that a user can enter. The server can look at any input and reject any commands on a blacklist created for this purpose. This might work for some databases but it can restrict the flexibility a user has to search for and get back the data they need.
Another way is to use SQL parameters. This is a technique that makes sure data entered into fields such as Username and Password are valid data items before an SQL command is constructed.