msgbartop
Adam Palmer MBCS CITP, Linux, PHP Programmer, MySQL Developer, Embedded Hardware, Security Consultant
Did my blog help you? Please link to me!
  dns test
 
RSS Feed
msgbarbottom

04 Sep 09 Security Consultant – PHP Developer – Exploiting Common PHP Code Flaws

There are a number of PHP and in fact programming errors in general that PHP Programmers and Security Consultants need to be aware of. Specifically, how can a malicious user use the code to gain access above what he is supposed to.

Cross Site Scripting (XSS), Shell Execution and SQL Injection are all issues that programmers need to be aware of. Luckily, buffer overflows in their traditional sense are not something that PHP developers need to concern themselves with.

Here in it’s most basic sense is an example of how we can read arbitrary files on the filesystem that we should not have access to.

Assume the following code as an example:

readfile.php:
<?php
$filename = “/data_files/” . $_GET['filename'];
$data = file_get_contents($filename);
echo “The data in file ” . $filename . ” is: ” . $data;
?>

The purpose of readfile.php is to allow the user to call www.example.com/readfile.php?filename=data1 . The system will then open /data_files/data1 and output the data to screen. This has multiple real life uses.

The problem in it’s most simple form, is that the user can of course enter anything after the filename= part. This could be a file that doesn’t exist, or a file within the directory that I should not be reading.

Most importantly of course, even though “/data_files/” has been specified, I can quite easily traverse it with “..” – i.e. should I enter, filename=../etc/passwd. This would translate to /data_files/../etc/passwd which is essentially /etc/passwd

Bugs in the real world are unlikely to be visible in the code in such an obvious fashion however once they are find, exploiting them can genuinely be that easy.

How can this be solved? Firstly, only have part of the filename come from the input parameter:

$filename = “/data_files/data” . $_GET['filename'] . “.txt”;
$data = file_get_contents($filename);

Alternatively, don’t have the input parameter passed directly to the file open function at all:

switch($_GET['filename'])
{
case 1:
$file = “data1.txt”;
break;
case 2:
$file = “data-two.txt”;
break;
}
$data = file_get_contents($file);

In this example, the user can now pass ?filename=1 and the relevant file will be opened – no other input will be accepted or relevant.

More advanced attacks will be covered in future, specifically SQL Injection – my favorite.

Tags: , , , , , , , , , ,



Leave a Comment