The Server Pages

»

TheServerPages Articles

»

Webmasters

»

PHP

»

Security

SQL Injection

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

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):
...
$id=$_GET["id"];
$result=mysql_query("SELECT * from articles where id=$id;");
...
Example 1 (exploit):

URL:
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:
...
$id=intval($_GET["id"]);
...
Checking and reporting the error:
...
$id=$_GET["id"];
if (!is_numeric($id)) {
	... error handling ...
} else {
	... continue ...
}
...


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

URL:
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.

Comments

Copyright © 2004-2015: TheServerPages.com