Advertisement

🐝OWASP Top 10🛡️ Learning {1.1 Directory Transversal}

                                                                     Photo on Unsplash

What is Directory Transversal ?

 

Websites are made up of two types of files: those intended to be accessible by browser i.e. like JS and CSS files.

Web servers often route URLs to particular template of files or assets.

A naively configured server can be too Permissive about what files it return. This may allow an hacker to access the files that were intended for public consumption.

Directory Traversal Vulnerabilities:

Directory traversal vulnerabilities occur when an application takes user input from a URL, file parameter or similar and treats it as a file path without properly sanitizing or validating the user input. This allows an attacker to manipulate the file path and access files and directories outside of the intended web root.
                                                            Photo on Unsplash
 

For example, consider a URL:

              
                     http://example.com/files?file=../../../../etc/passwd            

If the application takes the “file” parameter and includes it directly in a file read or file include operation without any validation, it would be possible to read the /etc/passwd file on the server.
To prevent these vulnerabilities, the application should validate and sanitize user input before using it in file operations

Common defenses include:

  1. Using platform specific functions to canonicalize paths (e.g. realpath() in PHP)
  2. Validating that the final path starts with the expected base directory
  3. Using a whitelist of allowed filenames or paths

 

Here’s an example in PHP that validates the file path:

<?php
$baseDir = '/var/www/files/';
$file = $_GET['file'];

// Validate file path
$path = realpath($baseDir . $file);
if ($path === false || strpos($path, $baseDir) !== 0) {
// Invalid path
die('Invalid file');
}

// Read the file
$contents = file_get_contents($path);

echo $contents;
 
 

In this example, we use realpath() to canonicalize the path, ensuring that it is an absolute path and does not contain any “..” components. We then validate that the resulting path starts with the expected base directory before reading the file.

Directory traversal vulnerabilities can have serious consequences, from exposing sensitive files to allowing an attacker to modify critical files on the server. It’s essential to validate and sanitize user input when performing file operations in web applications.

                Check Out our latest blog ©S.Kumar — Srinix Technology Blog

Post a Comment

0 Comments