Unmasking file upload vulnerabilities: protecting your system
In this blog, we will unravel the complexities of file upload vulnerabilities, delving into the risks, challenges, and solutions surrounding the security of file uploads.
Chahat Mundra
18th July 2024
File upload and its purpose
File upload is a fundamental feature in web and mobile apps, allowing users to transfer files from their devices to online storage. It bridges the client-side interface and the server-side backend, ensuring the safe and seamless transmission of documents, images, and videos. From a technical standpoint, it’s a foundational component that facilitates tasks like content sharing and document management, making it an essential aspect of modern app development.
Causes of file upload vulnerability
File upload vulnerabilities can arise for various reasons, including inadequate user input validation, incorrect file type checking, insufficient file permissions, or a lack of content validation.
Threat actors can exploit these weaknesses by uploading simple image files containing malicious scripts or viruses or using deceptive file extensions to evade detection. This can result in the execution of server-side scripts that enable remote code execution.
Impact of file upload vulnerability
The impact of file upload vulnerabilities generally depends on two key factors:
Validation failures
The specific aspects of the file that the website fails to validate correctly, such as its size, type, or contents. If these aspects are not checked rigorously, malicious files can be uploaded, leading to security breaches.
Post-upload restrictions
The restrictions imposed on the file once successfully uploaded. If the uploaded file is not correctly restricted, it might execute malicious code, access sensitive data, or disrupt server operations.
File upload flaws are a significant security concern because they can lead to data breaches, unauthorised access to sensitive information, and system compromise.
What can be achieved with different extensions
- Webshell as well as Remote Code execution can be achieved by uploading ASP / ASPX / PHP5 / PHP / PHP
- Stored Cross-site Scripting, SSRF can be achieved by uploading SVG file
- CSV INJECTION can be achieved by uploading CSV files
- XXE can be achieved by uploading XML and SVG files
- LFI as well as SSRF can be achieved through AVI files
- HTML INJECTION, XSS and OPEN REDIRECT can achieve by uploading HTML &JS files
- PIXEL FLOOD ATTACK can happen by uploading PNG or JPEG file
- RCE VIA LFI can be achieved by uploading ZIP file
- SSRF and BLIND XXE can be done by uploading PDF/PPTX
Types of file upload vulnerabilities
1. Path traversal
Path traversal is a type of file upload vulnerability allowing a threat actor to upload a file with a specially crafted filename that includes directory traversal characters (../ or..) to access files outside the intended upload directory. This can result in unauthorised access to sensitive files like configuration, password, or other files containing sensitive information.
In CVE-2023-2825, a flaw in GitLab allowed threat actors to access sensitive files. Threat actors could navigate beyond intended directories by exploiting an arbitrary path traversal issue, potentially extracting data or executing malicious code.
2. File inclusion
File inclusion is a vulnerability that occurs when an application includes a file from a potentially untrusted source, such as user input or a remote server, without proper validation or sanitisation. This can allow a threat actor to manipulate the path to the included file and execute arbitrary code or gain access to sensitive information on the server.
It is sub-classified into Local File inclusion & Remote File inclusion.
This HackerOne report discloses a critical vulnerability found within VMware Instances hosted by the MTN Group. Through the exploitation of specific URLs detailed in the report, threat actors can access sensitive files such as “/etc/passwd” stored on the affected servers. This exposure presents significant risks, potentially enabling malicious individuals to execute arbitrary code on the server, thereby facilitating unauthorised access and executing malicious actions with severe consequences.
3. Remote code execution
Remote Code Execution (RCE) is a vulnerability that permits threat actors to remotely execute code on a target machine. In this example, we’ll explore how RCE can be achieved through file uploads to run arbitrary commands. Initially, when attempting to upload the malicious file named upload.php, the server may reject it, indicating that the “.php” file extension is not allowed. However, this restriction can be bypassed by using double extensions, as demonstrated in the image below:
The system executed the arbitrary command “uname -a” after the successful upload. This command retrieves system information, such as the operating system’s name and version, kernel version, and hardware architecture.
Apache has recently issued an advisory for CVE-2023-50164, a critical vulnerability affecting Apache Struts 2. This vulnerability allows unauthorised path traversal, which could be exploited to upload a malicious file and execute remote code (RCE).
4. Cross-site scripting (XSS)
XSS via Exif data:
Metadata, which comprises contextual information about a file, such as an image, provides essential insights into its characteristics, including timestamps for creation and modification. The metadata manipulation emerges as a powerful technique for initiating Cross-Site Scripting (XSS) payloads. The below image illustrates how the comment can be added to execute XSS.
With tools like ExifTool, users can precisely adjust metadata, enabling the seamless integration of XSS payloads into files.
A vulnerability was identified by a threat actor allowing unrestricted file uploads via the avatar feature on the Shopify website. Additionally, the threat actor found a method to embed malicious code within PNG image files using the ExifTool. This issue has been documented in a HackerOne report.
XSS via filename:
In another example of XSS (Cross-Site Scripting) through file upload, an XSS payload was successfully included as a filename in a .jpg file, as depicted in the snapshot below.
In the snapshot below, there is a popup that displays the cookie value.
The XSS vulnerability arises because the module presents filenames in HTML without any sanitisation on the listing directory page. Consequently, any malicious scripts injected and stored on the server could execute in the client’s browser. This issue has been noted in a HackerOne report.
5. XML Externail Entities via File Upload:
XXE vulnerabilities through file uploads happen when threat actors exploit weaknesses in XML parsers. They embed harmful XML entities within files like SVG or XML, deceiving parsers into processing them. This can lead to data breaches or service disruptions. Threat actors often craft files with XML entities referencing external resources, like local files or remote servers. The XML parser executes the malicious entities when uploaded to a vulnerable web app and processed without validation. This grants threat actors unauthorised access to sensitive data or allows them to execute arbitrary code on the server, posing serious security risks.
A vulnerability was identified in Güralp MAN-EAM-0003 3.2.4’s cgi-bin/xmlstatus.cgi file, allowing XML file uploads to trigger an XML External Entity (XXE) issue. This flaw, classified as CVE-2022-38840, can lead to local file disclosure.
6. SSRF (Server-Side Request Forgery):
This can happen if the server uses the uploaded file to perform tasks such as reading metadata or resizing images, and the file path or URL is not properly sanitised before being used. The threat actor can manipulate the file contents to include a malicious URL that the server will inadvertently access, allowing the threat actor to perform actions on behalf of the server.
A problem in the file upload of imartinez/privategpt version 0.5.0 allows threat actors to send sneaky requests, exploiting a Server-Side Request Forgery (SSRF) vulnerability. By changing the ‘path’ parameter, they can deceive the app into making deceptive requests to internal services like the AWS metadata endpoint, potentially exposing sensitive data and internal servers. The CVE assigned to this is CVE-2024-5186.
7. SQL Injections
Malicious payloads can be utilised as filenames to assess the susceptibility of applications to SQL injections or other server-side injection attacks. When applications inadequately handle uploaded files and process them on the server side, it become vulnerable to such attacks. For instance, an attacker may upload an image file with a basic SQL injection payload as a filename, such as ‘OR 1=1;–.jpg, which always evaluates to true and retrieves data.
Security researcher Eugene Lim uncovered a significant SQL injection flaw within Starbucks systems. He exploited this flaw by sending XML-formatted HTTP requests with encoded single quotes to servers running Microsoft Dynamics AX, Starbucks’ financial software. This vulnerability allowed unauthorised access to Starbucks’ accounting database, potentially compromising sensitive financial data like payroll information.
8. Zipslip Attack
Zip Slip is a security flaw that affects archive extraction processes, allowing a threat actor to write arbitrary files to arbitrary locations on the filesystem by exploiting insufficient validation of file paths within a compressed archive.
A malicious file can be crafted using tools like evilarc.
Grzegorz Niedziela (gregxsunday) previously identified the ZipSlip and TarSlip vulnerabilities within Discourse. These vulnerabilities involve the extraction of files from archives without proper validation. Niedziela’s findings highlighted critical areas within libraries such as Gem::Package::TarReader, Zip::File, and Zlib::GzipReader. Additionally, he noted the use of the FileSystemAccess class for file creation, with mitigation strategies focusing on string comparison and File.expand_path for sanitisation. This discovery aligns with the known CVE-2022-36066 and findings reported on HackerOne.
9. Pixel Flood Attack:
A pixel flood attack entails the threat actor using a script or a tool to flood the website with too many image requests. The requested images can be smaller in pixels and sizes. Unfortunately, the high volume of queries could overburden the server, resulting in a crash or making it unusable.
Another method of launching a Pixel Flood Attack is to change the image’s pixels and see how the web application responds to that file & confirm whether the application is responsive or not.
The Jimp module, used for image processing, is vulnerable to memory exhaustion if EXIF data is manipulated. An attacker can craft an image with exaggerated dimensions (e.g., 64250×64250 pixels), causing Jimp to allocate excessive memory and crash. This vulnerability, detailed in HackerOne report #842462 and assigned CVE-2020-8175, can be replicated by installing Jimp, downloading the crafted image and executing the provided PoC code provided in the report.
Why it’s essential to look for securing file upload features
When files are not uploaded securely, applications can be jeopardised. Threat actors frequently begin by inserting code into the target application. After loading the code, the threat actor will find a way to run their intended action.
Unrestricted file uploads can lead to system/server takeover, file system and database overload, forwarding attacks to backend systems, and even defacement. This is determined by how the application handles uploaded files and where the files are stored.
Prevention
To prevent file upload vulnerabilities, web application developers and system administrators must implement proper security measures such as input validation, file type checking, content validation, and file permission settings. Regular security testing and auditing can also assist in identifying and correcting any vulnerabilities.
File Type Validation
Permit only specific file types essential for the application, such as `.jpg`, `.png`, and `.pdf`. This minimises the risk of malicious files being uploaded. Verify the MIME type of the uploaded files to ensure they match the expected file types, adding an extra layer of security.
File Name Sanitisation
Remove any special characters that could be used for path traversal or command injection attacks. Rename uploaded files using a unique, random string to avoid name collisions and obscure the original file name.
File Size Restrictions
Limit the size of uploaded files to prevent denial-of-service (DoS) attacks and resource exhaustion. Ensure the Content-Length header matches the expected file size to avoid incomplete or oversized uploads.
Content Scanning
Integrate antivirus software to scan uploaded files for malware and viruses, protecting the application from harmful content. Use known malware signatures and heuristic analysis to detect and block malicious files.
Directory Management
Store uploaded files in a dedicated directory with restricted permissions to limit the impact of potential breaches. Configure the server to prevent file execution in the upload directory (e.g., disable script execution for Apache/Nginx).
Access Control
Set directory and file permissions to ensure only authorised users can upload and access the upload directory. Users are required to authenticate and verify their permissions before file uploads are allowed.
Path Validation
Normalise the file path to prevent path traversal attacks by resolving any `.` and `..` sequences. Ensure the upload path always remains within the designated upload directory.
File Content Validation
Inspect the file header (magic number) to verify the content matches the expected file type. Enforce additional restrictions based on the file type, such as image dimensions and resolution for image files.
Conclusion
By implementing these recommendations, developers and administrators can enhance the security of their web applications when handling file uploads. They can achieve this by incorporating strict protocols for handling files, such as thorough validation of user inputs, meticulous verification of file types, and comprehensive scrutiny of file contents to ensure that only authorised and safe files are processed. Additionally, employing techniques like sanitising file names, imposing size limits, and conducting antivirus scans adds extra layers of protection against potential threats. Organisations can effectively reduce the risk of exploitation by enforcing robust access controls, normalising file paths, and validating file contents.