CWE-434 Base Rascunho Medium likelihood

Unrestricted Upload of File with Dangerous Type

This vulnerability occurs when an application accepts file uploads without properly restricting the file types, allowing attackers to upload and execute malicious files on the server.

Definição

What is CWE-434?

This vulnerability occurs when an application accepts file uploads without properly restricting the file types, allowing attackers to upload and execute malicious files on the server.
At its core, this flaw is about trust. Applications often treat uploaded files as safe data, but without strict validation, an attacker can upload a script, executable, or other dangerous file type. When the server stores this file in a web-accessible location and later processes or serves it, the malicious code can execute with the application's own privileges, leading to complete system compromise. To prevent this, developers must implement a multi-layered defense. This includes using an allow-list approach for file extensions, verifying the file's actual content (not just its claimed type), storing uploads outside the web root, and ensuring files are served with secure, non-executable permissions. Relying solely on client-side checks or obscuring upload locations is insufficient, as these are easily bypassed by a determined attacker.
Vulnerability Diagram CWE-434
Unrestricted File Upload Upload form shell.php Server save to /uploads/ no MIME / ext check .php executable here GET /uploads/shell.php → webshell, RCE Uploaded scripts land in an executable directory and run as the server.
Impacto no mundo real

Real-world CVEs caused by CWE-434

  • PHP-based FAQ management app does not check the MIME type for uploaded images

  • Web-based mail product stores ".shtml" attachments that could contain SSI

  • PHP upload does not restrict file types

  • upload and execution of .php file

  • upload file with dangerous extension

  • program does not restrict file types

  • improper type checking of uploaded files

  • Double "php" extension leaves an active php extension in the generated filename.

Como os atacantes a exploram

Trajeto do atacante passo a passo

  1. 1

    The following code intends to allow a user to upload a picture to the web server. The HTML code that drives the form on the user end has an input field of type "file".

  2. 2

    Once submitted, the form above sends the file to upload_picture.php on the web server. PHP stores the file in a temporary location until it is retrieved (or discarded) by the server side code. In this example, the file is moved to a more permanent pictures/ directory.

  3. 3

    The problem with the above code is that there is no check regarding type of file being uploaded. Assuming that pictures/ is available in the web document root, an attacker could upload a file with the name:

  4. 4

    Since this filename ends in ".php" it can be executed by the web server. In the contents of this uploaded file, the attacker could use:

  5. 5

    Once this file has been installed, the attacker can enter arbitrary commands to execute using a URL such as:

Exemplo de código vulnerável

Vulnerable PHP

Once submitted, the form above sends the file to upload_picture.php on the web server. PHP stores the file in a temporary location until it is retrieved (or discarded) by the server side code. In this example, the file is moved to a more permanent pictures/ directory.

Vulnerável PHP
```
// Define the target location where the picture being* 
  
  
   *// uploaded is going to be saved.* 
  $target = "pictures/" . basename($_FILES['uploadedfile']['name']);
  
  
   *// Move the uploaded file to the new location.* 
  if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target))
  {
  ```
  	echo "The picture has been successfully uploaded.";
  }
  else
  {
  	echo "There was an error uploading the picture, please try again.";
  }
Payload do atacante

The problem with the above code is that there is no check regarding type of file being uploaded. Assuming that pictures/ is available in the web document root, an attacker could upload a file with the name:

Payload do atacante
malicious.php
Exemplo de código seguro

Secure HTML

The following code intends to allow a user to upload a picture to the web server. The HTML code that drives the form on the user end has an input field of type "file".

Seguro HTML
<form action="upload_picture.php" method="post" enctype="multipart/form-data">
  Choose a file to upload:
  <input type="file" name="filename"/>
  <br/>
  <input type="submit" name="submit" value="Submit"/>
  </form>
What changed: the unsafe sink is replaced (or the input is validated/escaped) so the same payload no longer triggers the weakness.
Lista de verificação de prevenção

How to prevent CWE-434

  • Architecture and Design Generate a new, unique filename for an uploaded file instead of using the user-supplied filename, so that no external input is used at all.[REF-422] [REF-423]
  • Architecture and Design When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.
  • Architecture and Design Consider storing the uploaded files outside of the web document root entirely. Then, use other mechanisms to deliver the files dynamically. [REF-423]
  • Implementation Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a list of acceptable inputs that strictly conform to specifications. Reject any input that does not strictly conform to specifications, or transform it into something that does. When performing input validation, consider all potentially relevant properties, including length, type of input, the full range of acceptable values, missing or extra inputs, syntax, consistency across related fields, and conformance to business rules. As an example of business rule logic, "boat" may be syntactically valid because it only contains alphanumeric characters, but it is not valid if the input is only expected to contain colors such as "red" or "blue." Do not rely exclusively on looking for malicious or malformed inputs. This is likely to miss at least one undesirable input, especially if the code's environment changes. This can give attackers enough room to bypass the intended validation. However, denylists can be useful for detecting potential attacks or determining which inputs are so malformed that they should be rejected outright. For example, limiting filenames to alphanumeric characters can help to restrict the introduction of unintended file extensions.
  • Architecture and Design Define a very limited set of allowable extensions and only generate filenames that end in these extensions. Consider the possibility of XSS (CWE-79) before allowing .html or .htm file types.
  • Implementation Ensure that only one extension is used in the filename. Some web servers, including some versions of Apache, may process files based on inner extensions so that "filename.php.gif" is fed to the PHP interpreter.[REF-422] [REF-423]
  • Implementation When running on a web server that supports case-insensitive filenames, perform case-insensitive evaluations of the extensions that are provided.
  • Architecture and Design For any security checks that are performed on the client side, ensure that these checks are duplicated on the server side, in order to avoid CWE-602. Attackers can bypass the client-side checks by modifying values after the checks have been performed, or by changing the client to remove the client-side checks entirely. Then, these modified values would be submitted to the server.
Sinais de deteção

How to detect CWE-434

Dynamic Analysis with Automated Results Interpretation SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Web Application Scanner Web Services Scanner Database Scanners

Dynamic Analysis with Manual Results Interpretation SOAR Partial

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Cost effective for partial coverage: ``` Fuzz Tester Framework-based Fuzzer

Manual Static Analysis - Source Code High

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Focused Manual Spotcheck - Focused manual analysis of source Manual Source Code Review (not inspections)

Automated Static Analysis - Source Code High

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Source code Weakness Analyzer Context-configured Source Code Weakness Analyzer

Architecture or Design Review High

According to SOAR [REF-1479], the following detection techniques may be useful: ``` Highly cost effective: ``` Formal Methods / Correct-By-Construction ``` Cost effective for partial coverage: ``` Inspection (IEEE 1028 standard) (can apply to requirements, design, source code, etc.)

Correção automática do Plexicus

O Plexicus deteta automaticamente o CWE-434 e abre um PR de correção em menos de 60 segundos.

O Codex Remedium analisa cada commit, identifica esta fraqueza exata e entrega um pull request pronto para revisão com o patch. Sem tickets. Sem transferências.

Perguntas frequentes

Frequently asked questions

O que é o CWE-434?

This vulnerability occurs when an application accepts file uploads without properly restricting the file types, allowing attackers to upload and execute malicious files on the server.

Qual a gravidade do CWE-434?

A MITRE classifica a probabilidade de exploração como Média — a exploração é realista mas normalmente requer condições específicas.

Que linguagens ou plataformas são afetadas pelo CWE-434?

MITRE lists the following affected platforms: ASP.NET, PHP, Web Server.

Como posso prevenir o CWE-434?

Generate a new, unique filename for an uploaded file instead of using the user-supplied filename, so that no external input is used at all.[REF-422] [REF-423] When the set of acceptable objects, such as filenames or URLs, is limited or known, create a mapping from a set of fixed input values (such as numeric IDs) to the actual filenames or URLs, and reject all other inputs.

Como é que o Plexicus deteta e corrige o CWE-434?

O motor SAST do Plexicus correlaciona a assinatura de fluxo de dados do CWE-434 em cada commit. Quando é encontrada uma correspondência, o nosso agente Codex Remedium abre um PR de correção com o código corrigido, testes e um resumo de uma linha para o revisor.

Onde posso saber mais sobre o CWE-434?

A MITRE publica a definição canónica em https://cwe.mitre.org/data/definitions/434.html. Pode também consultar a documentação da OWASP e do NIST para orientações adjacentes.

Fraquezas relacionadas

Weaknesses related to CWE-434

CWE-669 Pai

Incorrect Resource Transfer Between Spheres

This vulnerability occurs when an application incorrectly moves or shares a resource (like data, permissions, or functionality) between…

CWE-1420 Irmão

Exposure of Sensitive Information during Transient Execution

Transient execution vulnerabilities occur when a processor speculatively runs operations that don't officially commit, potentially leaking…

CWE-212 Irmão

Improper Removal of Sensitive Information Before Storage or Transfer

This vulnerability occurs when an application stores or transmits a resource containing sensitive data without properly cleaning it first,…

CWE-243 Irmão

Creation of chroot Jail Without Changing Working Directory

This vulnerability occurs when a program creates a chroot jail but fails to change its current working directory afterward. Because the…

CWE-494 Irmão

Download of Code Without Integrity Check

This vulnerability occurs when an application fetches and runs code from an external source—like a remote server or CDN—without properly…

CWE-565 Irmão

Reliance on Cookies without Validation and Integrity Checking

This vulnerability occurs when an application uses cookies to make security decisions—like granting access or changing settings—but fails…

CWE-829 Irmão

Inclusion of Functionality from Untrusted Control Sphere

This weakness occurs when an application integrates executable code, like a library or plugin, from a source it does not fully control or…

CWE-351 Par

Insufficient Type Distinction

This vulnerability occurs when an application fails to properly differentiate between different types of data or objects, leading to…

CWE-436 Par

Interpretation Conflict

An interpretation conflict occurs when two systems process the same data or sequence of events differently, leading one system to make…

Pronto quando você estiver

Pare de pagar por desenvolvedor.
Comece a fechar o ciclo.

O Plexicus é o ASPM nativo de IA que verifica, filtra, corrige, pentesta e explica — de forma autónoma. Programadores ilimitados, repos ilimitados, ações de IA de utilização justa. Nível gratuito real, €269/mo anual quando estiver pronto.