Saturday, August 1, 2009

Directory traversal


<?php

$page = isset($_GET['page']) ? $_GET['page'] : 'home';

require $page . '.php';

?>

We will just say that this particular file is stored in the following path:

/home/someone/public html/index.php. The attacker could then do: in-

dex.php?page=../secret

That would give us /home/someone/public html/secret.php which would

otherwise have been accessible. I am sure you could think of more dangerous

situations than this particular one.

There are a couple of ways you could prevent this with. First of all you

could have an array of valid pages, e.g.:

$pages = array(

'home',

'login',

'logout',

// etc.

);


if (!in_array($page, $pages) {

die('Invalid page');

}

Another thing you could do is check that the requested file matches a par-

ticular format:

$file = str_replace('\\', '/', realpath($page . '.php'));

if (!preg_match('%^/home/someone/public_html/[a-z]+\.php$%',

$file)) {

die('Invalid page');

}

include $file;

Basically you need to verify that the entered information is valid and con-

forms to what you expected.


No comments: