The Server Pages


TheServerPages Articles







SQL Injection

Author: Wojjie     Posted: 2004-05-11     Viewed: 7,496

What is it?

SQL Injection is when a visitor injects SQL code that manages to get processed by the SQL server.

Common Causes

This problem usually arises when the programmer does not properly check the user inputed variables before throwing it to the SQL server.

Examples and their exploits

Example 1 (code):
$result=mysql_query("SELECT * from articles where id=$id;");
Example 1 (exploit):

page.php?id=0 UNION SELECT * FROM admin_users
Example 1 (explaination):

What ends up happening here is that since the $id variable is not checked properly, it gets processed in the SQL query. The SQL query the server finally gets in this example is:

SELECT * from articles where id=0 
	UNION SELECT * FROM admin_users;

Hopefully the reason why this happens is apparent to everyone.

Example 1 (solution):

Since $id is EXPECTED to be a number, you should check that it is just that. One common approach is to remove any illegal content in the variable, instead of checking and displaying error messages. Here are two approaches one could of dealt with this issue:

Removing any possible illegal content:
Checking and reporting the error:
if (!is_numeric($id)) {
	... error handling ...
} else {
	... continue ...

Example 2 (code):
$result=mysql_query("SELECT * FROM articles 
	where title=\"$name\";");
Example 2 (exploit):

page.php?name=" UNION SELECT * FROM admin_users 
	where name="%
Example 2 (explaination):
What query gets executed:
SELECT * FROM articles where title="" 
   UNION SELECT * FROM admin_users where name="%"

Hopefully the reason why this happens is apparent to everyone.

Example 2 (solution):

In this example, $name is expected to be a string, so you may expect it to contain anything (perhaps the name has quotes in it?). Best solution to this is to escape the quote in some way.

Using HTML
$name=str_replace("\"", """, $_GET["name"]);
Using a backslash:
$name=str_replace("\"", "\\\"", $_GET["name"]);

Article Sections:
Common Mistakes and their Solutions (2004-05-11)
About various common vulnerabilities found in PHP sites, and solutions on how to prevent them.
Cross-Site Scripting (2004-05-12)
Cross-Site Scripting is when a visitor is able to input html/javascript code inito a website and have it display this code.
GET/POST Variable Manipulation (2004-05-13)
When a visitor is able to cheat the website by modifying GET/POST variables that contain sensitive information and therefore change things that he/she should not be able to.


Copyright © 2004-2015: