Input Validation / Upload of Malicious Files
The application allows the attacker to upload or transfer malicious that can be automatically processed within the product's environment.The application should be able to fend off bogus and malicious files in a way to keep the application and the users safe.
An attacker could be able to upload executable code this could allow them to execute operating system commands, read and modify information in the filesystem, access the back end database and fully compromise the server.
Malicious files should be detected and stopped at various points of the application architecture.
The following principles should be followed to reach a secure file upload implementation:
- List allowed extensions. Only allow safe and critical extensions for business functionality
- Ensure that input validation is applied before validating the extensions.
- Validate the file type, don't trust the Content-Type header as it can be spoofed
- Change the filename to something generated by the application
- Set a filename length limit. Restrict the allowed characters if possible
- Set a file size limit
- Only allow authorised users to upload files
- Store the files on a different server. If that's not possible, store them outside of the webroot
- In the case of public access to the files, use a handler that gets mapped to filenames inside the application (someid -> file.ext)
- Run the file through an antivirus or a sandbox if available to validate that it doesn't contain malicious data
- Ensure that any libraries used are securely configured and kept up to date
- Protect the file upload from CSRF attacks
The following code block shows an example of an upload form that does not validate any file types. This code does not contain any validation, and is vulnerable to malicious uploads.
<form action="upload.php" method="POST" enctype="multipart/form-data"> <input type="file" name="userfile"> <input type="submit" value="Upload File"> </form>