# File Upload Mitigations

{% hint style="danger" %}
Its best practice to implement all of these prevention mechanisms and also use other various detection solutions.&#x20;
{% endhint %}

### 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.&#x20;

{% tabs %}
{% tab title="Python" %}

```python
//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(...)
```

{% endtab %}
{% endtabs %}

\
\
Another option would be utilizing [CDN](/glossary.md#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.&#x20;

{% hint style="danger" %}
Attackers can spoof even the system based file checks so its important to use multiple layers of defense here.&#x20;
{% endhint %}

### EDR and AV:

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


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://www.hackbook.io/web-application-hacking/web-techniques/file-uploads/file-upload-mitigations.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
