Preventing File System Attacks

Jump to: navigation, search
Categories » Programming » .NET Programming » ASP.NET » Preventing File System Attacks
Categories » Programming » Web Programming » ASP.NET » Preventing File System Attacks
Categories » Programming » Web Programming » PHP » Preventing File System Attacks
Categories » Programming » Web Programming » Preventing File System Attacks

Background

It is important to prevent users from being able to use strings like ../ to get out of the intended directory for a script (e.g., when using fopen to open a user-requested file).

Code

ASP.NET

If a user attempts to go above the application's working directory, the server will generate the following error:

System.Web.HttpException: Cannot use a leading .. to exit above the top directory.

It still may be necessary to write some code to prevent a user from going above (or below) the intended directory, but at least the above exception makes things a little safer.

PHP

This seems to decode URL encoded strings as well.

// This is the directory we want to restrict users to
$doc_root = realpath("../files/");
// Find the actual path of the user's requested file
$requested_file = realpath("../files/".$_REQUEST['file']);
if ($requested_file) { // if the file exists
	if (substr($requested_file,0,strlen($doc_root)) === $doc_root) {
		// the file is ok
	} else die(); // the file is outside of the intended directory
} else die(); // the file doesn't exist
Personal tools
Namespaces
Variants
Actions
Navigation
Categories
Toolbox