CWE

Common Weakness Enumeration

A Community-Developed Dictionary of Software Weakness Types

CWE/SANS Top 25 Most Dangerous Software Errors Common Weakness Scoring System
Common Weakness Risk Analysis Framework
Home > CWE List > CWE- Individual Dictionary Definition (2.6)  

Presentation Filter:

CWE-434: Unrestricted Upload of File with Dangerous Type

 
Unrestricted Upload of File with Dangerous Type
Weakness ID: 434 (Weakness Base)Status: Draft
+ Description

Description Summary

The software allows the attacker to upload or transfer files of dangerous types that can be automatically processed within the product's environment.
+ Alternate Terms
Unrestricted File Upload:

The "unrestricted file upload" term is used in vulnerability databases and elsewhere, but it is insufficiently precise. The phrase could be interpreted as the lack of restrictions on the size or number of uploaded files, which is a resource consumption issue.

+ Time of Introduction
  • Implementation
  • Architecture and Design
+ Applicable Platforms

Languages

ASP.NET: (Sometimes)

PHP: (Often)

Language-independent

Architectural Paradigms

Web-based

Technology Classes

Web-Server: (Sometimes)

+ Common Consequences
ScopeEffect
Integrity
Confidentiality
Availability

Technical Impact: Execute unauthorized code or commands

Arbitrary code execution is possible if an uploaded file is interpreted and executed as code by the recipient. This is especially true for .asp and .php extensions uploaded to web servers because these file types are often treated as automatically executable, even when file system permissions do not specify execution. For example, in Unix environments, programs typically cannot run unless the execute bit is set, but PHP programs may be executed by the web server without directly invoking them on the operating system.

+ Likelihood of Exploit

Medium to High

+ Demonstrative Examples

Example 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".

(Good Code)
Example Language: 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>

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.

(Bad Code)
Example Language: 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.";
}

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:

(Attack)
 
malicious.php

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:

(Attack)
Example Language: PHP 
<?php
system($_GET['cmd']);
?>

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

(Attack)
 
http://server.example.com/upload_dir/malicious.php?cmd=ls%20-l

which runs the "ls -l" command - or any other type of command that the attacker wants to specify.

Example 2

The following code demonstrates the unrestricted upload of a file with a Java servlet and a path traversal vulnerability. The HTML code is the same as in the previous example with the action attribute of the form sending the upload file request to the Java servlet instead of the PHP code.

(Good Code)
Example Language: HTML 
<form action="FileUploadServlet" 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>

When submitted the Java servlet's doPost method will receive the request, extract the name of the file from the Http request header, read the file contents from the request and output the file to the local upload directory.

(Bad Code)
Example Language: Java 
public class FileUploadServlet extends HttpServlet {

...

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();
String contentType = request.getContentType();

// the starting position of the boundary header
int ind = contentType.indexOf("boundary=");
String boundary = contentType.substring(ind+9);

String pLine = new String();
String uploadLocation = new String(UPLOAD_DIRECTORY_STRING); //Constant value

// verify that content type is multipart form data
if (contentType != null && contentType.indexOf("multipart/form-data") != -1) {

// extract the filename from the Http header
BufferedReader br = new BufferedReader(new InputStreamReader(request.getInputStream()));
...
pLine = br.readLine();
String filename = pLine.substring(pLine.lastIndexOf("\\"), pLine.lastIndexOf("\""));
...

// output the file to the local upload directory
try {
BufferedWriter bw = new BufferedWriter(new FileWriter(uploadLocation+filename, true));
for (String line; (line=br.readLine())!=null; ) {
if (line.indexOf(boundary) == -1) {
bw.write(line);
bw.newLine();
bw.flush();
}
} //end of for loop
bw.close();

} catch (IOException ex) {...}
// output successful upload response HTML page
}
// output unsuccessful upload response HTML page
else
{...}
}
...
}

As with the previous example this code does not perform a check on the type of the file being uploaded. This could allow an attacker to upload any executable file or other file with malicious code.

Additionally, the creation of the BufferedWriter object is subject to relative path traversal (CWE-22, CWE-23). Depending on the executing environment, the attacker may be able to specify arbitrary files to write to, leading to a wide variety of consequences, from code execution, XSS (CWE-79), or system crash.

+ Observed Examples
ReferenceDescription
CVE-2001-0901Web-based mail product stores ".shtml" attachments that could contain SSI
CVE-2002-1841PHP upload does not restrict file types
CVE-2005-1868upload and execution of .php file
CVE-2005-1881upload file with dangerous extension
CVE-2005-0254program does not restrict file types
CVE-2004-2262improper type checking of uploaded files
CVE-2006-4558Double "php" extension leaves an active php extension in the generated filename.
CVE-2006-6994ASP program allows upload of .asp files by bypassing client-side checks
CVE-2005-3288ASP file upload
CVE-2006-2428ASP file upload
+ Potential Mitigations

Phase: 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.[R.434.1] [R.434.2]

Phase: Architecture and Design

Strategy: Enforcement by Conversion

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.

Phase: Architecture and Design

Consider storing the uploaded files outside of the web document root entirely. Then, use other mechanisms to deliver the files dynamically. [R.434.2]

Phase: Implementation

Strategy: Input Validation

Assume all input is malicious. Use an "accept known good" input validation strategy, i.e., use a whitelist 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 (i.e., do not rely on a blacklist). A blacklist 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, blacklists 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.

Phase: 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.

Phase: Implementation

Strategy: Input Validation

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.[R.434.1] [R.434.2]

Phase: Implementation

When running on a web server that supports case-insensitive filenames, perform case-insensitive evaluations of the extensions that are provided.

Phase: 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.

Phase: Implementation

Do not rely exclusively on sanity checks of file contents to ensure that the file is of the expected type and size. It may be possible for an attacker to hide code in some file segments that will still be executed by the server. For example, GIF images may contain a free-form comments field.

Phase: Implementation

Do not rely exclusively on the MIME content type or filename attribute when determining how to render a file. Validating the MIME content type and ensuring that it matches the extension is only a partial solution.

Phases: Architecture and Design; Operation

Strategy: Environment Hardening

Run your code using the lowest privileges that are required to accomplish the necessary tasks [R.434.4]. If possible, create isolated accounts with limited privileges that are only used for a single task. That way, a successful attack will not immediately give the attacker access to the rest of the software or its environment. For example, database applications rarely need to run as the database administrator, especially in day-to-day operations.

Phases: Architecture and Design; Operation

Strategy: Sandbox or Jail

Run the code in a "jail" or similar sandbox environment that enforces strict boundaries between the process and the operating system. This may effectively restrict which files can be accessed in a particular directory or which commands can be executed by the software.

OS-level examples include the Unix chroot jail, AppArmor, and SELinux. In general, managed code may provide some protection. For example, java.io.FilePermission in the Java SecurityManager allows the software to specify restrictions on file operations.

This may not be a feasible solution, and it only limits the impact to the operating system; the rest of the application may still be subject to compromise.

Be careful to avoid CWE-243 and other weaknesses related to jails.

Effectiveness: Limited

The effectiveness of this mitigation depends on the prevention capabilities of the specific sandbox or jail being used and might only help to reduce the scope of an attack, such as restricting the attacker to certain system calls or limiting the portion of the file system that can be accessed.

+ Weakness Ordinalities
OrdinalityDescription
Primary

This can be primary when there is no check at all.

Resultant

This is frequently resultant when use of double extensions (e.g. ".php.gif") bypasses a sanity check.

This can be resultant from client-side enforcement (CWE-602); some products will include web script in web clients to check the filename, without verifying on the server side.

+ Relationships
NatureTypeIDNameView(s) this relationship pertains toView(s)
ChildOfCategoryCategory429Handler Errors
Development Concepts (primary)699
ChildOfCategoryCategory632Weaknesses that Affect Files or Directories
Resource-specific Weaknesses (primary)631
ChildOfWeakness ClassWeakness Class669Incorrect Resource Transfer Between Spheres
Research Concepts (primary)1000
ChildOfCategoryCategory714OWASP Top Ten 2007 Category A3 - Malicious File Execution
Weaknesses in OWASP Top Ten (2007) (primary)629
ChildOfCategoryCategory8012010 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2010 CWE/SANS Top 25 Most Dangerous Programming Errors (primary)800
ChildOfCategoryCategory813OWASP Top Ten 2010 Category A4 - Insecure Direct Object References
Weaknesses in OWASP Top Ten (2010) (primary)809
ChildOfCategoryCategory8642011 Top 25 - Insecure Interaction Between Components
Weaknesses in the 2011 CWE/SANS Top 25 Most Dangerous Software Errors (primary)900
PeerOfWeakness BaseWeakness Base351Insufficient Type Distinction
Research Concepts1000
PeerOfWeakness BaseWeakness Base430Deployment of Wrong Handler
Research Concepts1000
PeerOfWeakness BaseWeakness Base436Interpretation Conflict
Research Concepts1000
MemberOfViewView884CWE Cross-section
CWE Cross-section (primary)884
CanFollowWeakness ClassWeakness Class73External Control of File Name or Path
Research Concepts1000
CanFollowWeakness BaseWeakness Base183Permissive Whitelist
Research Concepts1000
CanFollowWeakness BaseWeakness Base184Incomplete Blacklist
Research Concepts1000
+ Relationship Notes

This can have a chaining relationship with incomplete blacklist / permissive whitelist errors when the product tries, but fails, to properly limit which types of files are allowed (CWE-183, CWE-184).

This can also overlap multiple interpretation errors for intermediaries, e.g. anti-virus products that do not remove or quarantine attachments with certain file extensions that can be processed by client systems.

+ Research Gaps

PHP applications are most targeted, but this likely applies to other languages that support file upload, as well as non-web technologies. ASP applications have also demonstrated this problem.

+ Affected Resources
  • File/Directory
+ Functional Areas
  • File Processing
+ Taxonomy Mappings
Mapped Taxonomy NameNode IDFitMapped Node Name
PLOVERUnrestricted File Upload
OWASP Top Ten 2007A3CWE_More_SpecificMalicious File Execution
+ References
[R.434.1] Richard Stanway (r1CH). "Dynamic File Uploads, Security and You". <http://shsc.info/FileUploadSecurity>.
[R.434.2] Johannes Ullrich. "8 Basic Rules to Implement Secure File Uploads". 2009-12-28. <http://blogs.sans.org/appsecstreetfighter/2009/12/28/8-basic-rules-to-implement-secure-file-uploads/>.
[R.434.3] Johannes Ullrich. "Top 25 Series - Rank 8 - Unrestricted Upload of Dangerous File Type". SANS Software Security Institute. 2010-02-25. <http://blogs.sans.org/appsecstreetfighter/2010/02/25/top-25-series-rank-8-unrestricted-upload-of-dangerous-file-type/>.
[R.434.4] [REF-31] Sean Barnum and Michael Gegick. "Least Privilege". 2005-09-14. <https://buildsecurityin.us-cert.gov/daisy/bsi/articles/knowledge/principles/351.html>.
[R.434.5] [REF-7] Mark Dowd, John McDonald and Justin Schuh. "The Art of Software Security Assessment". Chapter 17, "File Uploading", Page 1068.. 1st Edition. Addison Wesley. 2006.
+ Content History
Submissions
Submission DateSubmitterOrganizationSource
PLOVERExternally Mined
Modifications
Modification DateModifierOrganizationSource
2008-07-01Eric DalciCigitalExternal
updated Time_of_Introduction
2008-09-08CWE Content TeamMITREInternal
updated Alternate_Terms, Relationships, Other_Notes, Taxonomy_Mappings
2009-01-12CWE Content TeamMITREInternal
updated Relationships
2009-12-28CWE Content TeamMITREInternal
updated Applicable_Platforms, Functional_Areas, Likelihood_of_Exploit, Potential_Mitigations, Time_of_Introduction
2010-02-16
(Critical)
CWE Content TeamMITREInternal
converted from Compound_Element to Weakness
2010-02-16CWE Content TeamMITREInternal
updated Alternate_Terms, Applicable_Platforms, Common_Consequences, Demonstrative_Examples, Name, Other_Notes, Potential_Mitigations, References, Related_Attack_Patterns, Relationship_Notes, Relationships, Type, Weakness_Ordinalities
2010-04-05CWE Content TeamMITREInternal
updated Related_Attack_Patterns
2010-06-21CWE Content TeamMITREInternal
updated References, Relationship_Notes
2010-09-27CWE Content TeamMITREInternal
updated Potential_Mitigations
2010-12-13CWE Content TeamMITREInternal
updated Potential_Mitigations
2011-06-27CWE Content TeamMITREInternal
updated Relationships
2011-09-13CWE Content TeamMITREInternal
updated Potential_Mitigations, References, Relationships
2012-05-11CWE Content TeamMITREInternal
updated References, Relationships
2012-10-30CWE Content TeamMITREInternal
updated Potential_Mitigations
Previous Entry Names
Change DatePrevious Entry Name
2010-02-16Unrestricted File Upload
Page Last Updated: February 18, 2014