02 Mar, 2023

Failure to Restrict File Uploads

Vulnerability Assessment as a Service (VAaaS)

Tests systems and applications for vulnerabilities to address weaknesses.

Failure to Restrict File Uploads refers to a security vulnerability in a web application where the application fails to properly limit the type, size, or number of files that can be uploaded by users. This can potentially allow malicious files, such as malware or scripts, to be uploaded and executed on the server, leading to a range of security issues, including data breaches, server compromise, and denial of service attacks.

Example of vulnerable code on different programming languages:


in PHP

A common mistake is to use the $_FILES global variable to directly access the uploaded file without performing any validation. Here is an example:

				
					<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);

if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
    echo "The file ". htmlspecialchars( basename( $_FILES["fileToUpload"]["name"])). " has been uploaded.";
} else {
    echo "Sorry, there was an error uploading your file.";
}
?>

				
			


In this example, there is no validation of the file type, size, or number of files uploaded. This leaves the application vulnerable to attacks where an attacker can upload malicious files to the server.

in Ruby on Rails

A common mistake is to use the params[:file] parameter to directly access the uploaded file without performing any validation. Here is an example:

				
					class UploadController < ApplicationController
  def index
    if request.post?
      uploaded_io = params[:file]
      File.open(Rails.root.join('public', 'uploads', uploaded_io.original_filename), 'wb') do |file|
        file.write(uploaded_io.read)
      end
    end
  end
end

				
			


In this example, there is no validation of the file type, size, or number of files uploaded. This leaves the application vulnerable to attacks where an attacker can upload malicious files to the server.

in Node.js

A common mistake is to use the fs module to write uploaded files to the server without performing any validation. Here is an example:

				
					const express = require('express');
const fileUpload = require('express-fileupload');
const app = express();

app.use(fileUpload());

app.post('/upload', function(req, res) {
  if (!req.files || Object.keys(req.files).length === 0) {
    return res.status(400).send('No files were uploaded.');
  }

  let uploadedFile = req.files.file;
  let fileName = uploadedFile.name;
  let filePath = __dirname + '/uploads/' + fileName;

  uploadedFile.mv(filePath, function(err) {
    if (err) {
      return res.status(500).send(err);
    }

    res.send('File ' + fileName + ' uploaded!');
  });
});

				
			


In this example, there is no validation of the file type, size, or number of files uploaded. This leaves the application vulnerable to attacks where an attacker can upload malicious files to the server.

• in C#

In C#, a common mistake is to use the HttpPostedFile class to directly access the uploaded file without performing any validation. Here is an example:

				
					using System;
using System.IO;
using System.Web;
using System.Web.UI;

public partial class Upload : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack)
        {
            HttpPostedFile file = Request.Files["file"];
            if (file != null && file.ContentLength > 0)
            {
                string fileName = Path.GetFileName(file.FileName);
                string path = Server.MapPath("~/uploads/") + fileName;
                file.SaveAs(path);
                StatusLabel.Text = "File " + fileName + " uploaded successfully!";
            }
        }
    }
}

				
			


In this example, there is no validation of the file type, size, or number of files uploaded. This leaves the application vulnerable to attacks where an attacker can upload malicious files to the server.

Examples of exploitation Failure to Restrict File Uploads

Uploading a malicious script

An attacker can upload a malicious script disguised as an image, PDF, or any other file format. Once the script is uploaded, the attacker can execute it on the server and gain access to sensitive information or take control of the server. For example, the attacker can upload a PHP script with a .jpg extension that, when executed on the server, opens a backdoor for the attacker to execute arbitrary code.

Denial-of-Service (DoS) attacks

An attacker can upload large files to the server, causing it to crash or become unresponsive. This can lead to a DoS attack, where legitimate users are unable to access the server. For example, an attacker can upload a large video file that consumes all available disk space on the server.

Cross-Site Scripting (XSS)

An attacker can upload a file that contains malicious code, such as JavaScript, and then trick a user into downloading and executing the file. This can lead to a Cross-Site Scripting (XSS) attack, where the attacker can steal user credentials or inject malicious code into the user’s browser. For example, the attacker can upload a file that contains JavaScript code that steals user cookies and sends them to the attacker’s server.

Remote Code Execution (RCE)

An attacker can upload a file that contains malicious code that allows them to execute commands on the server. This can lead to a Remote Code Execution (RCE) attack, where the attacker can take complete control of the server. For example, an attacker can upload a file that contains a command injection payload that, when executed, allows the attacker to execute arbitrary commands on the server.

Privilege escalation techniques for Failure to Restrict File Uploads

Uploading a web shell

An attacker can upload a web shell, which is a script that allows them to execute arbitrary code on the server. Once the web shell is uploaded, the attacker can use it to escalate privileges by executing commands as a higher privileged user. For example, the attacker can upload a web shell that allows them to execute commands as the root user.

Exploiting a vulnerability in a web application

An attacker can use a file upload vulnerability to upload a file that contains a web application exploit. The exploit can be used to escalate privileges by taking advantage of a vulnerability in the web application. For example, the attacker can upload a file that contains a PHP exploit, which allows them to execute arbitrary code as the web server user.

Abusing file permissions

An attacker can use a file upload vulnerability to upload a file with incorrect file permissions. For example, the attacker can upload a file that is executable by everyone, including the root user. Once the file is executed, the attacker can escalate privileges by executing commands as the root user.

Uploading a malicious plugin or extension

An attacker can upload a malicious plugin or extension that adds functionality to the web application. The plugin or extension can be designed to escalate privileges by taking advantage of a vulnerability in the web application. For example, the attacker can upload a malicious plugin that allows them to execute arbitrary code as the web server user.

General methodology and checklist for Failure to Restrict File Uploads

Methodology:

  1. Identify the file upload functionality: The first step is to identify the file upload functionality in the application. This can be done by inspecting the source code, reviewing the application’s functionality, or using a web proxy tool to intercept requests.

  2. Test for allowed file types: Check the application’s allowed file types and ensure that only authorized file types are permitted for upload. Attempt to upload different file types, such as executables, scripts, or other potentially harmful files, and see if the application rejects them.

  3. Test for file size restrictions: Check if the application has file size restrictions and ensure that they are being enforced. Attempt to upload files that exceed the allowed file size and see if the application rejects them.

  4. Test for server-side validation: Check if the application is performing server-side validation of the uploaded files. Attempt to upload files that contain invalid content, such as files with incorrect extensions or files with incorrect headers, and see if the application rejects them.

  5. Test for client-side validation: Check if the application is performing client-side validation of the uploaded files. Attempt to bypass client-side validation by modifying the client-side code or by using a tool to manipulate the HTTP request.

  6. Test for filename manipulation: Check if the application is performing filename manipulation on the uploaded files. Attempt to upload files with special characters or with a long filename to see if the application is performing proper sanitization.

  7. Test for security misconfigurations: Check if there are any security misconfigurations in the application that could allow an attacker to bypass file upload restrictions. This can include directory traversal, weak permissions on uploaded files, or other misconfigurations.

  8. Test for privilege escalation: Test for privilege escalation by attempting to upload a file that can be used to escalate privileges, such as a web shell or a malicious plugin.

Checklist:

  1. Check if the file upload functionality exists in the application.

  2. Check if the application has restrictions on the allowed file types that can be uploaded.

  3. Check if the application has restrictions on the file size that can be uploaded.

  4. Check if the application performs server-side validation on the uploaded files.

  5. Check if the application performs client-side validation on the uploaded files.

  6. Check if the application performs filename manipulation on the uploaded files.

  7. Check if the application has proper permissions on uploaded files.

  8. Check if the application stores uploaded files in a safe and secure location.

  9. Check if the application has appropriate security controls, such as authentication and access controls, for accessing uploaded files.

  10. Check if the application has security misconfigurations, such as directory traversal, that could allow an attacker to bypass file upload restrictions.

  11. Test for privilege escalation by attempting to upload a file that can be used to escalate privileges, such as a web shell or a malicious plugin.

  12. Document all findings and provide recommendations for mitigating the identified vulnerabilities.

Tools set for exploiting Failure to Restrict File Uploads

Manual Tools:

  • Burp Suite – A popular web application testing tool that includes a file upload interceptor and various other tools for analyzing web traffic.

  • OWASP ZAP – A free and open-source web application security scanner that includes a file upload scanner and other vulnerability testing tools.

  • Fiddler – A web debugging proxy tool that can intercept HTTP and HTTPS traffic, including file uploads.

  • Tamper Data – A browser plugin for Firefox that allows users to intercept and modify HTTP requests, including file uploads.

  • Inspect Element – A built-in browser tool that allows users to inspect and modify HTML, CSS, and JavaScript code, including file upload functionality.

Automated Tools:

  • Nessus – A vulnerability scanner that includes a plugin for identifying Failure to Restrict File Uploads vulnerabilities.

  • Acunetix – A web application security scanner that includes a file upload scanner and other vulnerability testing tools.

  • Netsparker – A web application security scanner that includes a file upload scanner and other vulnerability testing tools.

  • Qualys – A cloud-based vulnerability management tool that includes a plugin for identifying Failure to Restrict File Uploads vulnerabilities.

  • Nikto – A web server scanner that includes a plugin for identifying Failure to Restrict File Uploads vulnerabilities.

  • Skipfish – A web application security scanner that includes a file upload scanner and other vulnerability testing tools.

  • Wapiti – A web application security scanner that includes a file upload scanner and other vulnerability testing tools.

  • Vega – An open-source web application scanner that includes a file upload scanner and other vulnerability testing tools.

  • Metasploit Framework – An open-source penetration testing tool that includes a module for exploiting Failure to Restrict File Uploads vulnerabilities.

  • OWASP Amass – An open-source network mapping and vulnerability scanning tool that includes a plugin for identifying Failure to Restrict File Uploads vulnerabilities.

Browser Plugins:

  • Chrome DevTools – A built-in tool in Google Chrome that allows users to inspect and modify HTML, CSS, and JavaScript code, including file upload functionality.

  • Firefox Developer Tools – A built-in tool in Firefox that allows users to inspect and modify HTML, CSS, and JavaScript code, including file upload functionality.

  • Tamper Chrome – A browser extension for Google Chrome that allows users to intercept and modify HTTP requests, including file uploads.

  • HackBar – A browser extension for Firefox that allows users to intercept and modify HTTP requests, including file uploads.

  • Requestly – A browser extension for Chrome, Firefox, and Edge that allows users to modify HTTP requests, including file uploads.

Average CVSS score of stack Failure to Restrict File Uploads

The Common Vulnerability Scoring System (CVSS) is a framework for assessing the severity of security vulnerabilities. The CVSS score ranges from 0 to 10, with 10 being the most severe. The score is based on a number of factors, including the impact on confidentiality, integrity, and availability of the system.

The CVSS score for Failure to Restrict File Uploads vulnerabilities can vary widely depending on the specific implementation and the severity of the impact. However, in general, these vulnerabilities can be considered high-severity vulnerabilities with a CVSS score of 7.0 or higher.

According to the National Vulnerability Database (NVD), the average CVSS score for Failure to Restrict File Uploads vulnerabilities in the past 5 years (as of 2023) is around 8.5, which is considered a critical severity level. This indicates that Failure to Restrict File Uploads is a serious vulnerability that can have a significant impact on the security of a web application.

The Common Weakness Enumeration (CWE)

• CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE is related to uploading a file without checking its type, which can lead to the upload of malicious files such as executable files, scripts, and other types of files that can harm the system.

• CWE-400: Uncontrolled Resource Consumption – This CWE is related to uploading large files or uploading a large number of files, which can consume excessive resources and cause denial of service attacks.

• CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE is related to uploading a file without checking its type, which can lead to the upload of malicious files such as executable files, scripts, and other types of files that can harm the system.

• CWE-352: Cross-Site Request Forgery (CSRF) – This CWE is related to uploading a file through a malicious website that takes advantage of an authenticated user’s credentials to perform unauthorized actions.

• CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE is related to uploading a file without checking its type, which can lead to the upload of malicious files such as executable files, scripts, and other types of files that can harm the system.

• CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE is related to uploading a file without checking its type, which can lead to the upload of malicious files such as executable files, scripts, and other types of files that can harm the system.

• CWE-444: Inconsistent Interpretation of HTTP Requests (‘HTTP Request Smuggling’) – This CWE is related to uploading a file using HTTP Request Smuggling techniques, which can bypass security controls and perform unauthorized actions.

• CWE-522: Insufficiently Protected Credentials – This CWE is related to uploading a file that contains sensitive information such as passwords or authentication tokens, which can be accessed by attackers and used for malicious purposes.

• CWE-434: Unrestricted Upload of File with Dangerous Type – This CWE is related to uploading a file without checking its type, which can lead to the upload of malicious files such as executable files, scripts, and other types of files that can harm the system.

• CWE-400: Uncontrolled Resource Consumption – This CWE is related to uploading large files or uploading a large number of files, which can consume excessive resources and cause denial of service attacks.

Top 10 CVES related to Failure to Restrict File Uploads

• CVE-2019-16114 – In ATutor 2.2.4, an unauthenticated attacker can change the application settings and force it to use his crafted database, which allows him to gain access to the application. Next, he can change the directory that the application uploads files to, which allows him to achieve remote code execution. This occurs because install/include/header.php does not restrict certain changes (to db_host, db_login, db_password, and content_dir) within install/include/step5.php.

• CVE-2018-1306 – The PortletV3AnnotatedDemo Multipart Portlet war file code provided in Apache Pluto version 3.0.0 could allow a remote attacker to obtain sensitive information, caused by the failure to restrict path information provided during a file upload. An attacker could exploit this vulnerability to obtain configuration data and other sensitive information.

• CVE-2018-1000627 – Battelle V2I Hub 2.5.1 could allow a remote attacker to obtain sensitive information, caused by the failure to restrict access to the API key file. An attacker could exploit this vulnerability to obtain the current API key to gain unauthorized access to the system.

• CVE-2017-18229 – An issue was discovered in GraphicsMagick 1.3.26. An allocation failure vulnerability was found in the function ReadTIFFImage in coders/tiff.c, which allows attackers to cause a denial of service via a crafted file, because file size is not properly used to restrict scanline, strip, and tile allocations.

• CVE-2017-16787 – The Web Configuration Utility in Meinberg LANTIME devices with firmware before 6.24.004 allows remote attackers to read arbitrary files by leveraging failure to restrict URL access.

• CVE-2017-11357 – Progress Telerik UI for ASP.NET AJAX before R2 2017 SP2 does not properly restrict user input to RadAsyncUpload, which allows remote attackers to perform arbitrary file uploads or execute arbitrary code.

• CVE-2016-5661 – Accela Civic Platform Citizen Access portal relies on the client to restrict file types for uploads, which allows remote authenticated users to execute arbitrary code via modified _EventArgument and filename parameters.

• CVE-2013-6737 – IBM System Storage Storwize V7000 Unified 1.3.x and 1.4.x before 1.4.3.0 does not properly restrict the content of a dump file upon encountering a 1691 hardware fault, which allows remote authenticated users to obtain sensitive customer-data fragments by reading this file after it is copied.

• CVE-2013-5465 – IBM Maximo Asset Management 7.x before 7.1.1.7 LAFIX.20140319-0837, 7.1.1.11 before IFIX.20140323-0749, 7.1.1.12 before IFIX.20140321-1336, 7.5.x before 7.5.0.3 IFIX027, and 7.5.0.4 before IFIX011; SmartCloud Control Desk 7.x before 7.5.0.3 and 7.5.1.x before 7.5.1.2; and Tivoli IT Asset Management for IT, Tivoli Service Request Manager, Maximo Service Desk, and Change and Configuration Management Database (CCMDB) 7.x before 7.1.1.7 LAFIX.20140319-0837, 7.1.1.11 before IFIX.20140207-1801, and 7.1.1.12 before IFIX.20140218-1510 do not properly restrict file types during uploads, which allows remote authenticated users to have an unspecified impact via an invalid type.

• CVE-2011-2933 – An Arbitrary File Upload vulnerability exists in admin/media/upload.php in WebsiteBaker 2.8.1 and earlier due to a failure to restrict uploaded files with .htaccess, .php4, .php5, and .phtl extensions.

Failure to Restrict File Uploads exploits

  • File Upload XSS: Attackers can upload a file containing malicious code, such as a JavaScript file or a Flash object, and trick users into downloading and executing it, which can lead to a cross-site scripting (XSS) attack.

  • Remote Code Execution: Attackers can upload a file containing malicious code that can be executed on the server, which can lead to remote code execution (RCE) and compromise the system.

  • Malware Delivery: Attackers can upload a file containing malware, such as a Trojan or a virus, and trick users into downloading and executing it, which can lead to a malware infection.

  • Server-Side Request Forgery (SSRF): Attackers can upload a file containing a URL that points to an internal resource on the server, which can be used to perform server-side request forgery (SSRF) attacks.

  • Authentication Bypass: Attackers can upload a file containing a bypass script, which can bypass authentication checks and grant unauthorized access to the system.

  • Denial of Service (DoS): Attackers can upload a file containing large amounts of data, which can consume excessive resources and cause a denial of service (DoS) attack.

  • Path Traversal: Attackers can upload a file with a specially crafted filename that includes path traversal characters, which can allow them to access files outside of the upload directory and gain unauthorized access to sensitive files.

  • Shell Upload: Attackers can upload a file containing a shell script, which can be executed on the server and give them command-line access to the system.

  • File Inclusion: Attackers can upload a file containing code that can be included in other parts of the system, which can allow them to execute arbitrary code and gain unauthorized access.

  • SQL Injection: Attackers can upload a file containing SQL injection code, which can be executed on the server and compromise the database, leading to unauthorized access to sensitive information.

Practicing in test for Failure to Restrict File Uploads

Create a test web application: that allows users to upload files and test different scenarios, such as uploading different file types, attempting to bypass file type restrictions, and attempting to upload large files.

Use a vulnerable web application: such as DVWA or Mutillidae, to practice exploiting file upload vulnerabilities.

Use a penetration testing lab: such as HackTheBox or TryHackMe, to practice exploiting file upload vulnerabilities in a controlled environment.

Participate in CTF challenges: that focus on web application security to practice identifying and exploiting file upload vulnerabilities.

Use automated tools: such as Burp Suite or OWASP ZAP, to scan for file upload vulnerabilities and practice exploiting them.

For study Failure to Restrict File Uploads

Read about the OWASP Top 10: The OWASP Top 10 is a list of the most critical web application security risks, and Failure to Restrict File Uploads is one of them. Read about the different vulnerabilities and learn how to test for them.

Learn about file upload restrictions: Study different file upload restrictions, such as file size, file type, and file extension, and learn how to bypass them.

Practice testing: Practice testing for file upload vulnerabilities by creating a test web application, using a vulnerable web application, using a penetration testing lab, participating in CTF challenges, and using automated tools.

Study real-world examples: Look up real-world examples of file upload vulnerabilities and learn how they were exploited.

Study the underlying technologies: Study the underlying technologies used in web application development, such as HTTP, HTML, and JavaScript, to better understand how file upload vulnerabilities can occur.

Take online courses: Take online courses on web application security, such as those offered by Udemy, Coursera, or SANS, to learn more about Failure to Restrict File Uploads and other web application security risks.

Books with review of Failure to Restrict File Uploads

Web Application Security: A Beginner’s Guide by Bryan Sullivan and Vincent Liu – This book provides an introduction to web application security, including Failure to Restrict File Uploads, with clear explanations and real-world examples.

The Web Application Hacker’s Handbook: Finding and Exploiting Security Flaws by Dafydd Stuttard and Marcus Pinto – This book covers a wide range of web application security topics, including Failure to Restrict File Uploads, with practical guidance and in-depth explanations.

Hacking Web Applications: The Art of Hacking Series, Security Penetration Testing for Today’s DevOps and Cloud Environments by Mike Shema – This book provides an overview of web application security, including Failure to Restrict File Uploads, with practical guidance and hands-on exercises.

The Tangled Web: A Guide to Securing Modern Web Applications by Michal Zalewski – This book covers a variety of web application security topics, including Failure to Restrict File Uploads, with a focus on the underlying technologies and the challenges of securing modern web applications.

Real-World Bug Hunting: A Field Guide to Web Hacking by Peter Yaworski – This book provides a practical guide to finding and exploiting web application vulnerabilities, including Failure to Restrict File Uploads, with real-world examples and practical exercises.

Web Hacking 101: How to Make Money Hacking Ethically by Peter Yaworski – This book provides an introduction to web application hacking, including Failure to Restrict File Uploads, with practical guidance and real-world examples.

OWASP Testing Guide v4.0 by The Open Web Application Security Project – This guide provides a comprehensive overview of web application security testing, including Failure to Restrict File Uploads, with practical guidance and detailed explanations.

Black Hat Python: Python Programming for Hackers and Pentesters by Justin Seitz – This book provides an introduction to Python programming for security professionals, including practical examples of exploiting web application vulnerabilities, including Failure to Restrict File Uploads.

Hands-On Bug Hunting for Penetration Testers: A Practical Guide to Help Ethical Hackers Discover Web Application Security Flaws by Joseph Marshall – This book provides a practical guide to finding and exploiting web application vulnerabilities, including Failure to Restrict File Uploads, with real-world examples and hands-on exercises.

The Basics of Web Hacking: Tools and Techniques to Attack the Web by Josh Pauli – This book provides an introduction to web application security, including Failure to Restrict File Uploads, with practical guidance and step-by-step instructions.

List of payloads Failure to Restrict File Uploads

  1. Shell commands as file names: <?php system($_GET['cmd']); ?> saved as file.php%00.jpg

  2. Uploading files with double extensions: file.php.jpg or file.php.gif

  3. Uploading files with no extension: file.php or file

  4. Uploading files with invalid extensions: file.php%00.jpg or file.php;.jpg

  5. Uploading files with null byte: file.php%00.jpg

  6. Uploading files with malicious content: <?php echo "Hello world!"; ?>

  7. Uploading files with PHP code embedded in images: <?php echo "Hello world!"; ?> saved as file.jpg.php

  8. Uploading files with shell commands in metadata: exiftool -Comment='<?php echo shell_exec($_GET['cmd']); ?>' image.jpg

  9. Uploading files with PHP code in metadata: exiftool -Comment='<?php echo "Hello world!"; ?>' image.jpg

  10. Uploading files with large file sizes to cause denial of service: dd if=/dev/zero of=file bs=1M count=10000 (creates a 10GB file)

How to be protected from Failure to Restrict File Uploads

  1. Use server-side validation to restrict file types and file sizes.

  2. Use a file upload library that is designed to handle uploaded files securely.

  3. Rename uploaded files to a unique name or hash to prevent malicious files from being executed.

  4. Use Content-Disposition header to enforce that the uploaded files should not be treated as executable.

  5. Use a Content Security Policy (CSP) to restrict where the files can be uploaded from and executed.

  6. Sanitize file names and metadata to remove potentially malicious content.

  7. Use file system permissions to restrict access to uploaded files and directories.

  8. Use anti-virus software to scan uploaded files for viruses and malware.

  9. Use web application firewalls (WAFs) to detect and block attacks.

  10. Keep all software and plugins up to date with the latest security patches to prevent known vulnerabilities from being exploited.

Conclusion

Failure to Restrict File Uploads is a serious vulnerability that can lead to arbitrary code execution on the server, privilege escalation, and data leakage. It occurs when a web application fails to properly validate and restrict the types, sizes, and contents of files that are uploaded by users. Attackers can exploit this vulnerability by uploading malicious files that can be executed by the server, bypassing security measures and gaining unauthorized access to sensitive information.

To mitigate the risk of Failure to Restrict File Uploads vulnerabilities, web developers should use a combination of techniques such as server-side validation, file upload libraries, renaming uploaded files, using Content-Disposition headers, Content Security Policies, and sanitizing file names and metadata. File system permissions, anti-virus software, web application firewalls, and keeping software up-to-date with security patches can also help reduce the risk of this type of vulnerability.

Web application security testing should include thorough testing for Failure to Restrict File Uploads vulnerabilities to identify any weaknesses in the application’s file upload functionality. It is important for web developers to stay up-to-date with the latest security trends, best practices, and techniques to protect against this and other types of web application vulnerabilities.

Other Services

Ready to secure?

Let's get in touch