PHP: List of common pitfalls

I have seen a lot of PHP code, good and bad ones. Even some exploits for pretty common things that were just careless implemented.
In this post i want to share some of these pitfalls so you dont have to make them on your own.

$_GET Vulerabilities

str_replace() validation

<?php
include(str_replace('../','',$_GET['file']));
?>

The str_replace() validation is still vulnerable against a directory change attack.
Simple hack would be:
index.php?file=....//somefile.php
Explanation:
str_replace() does not double replace. If you want to do so use code like this:

<?php
while(strpos($_GET['file'], '../') !== FALSE) {
  $_GET['file'] = str_replace('../','',$_GET['file']);
}
// Or
$_GET['file'] = preg_replace('\.+/+', '', $_GET['file']);
?>

Another example for wrong str_replace() usage:

<?php
include(str_replace('http://','',$_GET['file']));
?>

It is the same problem like above and easily hackable:
index.php?file=hhttp://ttp://www.google.com/

Suffix/Prefix validation

<?php
include('/path/'.$_GET['file'].'.php');
?>

Adding a prefix and a suffix is good, but still vulnerable.
Possible hack:
index.php?file=../../../../etc/passwd%00
Explanation:
The "%00" is a nullbyte, so the internal representation of a zero. Everything behind the nullbyte will be ignored.
The the real command will look like this:
include('/path/../../../../etc/passwd');
On many systems this will include the /etc/passwd!

SQL validation

<?php
mysql_query('SELECT * FROM articles WHERE id = '.$_GET['id'].' ;');
?>

This is very dangerous! The $_GET value can be changed in the query and can give controll over the SQL query!
A simple fix could look like this:

<?php
mysql_query('SELECT * FROM articles WHERE id = '.(int)$_GET['id'].' ;');
?>

Still not perfect but secure.

More

You have some more examples?
Let me know them! Thanks.

No related posts.


 
 
 

Die Kommentarfunktion zu diesem Beitrag wurde deaktiviert.