CWE-434: Unrestricted Upload of File with Dangerous Type

Learn about CWE-434 (Unrestricted Upload of File with Dangerous Type), its security impact, exploitation methods, and prevention guidelines.

What is Unrestricted Upload of File with Dangerous Type?

• Overview: This vulnerability occurs when a software application allows users to upload files without properly checking or restricting the file types. As a result, files with potentially dangerous content, such as scripts or executables, can be uploaded and executed on the server.

• Exploitation Methods:

  • Attackers can exploit this vulnerability by uploading files containing malicious scripts or executables that the server automatically processes.
  • Common attack patterns include uploading web shells, scripts that execute server commands, or files that exploit other vulnerabilities within the application.

• Security Impact:

  • Direct consequences of successful exploitation include unauthorized access to server resources, execution of arbitrary code, and potential data breaches.
  • Potential cascading effects include compromise of the entire server environment, spread of malware, and defacement of the application.
  • Business impact can involve loss of customer trust, legal liabilities, and financial loss due to downtime or breach recovery efforts.

• Prevention Guidelines:

  • Specific code-level fixes include implementing strict file type validation and verifying file contents against a whitelist of allowed MIME types and extensions.
  • Security best practices involve using a separate directory with limited permissions for file uploads, and avoiding executing files from upload directories.
  • Recommended tools and frameworks include using libraries or built-in functions that safely handle file uploads and security frameworks that provide additional layers of protection.
Corgea can automatically detect and fix Unrestricted Upload of File with Dangerous Type in your codebase. [Try Corgea free today](https://corgea.app).

Technical Details

Likelihood of Exploit: Medium

Affected Languages: ASP.NET, PHP, Not Language-Specific

Affected Technologies: Web Server

Vulnerable Code Example

ASP.NET Example

// FileUploadController.cs
using System.IO;
using System.Web;
using System.Web.Mvc;

public class FileUploadController : Controller
{
    // This method allows unrestricted file uploads, creating a security risk
    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            var fileName = Path.GetFileName(file.FileName);
            var path = Path.Combine(Server.MapPath("~/Uploads"), fileName);
            file.SaveAs(path);
        }
        return RedirectToAction("Index");
    }
}

Explanation:

  • File Type Validation: The code does not restrict the types of files that can be uploaded, allowing potentially dangerous files to be executed on the server.
  • File Name Handling: Files are saved directly with their original names without any validation or sanitization, making the application vulnerable to directory traversal attacks.
  • Secure Storage: Files are stored in a directory that may have execute permissions, which can be exploited if a dangerous file type is uploaded.

How to fix Unrestricted Upload of File with Dangerous Type?

To fix the vulnerability, we need to implement the following security measures:

  1. File Type Validation: Restrict uploads to only allow specific, safe file types by checking the file extension against a whitelist.
  2. File Name Sanitization: Generate a safe file name to prevent directory traversal attacks.
  3. Use Secure Storage Paths: Store uploaded files in a location that does not have execute permissions, reducing the risk of execution.
  4. Limit File Size: Implement file size restrictions to prevent denial-of-service attacks.
  5. Content-Type Validation: Validate the MIME type of the file to ensure it matches the expected content.

Fixed Code Example

// FileUploadController.cs
using System.IO;
using System.Web;
using System.Web.Mvc;
using System.Linq;

public class FileUploadController : Controller
{
    // Secure file upload method with proper validation and restrictions
    [HttpPost]
    public ActionResult Upload(HttpPostedFileBase file)
    {
        if (file != null && file.ContentLength > 0)
        {
            // Define allowed file extensions
            var allowedExtensions = new[] { ".jpg", ".png", ".txt", ".pdf" };
            
            // Get the file extension
            var fileExtension = Path.GetExtension(file.FileName).ToLowerInvariant();
            
            // Check if the file extension is allowed
            if (!allowedExtensions.Contains(fileExtension))
            {
                ModelState.AddModelError("File", "Invalid file type.");
                return View("Index");
            }

            // Sanitize file name and save it in a secure path
            var safeFileName = Path.GetRandomFileName() + fileExtension;
            var path = Path.Combine(Server.MapPath("~/SecureUploads"), safeFileName);

            file.SaveAs(path);
        }
        return RedirectToAction("Index");
    }
}

Explanation:

  • File Type Validation: A whitelist of allowed file extensions is defined to limit uploads to known safe types.
  • File Extension Check: The file's extension is validated against the allowed list to prevent uploading dangerous file types.
  • File Name Generation: A random file name is generated to prevent directory traversal attacks and sanitize the file name.
  • Secure Storage: Files are saved in a directory (SecureUploads) that does not have execute permissions, reducing execution risks.
  • File Handling: The file is saved securely after passing all validations, ensuring the application is protected against potential file upload vulnerabilities.
Corgea Logo

Find this vulnerability and fix it with Corgea

Scan your codebase for CWE-434: Unrestricted Upload of File with Dangerous Type and get remediation guidance

Start for free and no credit card needed.