We're trying to secure our upload forms in PHP regarding image uploads and PDF files. For this purpose, we're currently trying to do the following in all cases, according to our research done so far:
- Check MIME type
- Check file size
- Scan contents for malicious contents
- Upload the validated files into a directory which is non-executable and inaccessible from the web root. For the upload, we validate the filenames according to OWASP's regex recommendation.
When it comes to steps 1 and 2, built-in PHP tools like Symfony's validation package seem to be suitable. Step 4 can generally be executed in plain PHP. The problems we have are two:
- How do you complete step 3; what is considered more secure? File scanning vs File validation? We're wondering as some posts of this forum seemingly recommend to validate file types e.g. for PDF, and also for images, instead of using malware scanner software, e.g. clamav. These command-line tools however also seem to have reported heavy vulnerabilities; so we were wondering; Should you rather go for scanning software or file conversion/validation tools, to try to reduce the risk that your uploaded files hold malicious code? Are there clearly different risk levels or is this rather an opinion-based thing?
- Another thing is that we're also completely clueless about how we're supposed to validate base64-string uploads. Is it safe to
base64_decode()potentially malicious code, to then validate the file as a stream? Or would you rather upload the decoded file into a temporary directory for scanning, or is this too risky? Our experience here is limited, as you may notice.