Is there any security threat from allowing an ID passed through $_GET['id'] to be used in file paths? If so could you provide an example how it could be exploited, and/or how to properly avoid it?
For example:
$settings['full_path']="/home/user/public_html/";
if(file_exists($settings['full_path'].$_GET['id'].".zip"))
{
unlink($settings['full_path'].$_GET['id'].".zip");
}
Potential problems with user input on file paths?
Moderator: General Moderators
Re: Potential problems with user input on file paths?
example.com?id=../../some_completely_diffetent_file
If you want to avoid it, validate it against length and allowed characters, i.e.:
If you want to avoid it, validate it against length and allowed characters, i.e.:
Code: Select all
if(!ctype_alpha($_GET['id']))
{
die('Only alphanumeric symbols allowed.');
}
Re: Potential problems with user input on file paths?
Like Zyxist said, depending on what you want to do with the file, you need to make sure that the user input doesn't contain patterns that will navigate away from your expected location. Namely, "../". While Zyxist's suggestion to restrict to alphanumerics would probably work, you can't always be so restrictive. realpath() is great for this type of thing.
There's more to protect against though, and it depends on exactly what you are needing to do with these files. For example, you should make sure that the user making the request is authorized to read/update/delete the file. I never store files on the file system with user-provided names. Instead, I generate an ID for each file and store information in the database about it. Usually this is info such as the file name, type, who has rights to it, etc.
You can learn more from this recent thread:
viewtopic.php?f=34&t=113948&p=601396#p601396
Code: Select all
$userDirectory = '/path/to/user/dir'; // It's safe to work in this directory
$requestedFile = realpath($userDirectory . '/' . $filename); // FALSE if doesn't exist
$requestedPath = dirname($requestedFile); // Empty string "" if $requestedFile is FALSE
$expectedPath = realpath($userDirectory);
// Make sure the expected directory exists
if (!$expectedPath) {
die('User directory is missing.');
}
// Confirm that the requested file is in the expected path
if ($requestedPath == $expectedPath) {
// Do something with the file.
}You can learn more from this recent thread:
viewtopic.php?f=34&t=113948&p=601396#p601396