File Upload Mitigations

Its best practice to implement all of these prevention mechanisms and also use other various detection solutions.

Don't let uploads execute code:

We would want to ensure all uploaded files written to disk do not get an execute permission set. Separating the uploads into their own partition or directory can also help to manage the permissions and lock down any future accidental edits that might lift permissions. Also renaming the files to mitigate any file naming trickery, and only allowing the files and server sided languages to be installed that you need for the webapp to function.

//This py example will save uploads without an execute flag
import os
file_descriptor = os.open("/path/to/file", os.O_WRONLY | os.O_CREAT, 0o600)
with os.fdopen(open(file_discriptor, "wb")) as file_handle:
    file_handle.write(...)

Another option would be utilizing CDN providers or cloud bucket storage solutions which can manage the security concerns of file uploads for you along with the other non-security added benefits of using these. Many CDNs will also offer file upload widgets that you can inject into your site to make the whole development process even smoother.

Analyze uploads:

If you are only expecting a certain type of file inspect both the file extension and the magic bytes to ensure the file is what it claims to be. Also verify the Content-Type header is the expected data type. Once saved as a non executable file on disk there are various system commands that can again check the file to ensure its legitimate. In linux the file <filename> command can do just that. And in python imghdr.what('file.gif') can be used.

Attackers can spoof even the system based file checks so its important to use multiple layers of defense here.

EDR and AV:

Keep updates rolling in and ensure response and mitigation teams are managing this area to things.

Last updated