Uploading files
suggest changeIf you want users to upload files to your server you need to do a couple of security checks before you actually move the uploaded file to your web directory.
The uploaded data:
name and type are supplied by the client, so a program can send any values it likes. size and tmp_name are filled in by PHP. Before using tmp_name, check that error is UPLOAD_ERR_OK.
$_FILES['file']['name'];
$_FILES['file']['type'];
$_FILES['file']['size'];
$_FILES['file']['tmp_name'];
name- Verify every aspect of it.type- Never use this data. It can be fetched by using PHP functions instead.size- Safe to use.tmp_name- Safe to use.
Exploiting the file name
Normally the operating system does not allow specific characters in a file name, but by spoofing the request you can add them allowing for unexpected things to happen. For example, let’s name the file: ../script.php%00.png. Take a good look at that filename and you should notice a couple of things.
- The first thing to notice is the
../, fully illegal in a file name and at the same time perfectly fine if you are moving a file from 1 directory to another, which we’re gonna do right? - A real NUL byte in a path used to truncate the name in filesystem calls, which would strip
.png. PHP has rejected NUL bytes in paths since 5.3.4. PHP also does not URL-decode$_FILES[...]['name'], so the three characters%00stay in the name and do not become a NUL.
So now I’ve uploaded script.php to another directory, by-passing simple validations to file extensions. It also by-passes .htaccess files disallowing scripts to be executed from within your upload directory.
Getting the file name and extension safely
You can use pathinfo() to extrapolate the name and extension in a safe manner but first we need to replace unwanted characters in the file name:
// This array contains a list of characters not allowed in a filename
$illegal = array_merge(array_map('chr', range(0,31)), ["<", ">", ":", '"', "/", "\\", "|", "?", "*", " "]);
$filename = str_replace($illegal, "-", $_FILES['file']['name']);
$pathinfo = pathinfo($filename);
$extension = $pathinfo['extension'] ?? '';
$filename = $pathinfo['filename'] ?? '';
if(!empty($extension) && !empty($filename)){
echo $filename, $extension;
} else {
die('file is missing an extension or name');
}
While now we have a filename and extension that can be used for storing, I still prefer storing that information in a database and give that file a generated name of for example, md5(uniqid().microtime())
+----+--------+-----------+------------+------+----------------------------------+---------------------+
| id | title | extension | mime | size | filename | time |
+----+--------+-----------+------------+------+----------------------------------+---------------------+
| 1 | myfile | txt | text/plain | 1020 | 5bcdaeddbfbd2810fa1b6f3118804d66 | 2017-03-11 00:38:54 |
+----+--------+-----------+------------+------+----------------------------------+---------------------+
This would resolve the issue of duplicate file names and unforeseen exploits in the file name. The stored name no longer comes from the client, so the attacker cannot choose a path that will be executed.
Mime-type validation
Checking a file extension to determine what file it is is not enough as a file may be named image.png but may very well contain a php script. By checking the mime-type of the uploaded file against a file extension you can verify if the file contains what its name is referring to.
You can even go 1 step further for validating images, and that is actually opening them:
if ($mime == 'image/jpeg' && ($extension == 'jpeg' || $extension == 'jpg')) {
if ($img = imagecreatefromjpeg($_FILES['file']['tmp_name'])) {
imagedestroy($img);
} else {
die('image failed to open, could be corrupt or the file contains something else.');
}
}
You can fetch the mime-type using a built-in function or a class. Pass tmp_name, not the client filename.
White listing your uploads
Most importantly, you should whitelist file extensions and mime types depending on each form.
function isFiletypeAllowed($extension, $mime, array $allowed)
{
return isset($allowed[$mime]) &&
is_array($allowed[$mime]) &&
in_array($extension, $allowed[$mime]);
}
$allowedFiletypes = [
'image/png' => [ 'png' ],
'image/gif' => [ 'gif' ],
'image/jpeg' => [ 'jpg', 'jpeg' ],
];
var_dump(isFiletypeAllowed('jpg', 'image/jpeg', $allowedFiletypes));