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.
Imagine um scanner de chave de hotel que só deveria abrir quartos no segundo andar. Se um hóspede digita '../../master-safe' no teclado da porta, uma fechadura vulnerável sobe pelo corredor e abre o cofre principal da gerência.
Web Application SecurityCWE-918.CWE-918Defense-in-DepthUm endpoint aceita um nome de arquivo ou identificador de recurso fornecido pelo usuário por parâmetro HTTP.
O invasor injeta sequências de diretório relativo como '../', '..%2f' ou caminhos absolutos no parâmetro.
O backend concatena o nome sem resolver o caminho canônico nem validar que o destino permaneça no diretório base.
O runtime abre e transmite arquivos sensíveis do sistema (como /etc/passwd ou credenciais) diretamente ao cliente.
<?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.