Open In App

Explain Path Traversal?

Last Updated : 28 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Path traversal, commonly referred to as Directory Traversal, is a security flaw that arises when user-supplied input file names are not sufficiently validated for security or sanitized. This vulnerability might be used by an attacker to read, write, or access files that they shouldn’t be permitted to access or modify. This frequently requires working with file-related functions in PHP applications that accept file paths, including fopen(), file_get_contents(), include(), and so on.

Working of Path Traversal Attacks

You have a PHP script that will, in response to user input, show an image file from a directory.

PHP




<?php
$filename = $_GET["filename"];
$filepath = "/images/" . $filename;
header("Content-Type: image/jpeg");
echo file_get_contents($filepath);
?>


Now, if the user provides a value like “my_image.jpg” for filename, the script will read the file /images/my_image.jpg. However, if someone provides a value like “../../etc/passwd”, the script will read the file “/etc/passwd”, leaking sensitive information.

Techniques to Prevent Path Traversal Attacks

  • Prior to utilizing user input in file operations, always sanitize it.

When the PHP basename() function is used, directory paths are removed and just the file name is retained.

$filename = basename($_GET['filename']);
  • Use whitelisting and only permit known beneficial values.
$allowed_files = ["image1.jpg", "image2.jpg"];
if (!in_array($_GET['filename'], $allowed_files)) {
   die("Not allowed!");
}
  • Disable Reporting PHP Errors to Client: To reduce information leakage, disable PHP error reporting to the client.
ini_set('display_errors', '0');
  • Verify the file’s anticipated extension by checking the file’s extension.
$file_extension = pathinfo($_GET['filename'], PATHINFO_EXTENSION);
if (!in_array($file_extension, ['jpg', 'png'])) {
   die("Not allowed!");
}
  • Always convert to an absolute path and confirm that it is located in the desired directory when using absolute paths.
$filepath = realpath("/images/" . $filename);
if (strpos($filepath, "/images/") !== 0) {
   die("Not allowed!");
}

You may aid in preventing path traversal vulnerabilities in your PHP application by implementing these security-recommended practices.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads