Lukas' Notes

web security

Definition

Path Traversal

A path traversal vulnerability occurs when a server uses client-supplied input to build a filesystem path and fails to confine the result to the webroot. Because ../ denotes the parent directory, an attacker can use a sequence such as ../../../etc/passwd to read arbitrary files outside the intended directory.

<?php
$content = file_get_contents('pages/' . $_GET['page']);
echo $content;
?>

Request GET /index.php?page=../../../etc/passwd then exfiltrates /etc/passwd.

Naive Mitigation Fails

Block-list replacement is bypassable

Filtering ../ with str_replace('../', '', $input) does not work, because the literal ../ it produces overlaps a fresh ../ once removed:

Never sanitise traversal by escaping or removing ../.

Prevention

Allow-list or canonical-path prefix check

  • Static inclusion — match $_GET['page'] against an allow-list of existing files.
  • Dynamic inclusion — compute the canonical path with realpath() and validate that it still starts with the webroot prefix.
<?php
$pdir  = '/var/www/htdocs/pages/';
$fname = realpath($pdir . $_GET['file']);
if (str_starts_with($fname, $pdir)) {
    echo file_get_contents($fname);
}
?>