10. Preventing file upload vulnerabilties

Extension validation While whitelisting extensions is always more secure, as we have seen previously, it is recommended to use both by whitelisting the allowed extensions and blacklisting dangerous extensions. This way, the blacklist list will prevent uploading malicious scripts if the whitelist is ever bypassed (e.g. shell.php.jpg)

Example PHP code

$fileName = basename($_FILES["uploadFile"]["name"]);

// blacklist test
if (preg_match('/^.+\.ph(p|ps|ar|tml)/', $fileName)) {
    echo "Only images are allowed";
    die();
}

// whitelist test
if (!preg_match('/^.*\.(jpg|jpeg|png|gif)$/', $fileName)) {
    echo "Only images are allowed";
    die();
}

blacklist checks: if ext exists anywhere in filename whitelist checks: if filename ends with extension

Content validation Always validate both extension and its' content.

$fileName = basename($_FILES["uploadFile"]["name"]);
$contentType = $_FILES['uploadFile']['type'];
$MIMEtype = mime_content_type($_FILES['uploadFile']['tmp_name']);

// whitelist test
if (!preg_match('/^.*\.png$/', $fileName)) {
    echo "Only PNG images are allowed";
    die();
}

// content test
foreach (array($contentType, $MIMEtype) as $type) {
    if (!in_array($type, array('image/png'))) {
        echo "Only PNG images are allowed";
        die();
    }
}

Upload disclosure

Avoid disclosing the uploads directory location or providing direct access to the uploaded files. Always recommended to hide upload directory from end-users and only allow them to download the uploaded files through a download page

Write a download.php script to fetch the requested file from uploads and then download the file for the end user, this way the directory is hidden

Make sure that the download.php script only grants access to files owned by the user who uploaded it. (i.e. avoiding IDOR/LFI) and users do not have access to the upload directory receiving a 403 error.

In addition - randomize names of uploaded files in storage + store their sanitized names in a database. when download.php needs to download a file, it fetches its' original name from the db + provides it at download time for the user.

Store uploaded files in separate server or container.


Disabling functions that enable RCE

few other tips: