logo

Database

Php Unlink Path Traversal

Description

Detects path traversal vulnerabilities in PHP unlink() function calls where unsanitized user input could be used to delete arbitrary files. An attacker could manipulate the file path argument to delete files outside the intended directory, potentially leading to unauthorized file deletion.

Weakness:

082 - Insecurely deleted files

Category: Information Collection

Detection Strategy

    Identifies calls to PHP unlink() function in the code

    Checks if the file path argument provided to unlink() contains user-controllable input

    Verifies if the file path argument lacks proper sanitization or validation

    Reports a vulnerability when unlink() receives a potentially malicious file path that could lead to arbitrary file deletion

Vulnerable code example

<?php
// Simple file deletion script with path traversal vulnerability
if (isset($_GET['file'])) {
    $base_path = 'uploads/';
    $file = $_GET['file'];
    unlink($base_path . $file);  // Vulnerable: Allows traversal via '../' in user input
}
?>

✅ Secure code example

<?php
if (isset($_GET['file'])) {
    $base_path = realpath('uploads/');  // Get canonical base path
    $full_path = realpath($base_path . '/' . $_GET['file']);
    
    // Verify path exists and is within uploads directory
    if ($full_path !== false && str_starts_with($full_path, $base_path)) {
        unlink($full_path);  // Safe: Path verified to be within uploads dir...