Thursday, August 11, 2011

The importance of URL encoding for GET parameter

POST and GET is widely used when we developing an web application, it is used to carry data from one page to another page. For example,

Extract variable category from the following URL
http://www.yourdomain.com/index.php?category=fruit

$cateogry = $_GET["category"];

and then, we may want to echo it on the web page, or form SQL statement for query.

If we don't have any filtering for the value before we really use it, it may become an opportunity for someone to hack in your system. Here are the possibilities,

SQL Injection
SQL injection is a code injection technique that exploits a security vulnerability occurring in the database layer of an application (like queries). Using the above example, if we use the category value to build SQL statement:
$sql = "select * from product where category='".$category."'"

Attackers can change the value from URL to:
http://www.yourcompany.com/index.php?category=';show tables where not '

and your SQL statement becomes
select * from product where category='';show tables where not ''
so your database structure can be listed. The whole database can be dropped in the worst case.

Cross-site Scription Vulnerability
Cross-site scripting vulnerability enables attackers to inject client-side script into web pages viewed by other users. If attackers change the URL from the above example

http://www.yourdomain.com/index.php?category=\%22><script>alert('You have been hacked')</script>

and you directly print "category" at the page, the Javascript sitting in the URL will be run. Attackers can put in any harmful script, such as trojan attack, to it rather that an alert message. Although this type of vulnerability can be blocked by the latest browser, you can't make sure every single client is using the latest browser.

Solution:
Actually, there is a very simple way to prevent this kind of attack. Before using GET or POST variable, do URL encoding first. URL encoding is also a build-in function of PHP.

$category = urlencode($_GET['category']
Related Posts Plugin for WordPress, Blogger...