TL;DR
The blueimp jQuery File Upload plugin is popular but has known vulnerabilities if not secured correctly on the server-side (PHP). This guide shows you how to protect your uploads directory and prevent malicious file execution.
1. Understand the Risks
Without proper security, attackers can upload dangerous PHP scripts disguised as images or other harmless files. These scripts could then be executed on your server, leading to data breaches, website defacement, or complete system compromise. Common attack vectors include:
- Direct Script Execution: Uploading and executing a malicious PHP file directly.
- File Inclusion Vulnerabilities: Exploiting weaknesses in your application code that allow attackers to include uploaded files.
2. Server-Side Validation is Crucial
Never trust the client-side validation alone! Always validate file uploads on the server using PHP.
2.1 Check File Extension
Verify that the uploaded file has an allowed extension. A simple check:
Important: Don’t rely solely on the extension. Attackers can easily rename files.
2.2 Use mime_content_type()
Check the MIME type of the uploaded file to confirm its actual content type:
Note: mime_content_type() can sometimes be unreliable. Combining it with other checks is best.
2.3 Get Image Dimensions
For images, verify the dimensions to ensure they are valid and not corrupted:
If imagecreate_from_*() fails, the file is likely not a valid image.
3. Secure File Storage
How you store uploaded files significantly impacts security.
3.1 Random Filenames
Rename uploaded files to random strings to prevent attackers from predicting filenames and directly accessing them:
Using uniqid() generates a unique filename.
3.2 Separate Uploads Directory
Store uploaded files in a directory that is *not* directly accessible from the web. This prevents direct execution of any malicious scripts.
- .htaccess: Use an
.htaccessfile to deny access to the uploads directory.
<FilesMatch ".(php|exe|sh|pl)"
Order Allow,Deny
Deny from all
</FilesMatch>
This example blocks access to PHP, EXE, SH and PL files.
3.3 Permissions
Set strict file permissions on the uploads directory (e.g., 755 for the directory and 644 for the files). Avoid making uploaded files writable by the web server user.
4. Disable PHP Execution in Uploads Directory
Even with filename checks, it’s best to prevent PHP execution entirely within the uploads directory.
4.1 Using .htaccess
Add this line to your .htaccess file (in the uploads directory):
Options -ExecCGI
This disables CGI script execution, preventing PHP files from running.
5. Keep blueimp File Upload Updated
Regularly update to the latest version of the blueimp jQuery File Upload plugin to benefit from security patches and bug fixes.