DefenseCode

Form File Upload

Risk type:MEDIUM

Description:

Website that uses forms for uploading files to server could be vulnerable to series of attacks like:

  • defacing
  • web server compromising by uploading and executing a web-shell which can:
    • run a command,
    • browse system files,
    • browse local resources,
    • attack other servers,
    • exploit local vulnerabilities,
  • making website vulnerable to some other vulnerability like server side scripting,
  • puting a phishing web page to server,
  • and much more...

Example:

Vulnerable website is using form file upload script "uploader.php" that saves user's uploaded files to "/www/uploads" directory. HTML upload form could look like this:

<form enctype="multipart/form-data" action="uploader.php" method="POST" />
<input type="hidden" name="MAX_FILE_SIZE" value="100000" />
Choose a file to upload:
<input name="uploadedfile" type="file" />
<input type="submit" value="Upload File" />
</form>

Script "uploader.php" has the following code:

<?php
$target_path = "uploads/";
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)){
echo "the file " . basename($_FILES['uploadedfile']['name']) . " has been uploaded!";
} else {
echo "there was an error uploading the file, please try again!";
}
?>

Since the script does not contain file type restrictions the attacker can upload malicious script "malicious.php" and execute it by using the following link:

http://www.victim.com/uploads/malicious.php

Mitigation:

  • Use a blacklist for file extensions (this is less safe because it is possible to bypass this protection using some extensions which are executable on the server but are not mentioned in the list).
  • Use a whitelist for file extensions.
  • Use Content-Type from the request HTML header - some web applications use this parameter to recognize a file as a good one.
  • Use file type recognizers (functions or APIs that check the file type).
  • Accept only alphanumeric characters and escape others.
  • Limit the file size and filename length. Also, restrict small size files.
  • Upload directory should not have any execute permission.
  • Prevent file overwriting by checking hash.
  • Use a virus scanner on the server (if applicable).
  • Use POST method instead of PUT or GET.

Further reading:

https://www.owasp.org/index.php/Unrestricted_File_Upload
http://www.acunetix.com/websitesecurity/upload-forms-threat.htm