flawopen.com/path-traversal/Php
How include and file_get_contents suffer from path traversal, and how to verify boundaries using realpath and str_starts_with.
设想一家酒店的房卡扫描锁原本只允许开启二楼的客房。如果客人在门禁键盘上输入 '../../master-safe',有缺陷的门锁就会跳出当前楼道,直接打开酒店经理办公室的主保险箱。
Web Application SecurityCWE-918.CWE-918CWE-918):Standard Common Weakness Enumeration classification for path-traversal-php.Defense-in-Depth应用程序接口通过 HTTP 参数接收用户指定的文件名、报告路径或静态资源标识。
攻击者在文件名参数中注入相对路径遍历符号(如 '../', '..%2f')或绝对路径覆盖。
后端直接将不可信输入与基础目录拼接,未进行规范化绝对路径解析(Canonicalization)与边界校验。
系统运行时打开并回传敏感配置文件(如 /etc/passwd、源码凭证、环境变量密钥),造成数据外泄。
<?php
// VULNERABLE: Direct concatenation in file read
$base_dir = '/var/www/uploads';
$file = $_GET['file'];
// Attacker input: ../../../../etc/passwd
$path = $base_dir . '/' . $file;
// Dumps arbitrary server file to user
readfile($path);
?>
<?php
// HARDENED: Canonicalize with realpath and enforce directory prefix check
$base_dir = realpath('/var/www/uploads');
$file = $_GET['file'] ?? '';
if (!is_string($file) || empty($file)) {
http_response_code(400);
exit('Invalid file parameter');
}
// 1. Resolve canonical path
$real_target = realpath($base_dir . DIRECTORY_SEPARATOR . $file);
// 2. Strict boundary check (ensure prefix matches base_dir + separator)
$expected_prefix = $base_dir . DIRECTORY_SEPARATOR;
if ($real_target === false || !str_starts_with($real_target, $expected_prefix)) {
http_response_code(403);
exit('Forbidden: Path Traversal detected');
}
if (!is_file($real_target)) {
http_response_code(404);
exit('File not found');
}
readfile($real_target);
?>
realpath() to resolve absolute paths。readfile() or include。