Mastering File Upload Security: DoS and Antivirus
Tags: webdev, security, fileupload
Published: 2024-03-20 13:45:00

**TL;DR:**

- Mitigate Denial of Service (DoS) threats by imposing restrictions on both the size of files and the quantity of uploads permitted on your server.
- Implement antivirus scanning for files that users download, ensuring protection against malware infections.

## File Upload vulnerabilities and security challenges

Incorporating a file upload feature into your website introduces a spectrum of vulnerabilities that can compromise not only your servers but also the integrity and safety of your users' data.

This article aims to shed light on the critical security challenges associated with file uploads and offers a roadmap to safeguard your digital infrastructure against malicious attacks. We'll explore strategies to prevent attackers from exploiting file upload functionalities to overload and destabilize your servers. Additionally, considering the risks posed when users download files uploaded by others, we emphasize the importance of integrating robust antivirus scanning processes.

<h2 id="DoS-attacks">⚡️ Denial of Service (DoS) attacks</h2>

A **Denial of Service (DoS)** attack is a malicious attempt to **disrupt** the normal **functioning** of a network, service, website, or computer system by overwhelming it with a **flood** of traffic or requests. The primary objective of a DoS attack is to make a target system or network unavailable to its users, thereby denying access to **legitimate** users. In our case, uploading specific files can result in service disruptions for **unsafe** server **configurations**.

Considering a file upload stream what are the possibilities to block the traffic?

- **Voluminous File Upload:** This vulnerability occurs when an attacker uploads an extremely large file, often much larger than what the system is designed to handle. Such a file can consume all available server resources, such as disk space, memory, and processing power, causing the system to slow down or even crash.

![An illustration of a cybersecurity attack: a hooded hacker uses a laptop, sending a large file marked 'DANGER' with an upload arrow to a server, where a red lightning bolt signifies a breach.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/xin6nnxo45tr9usdl4zu.png)

- **Multiple Small File Upload:** In this scenario, an attacker uploads a large number of relatively small files. While individual files may not be large, the cumulative impact can lead to resource depletion or storage space exhaustion.

![An illustration of a cybersecurity attack: a hooded hacker on the left uses a laptop, with arrows leading from him to twelve small documents marked with green upload arrows, then to a server hit by a red lightning bolt, signifying a system breach.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/jrrqj9weydeo025vias2.png)

<h3 id="prevent-DoS">🛡️ How to prevent file upload DoS attacks from happening?</h3>

To deal with these vulnerabilities, it's essential to implement proper security measures in the backend part of your file upload feature. It’s relatively easy and straightforward to do.

- **Set** appropriate file **size limits** to prevent the upload of excessively large files that could overload your system.
- **Set** a **limit** to the **number** of simultaneous files that can be uploaded at the same time.

Here is an elementary Typescript implementation example:

```tsx
const maxFiles = 6;
const maxFileSize = 50 * 1024 * 1024; // 50 MB limit

const uploadedFiles: File[] = req.body.files;
// Assuming 'files' is an array of File objects in the request body

// Check file size and number of files
if (uploadedFiles.length > maxFiles) {
  return res.status(400).json({ error: "Too many files uploaded." });
}

for (const file of uploadedFiles) {
  if (file.size > maxFileSize) {
    return res.status(400).json({ error: "File size exceeds the limit." });
  }
  // Handle the file, e.g., save it to the server
}

return res.status(200).json({ message: "Files uploaded successfully!" });
```

More general tips to prevent any type of DoS attacks are:

- Implementing **rate limiting** for file uploads to prevent the rapid uploading of numerous small files. This helps control the flow of incoming data.
- **IP blocking** → blocking traffic from known or suspected malicious sources to prevent DoS traffic from reaching its target. You can find lists of abusive IPs, for instance on [abuseipdb.com](https://www.abuseipdb.com/)
- Using a **Content Delivery Networks** (CDNs) such as [Cloudflare](https://www.cloudflare.com), can help absorb large amounts of traffic and mitigate the impact of DoS attacks.

### Additional benefits of DoS protection measure: 💰 & 🌱

Using **smaller and fewer files** can bring also other **benefits** to you and the environment.
- With **less quantity** to store on your server, you will have **better performances** and **less to pay** at the end of the month.
- Moreover, less storage usage will **reduce the environmental impact** of manufacturing, operating, and cooling data centers.
- Sending voluminous files is also costly so even though front-end file size validation isn’t enough for security measure it can help to reduce the environmental impact of the uses.

<h3 id="zip-bomb">💣 What is a Zip Bomb? A type of DoS attack</h3>

A **Zip Bomb**, also known as a Zip of Death or decompression bomb, is a **malicious archive file** designed to crash or render useless the program or system reading it. It's a **type of DoS attack**. The concept behind a Zip Bomb is to exploit the file compression algorithm's ability to highly compress a large amount of data. A Zip Bomb file appears small and innocuous but contains an **enormous amount of data when decompressed**.

When a targeted system tries to decompress such a file, it can exhaust system resources due to the disproportionally large size of the decompressed data compared to the compressed file. For example, a Zip Bomb could be a file that is only a few kilobytes in size but expands to several gigabytes or even terabytes when decompressed. This can lead to **system crashes**, slowdowns, or can render the system inoperable, thus achieving the attacker's goal of **denying service** to legitimate users.


![An illustration of a cyber attack sequence: a figure in a purple hood uses a laptop with a skull emblem, symbolizing a hacker. At the center, a yellow folder labeled 'ZIP' with a bomb indicates a malicious 'zip bomb.' To the right, an explosion in front of a cloud and servers shows the zip bomb's impact in a cloud environment.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ckjodf12kq0xy0chwzty.png)



Zip Bombs are not only limited to Zip files; they can be created in any file format that supports compression, such as RAR or 7z. Accepting an archive file is always a delicate matter, and decompressing it on your server even more so. The defense against Zip Bombs involves careful scanning and validation of input files, limiting the maximum size of decompressed data, and using updated antivirus and anti-malware programs capable of detecting such threats.

<h2 id="antivirus-scanning">🕵️‍♂️ Antivirus scanning for user protection</h2>

The purpose of uploading files is very often to share them with other people thus another user is supposed to download the file afterwards. These users can inadvertently become targets of malicious activity when using file upload features on web applications. In many cases, attackers may attempt to exploit the trust of users by uploading files that appear harmless but, in reality, contain malware or other malicious content. This can include infected documents, executables, or scripts. When these files are downloaded and executed on a user's system, it can lead to compromised security and potential data breaches.

If the uploaded files are **retrievable**, to safeguard both your platform and mainly your users, it is **crucial** to run an up-to-date **virus scanner**. Virus scanners are very adept at spotting malicious files masquerading as a different file type, invisible to most unaware users. This proactive measure can **automatically check** each uploaded file for potential threats, helping ensure that users are not unwittingly exposed to malicious content.

Running an antivirus can also help you secure your server, because it can detect potentially malicious files that succeeded in bypassing all your previous security checks.

Before really uploading a file you can **isolate** it and run an antivirus to identify potential threats, then only finally uploading it. This way all potential threats are being **neutralised** before having access to sensitive data.

<h3 id="antivirus-recommendations">⭐️ Recommendations to go beyond simple antivirus scanning</h3>


For maximal safety, you can implement **multi-scanning**. For each file run multiple anti-malware engines, which can be **parallelised**, in order to get the highest detection rate and the shortest window of exposure to malware outbreaks. Here are some reasons:

- Malware can **bypass** a single antivirus engine.
- Different anti-virus vendors have different **response times** to outbreaks due to their location and focused markets.
- **False positives** in virus detection are a common side-effect of any malware scanning solution.

Lastly, if you have to choose between an **Online** and an **Offline** antivirus, you should probably prefer an online solution.

- If you use offline antivirus software, you have to download and install it in your system. While **online** virus scanner does **not require** any **storage space**.
- **Real-time Protection & Regular Updates**: Online antivirus software constantly updates its virus definitions and scans your system in real-time, providing immediate protection against the latest threats. Online antivirus solutions automatically receive updates and patches to keep up with the evolving threat landscape.
- **Cloud-Based**: Online antivirus relies on cloud servers to analyse files and detect malware. This reduces the strain on your computer's resources and can be more efficient since the processing part is usually done on high-speed cloud-based servers.
- **Enhanced Detection**: Online antivirus solutions often use behavioural analysis and machine learning algorithms to identify previously unseen malware, improving their ability to detect new threats.
- **Less Control & Privacy**: Data sent to external servers and no customisation according to personal preferences are the main drawbacks that would make you prefer an offline solution.

My recommendation would be to use [ClamAV](https://www.clamav.net/) an open source antivirus engine. It is a versatile tool designed to detect multiple types of threats from numerous file formats and other use cases (cross-platform, integration such as mail server). Finally, it is updated on a daily basis, ensuring protection against the latest known threats. This rapid update cycle is crucial for an antivirus tool to be effective.

### Setting up AWS antivirus scanning for files in S3 Buckets

You can find a guide on the AWS blog, detailing [how to integrate Amazon S3 Malware Scanning into your web App](https://aws.amazon.com/fr/blogs/apn/integrating-amazon-s3-malware-scanning-into-your-application-workflow-with-cloud-storage-security/). [Amazon Simple Storage Service (Amazon S3)](https://aws.amazon.com/s3/) is a highly scalable object storage service that allows file storage. Currently, when a file is uploaded to an S3 Bucket, two scanning engines are available: **Sophos** and **ClamAV**, to detect malicious ones. Additionally, both engines can be used together for an even higher safety.

<h3 id="asynchronous-scanning">Asynchronous antivirus scanning to enhance performance and UX</h3>


Running an extensive antivirus engine can be quite **time-consuming** thus implementing **asynchronous** antivirus scanning can significantly **enhance** both **performance** and **user experience** in systems that require real-time or near-real-time processing. This approach involves decoupling the scanning process from the main application flow, allowing the application to continue executing without waiting for the scan to complete.

1. When a user uploads a file, the **server immediately acknowledges receipt** and begins the upload process, providing a responsive experience.
2. The file is being **processed in the background**, scanned and uploaded if successful or either deleted or quarantined if not.
3. **Send a status update** on the upload process to the user, such as through email notifications, dashboard updates, or real-time alerts using web sockets.

<h3 id="race-conditions">🏎️ Race conditions applied to file upload</h3>

[Race conditions in cybersecurity](https://portswigger.net/web-security/race-conditions) refer to a scenario where the outcome of a process is unexpectedly altered due to the **timing** of events not happening as planned. This occurs in a concurrent environment where multiple processes or threads execute in **overlapping timeframes**, leading to **conflicts** in accessing or modifying shared resources. The security risk arises when an attacker can **manipulate** the timing of actions to gain unauthorized access or privileges, modify data, or exploit system functionality in unintended ways.

In the context of file upload vulnerabilities, race conditions can be particularly concerning. There are multiple scenarios where the file security checks could be bypassed. Here is one example:

Imagine a web application that allows users to upload files. The application checks the file for security purposes (e.g., ensuring it's not a malicious executable) before moving it to a permanent storage location. A race condition vulnerability could occur if an attacker manages to manipulate the timing of the upload process.

1. **Initial Upload**: The attacker begins by uploading a benign file that passes the application's security checks.
2. **Timing Manipulation**: Right after the initial check but before the file is moved to its permanent location, the attacker quickly replaces the benign file with a malicious one, exploiting the time gap in the process.
3. **Execution of Malicious File**: The application, believing the file to be safe, moves it to permanent storage, from where the attacker can trigger the execution or processing of the malicious file.

This exploitation leverages the race condition to bypass security checks, allowing the upload and execution of potentially harmful files.

![The image depicts a 'Race condition vulnerability' in file uploads. A cloud symbolizes a server with a refresh icon, linked to 'Antivirus Scan' and 'Bucket Upload' boxes. A hooded hacker uses a laptop with a skull, connected by lines to two 'file.pdf' versions: one 'safe' with a green check, the other 'evil' with a purple emoji. A dashed 'frame to override file.pdf' line shows the 'evil' file replacing the 'safe' during upload, highlighting the exploitation of a race condition to insert a malicious file.](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/9ue236e43gm51941ntxg.png)



You can try yourself exploiting a file upload race condition vulnerability, of a different kind, on this [Portswigger’s Lab](https://portswigger.net/web-security/file-upload/lab-file-upload-web-shell-upload-via-race-condition).

## Conclusion:

I hope this article has provided you with a comprehensive understanding of the security challenges associated with file uploads and the strategies to mitigate these risks. By implementing the recommended security measures, you can ensure that your file upload feature is robust, resilient, and secure, protecting your servers and users from potential threats.

If you'd like to find out more about file type validation, take a look at the first article in this series: [Mastering File Upload Security: Understanding File Types](https://dev.to/theodo/mastering-file-upload-security-understanding-file-types-5fd6).