File uploads are a common feature in web applications, but if not handled correctly, they can become a serious security risk. Attackers can exploit weak upload mechanisms to execute malicious code, compromise data, or even take control of a server.
Example Scenario
One of the most dangerous attacks involves uploading a web shell, which is a script that allows remote control over a compromised server. For example, an attacker uploads a PHP file named shell.php with the following content:
<?php system($_GET[‘cmd’]); ?> |
If the server stores and allows execution of this file, an attacker can access it via:
https://example.com/uploads/shell.php?cmd=whoami |
This command runs whoami on the server, revealing the system user running the web server process. Attackers can then execute other commands, potentially gaining access with a reverse shell payload.
Mitigation Strategies
Regardless of the framework or programming language used, the following best practices should be implemented to mitigate file upload vulnerabilities:
- Whitelist Allowed File Types – Only allow specific file types that your application needs. For example, if users should only upload images, restrict uploads to .jpg, .png, and .gif.
- Verify Actual File Content – Attackers can rename files to bypass simple extension checks. Instead of relying solely on file names, verify the file’s magic bytes. For example, .jpeg files typically begin with FFD8.
- Secure File Storage – Store uploaded files outside the web root to prevent direct access and execution.
- Apply strict permissions – Such as preventing execution of scripts in the upload directory. The following example prevents script execution in the upload directory with .htaccess specific to Apache:
<Directory /var/www/uploads> RemoveHandler .php .cgi .pl .py .sh Options -ExecCGI </Directory> |
- Scan Uploaded Files – Use an antivirus scanner such as ClamAV to detect malicious files before processing them.
clamscan –infected –remove –recursive /path/to/uploads |
Conclusion
File upload security should never be an afterthought. By enforcing proper security measures, organizations significantly reduce the risk of exploitation. Always assume that users might try to upload malicious files and implement multiple layers of protection.
However, even with these measures in place, vulnerabilities may go unnoticed. Regular security assessments are crucial to identifying and addressing potential risks. At Hexadius Consulting, our team of experts specialize in testing and validating security defences to ensure comprehensive protection. Get in touch with us to validate and ensure that your systems are secure.
References
https://portswigger.net/web-security/file-upload
https://hacktricks.boitatech.com.br/pentesting-web/file-upload