12.2. Path Traversal

Web servers are typically set up to serve content from designated directories. Occasionally a vulnerability will be found in the server software itself which will allow files outside of designated areas to be accessed, but these are pretty much patched in more mature servers such as Apache. Web applications, however, can access the files in other directories, because they execute on the server machine behind the HTTP request. A path traversal attack tricks the script into displaying the contents of directories and files outside of the web root which may contain sensitive information.

Consider this vulnerable code, exploit_02.php:

<?php
define('TEMPLATE_DIR', '../templates/');

$GLOBALS['TEMPLATE']['content'] = '<p>Hello World!</p>';

if (isset($_GET['t']))
{
    $template = TEMPLATE_DIR . $_GET['t'];
}

if (isset($template) && file_exists($template))
{
    include $template;
}
else
{
    include TEMPLATE_DIR . 'default.php';
}
?>

The code accepts the name of a template file from the URL parameter t with which to display page content. A call to exploit_02.php?t=blue.php for example requests the file use ../templates/blue.php as its template when displaying the page. If blue.php doesn't exist it will default to ../templates/default.php. Well, at least that's what the intent is anyway.

The code is vulnerable because no checks are made on the $template variable to see if its value resides in the web root directory. Just as PHP uses ../ to back out of the public_files directory ...

Get PHP and MySQL®: Create-Modify-Reuse now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.