Description
Using input as a file path may let an attacker read or write unintended files through paths such as ../.
Potential impact
Sensitive files may be exposed, arbitrary files deleted, or configuration files modified.
Remediation
Restrict filenames with basename and an allow-list, and verify that the final path is inside the base directory.
Examples
The server must control the allow-list and target files. Protect them so attackers cannot replace files or symbolic links.
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]);
Explanation:
- Before: Uses user-controlled data as a filesystem path.
- After: Maps allowed file keys to fixed paths instead of joining a user-supplied path string.