Path traversal

Path traversal

Description

Choose downloadable files on the server. Appending a request value to the path passed to readfile can expose files outside the download directory.

Potential impact

Reads can expose sensitive files accessible to the process. The same path handling in write or delete operations can damage files the service account can modify.

Remediation

Require a string and look it up in a server-managed allow-list that maps keys to fixed paths under the base. If you use basename to extract a name, still check that access to that file is allowed.

Examples

Keep the allow-list, target files, and links under server control so other users cannot replace them.

Before

php
<?php
$path = $_GET['file'];
readfile('/var/www/downloads/' . $path);

After

php
<?php
$allowed = [
    'report.pdf' => '/var/www/downloads/report.pdf',
];

$file = $_GET['file'] ?? '';
if (!isset($allowed[$file])) {
    http_response_code(404);
    exit;
}

readfile($allowed[$file]);

The example maps only report.pdf to a fixed path. Other string keys receive a 404 response.

References