If I Upload a File Can Security Know

File upload vulnerabilities

In this department, you'll larn how simple file upload functions can be used as a powerful vector for a number of high-severity attacks. We'll show yous how to bypass common defense mechanisms in order to upload a web shell, enabling you to accept total command of a vulnerable spider web server. Given how common file upload functions are, knowing how to test them properly is essential cognition.

File upload vulnerabilities

What are file upload vulnerabilities?

File upload vulnerabilities are when a spider web server allows users to upload files to its filesystem without sufficiently validating things like their name, type, contents, or size. Failing to properly enforce restrictions on these could mean that even a bones image upload function tin exist used to upload capricious and potentially dangerous files instead. This could even include server-side script files that enable remote code execution.

In some cases, the deed of uploading the file is in itself enough to crusade damage. Other attacks may involve a follow-upwards HTTP request for the file, typically to trigger its execution by the server.

What is the touch on of file upload vulnerabilities?

The impact of file upload vulnerabilities generally depends on ii key factors:

  • Which aspect of the file the website fails to validate properly, whether that be its size, type, contents, and and then on.
  • What restrictions are imposed on the file one time it has been successfully uploaded.

In the worst case scenario, the file's type isn't validated properly, and the server configuration allows certain types of file (such as .php and .jsp) to be executed as code. In this instance, an attacker could potentially upload a server-side code file that functions as a web shell, effectively granting them full control over the server.

If the filename isn't validated properly, this could let an attacker to overwrite critical files just by uploading a file with the aforementioned name. If the server is as well vulnerable to directory traversal, this could mean attackers are fifty-fifty able to upload files to unanticipated locations.

Failing to make certain that the size of the file falls inside expected thresholds could also enable a class of denial-of-service (DoS) assault, whereby the assailant fills the available disk space.

How do file upload vulnerabilities ascend?

Given the adequately obvious dangers, information technology'due south rare for websites in the wild to accept no restrictions any on which files users are allowed to upload. More commonly, developers implement what they believe to be robust validation that is either inherently flawed or can be easily bypassed.

For example, they may attempt to blacklist unsafe file types, but fail to business relationship for parsing discrepancies when checking the file extensions. As with whatsoever blacklist, it'due south besides easy to accidentally omit more obscure file types that may still be unsafe.

In other cases, the website may effort to check the file type by verifying properties that tin be easily manipulated past an attacker using tools like Burp Proxy or Repeater.

Ultimately, even robust validation measures may exist applied inconsistently across the network of hosts and directories that form the website, resulting in discrepancies that can exist exploited.

Later in this topic, nosotros'll teach you how to exploit a number of these flaws to upload a spider web shell for remote code execution. We've even created some interactive, deliberately vulnerable labs then that you can practice what you lot've learned against some realistic targets.

How practice web servers handle requests for static files?

Before we look at how to exploit file upload vulnerabilities, it's of import that you have a basic understanding of how servers handle requests for static files.

Historically, websites consisted almost entirely of static files that would be served to users when requested. As a effect, the path of each request could be mapped one:i with the hierarchy of directories and files on the server's filesystem. Nowadays, websites are increasingly dynamic and the path of a request often has no straight relationship to the filesystem at all. Nevertheless, spider web servers still deal with requests for some static files, including stylesheets, images, then on.

The process for handling these static files is still largely the aforementioned. At some point, the server parses the path in the request to place the file extension. Information technology then uses this to determine the type of the file beingness requested, typically past comparison it to a list of preconfigured mappings between extensions and MIME types. What happens next depends on the file type and the server's configuration.

  • If this file type is non-executable, such as an image or a static HTML folio, the server may just send the file's contents to the client in an HTTP response.
  • If the file type is executable, such equally a PHP file, and the server is configured to execute files of this blazon, it will assign variables based on the headers and parameters in the HTTP request before running the script. The resulting output may and so be sent to the customer in an HTTP response.
  • If the file type is executable, but the server is not configured to execute files of this type, it will generally reply with an error. However, in some cases, the contents of the file may still exist served to the customer as plain text. Such misconfigurations can occasionally exist exploited to leak source code and other sensitive data. You lot tin can come across an example of this in our information disclosure learning materials.

Tip

The Content-Blazon response header may provide clues as to what kind of file the server thinks information technology has served. If this header hasn't been explicitly set up by the awarding code, information technology normally contains the effect of the file extension/MIME type mapping.

Now that you're familiar with the key concepts, let'south look at how you lot can potentially exploit these kinds of vulnerabilities.

Exploiting unrestricted file uploads to deploy a web shell

From a security perspective, the worst possible scenario is when a website allows you lot to upload server-side scripts, such as PHP, Java, or Python files, and is as well configured to execute them as code. This makes it trivial to create your own spider web shell on the server.

Spider web shell

A spider web trounce is a malicious script that enables an attacker to execute arbitrary commands on a remote web server simply by sending HTTP requests to the right endpoint.

If y'all're able to successfully upload a web trounce, you lot effectively take total control over the server. This means you can read and write capricious files, exfiltrate sensitive data, even use the server to pivot attacks against both internal infrastructure and other servers outside the network. For case, the following PHP one-liner could exist used to read arbitrary files from the server'southward filesystem:

<?php echo file_get_contents('/path/to/target/file'); ?>

In one case uploaded, sending a request for this malicious file will return the target file's contents in the response.

A more than versatile web trounce may look something similar this:

<?php repeat system($_GET['control']); ?>

This script enables you to laissez passer an arbitrary arrangement command via a query parameter as follows:

Go /example/exploit.php?command=id HTTP/1.1

Exploiting flawed validation of file uploads

In the wild, it'south unlikely that you'll find a website that has no protection whatsoever against file upload attacks like we saw in the previous lab. Just only because defenses are in place, that doesn't mean that they're robust.

In this section, we'll expect at some ways that spider web servers attempt to validate and sanitize file uploads, as well as how you lot can exploit flaws in these mechanisms to obtain a web beat out for remote code execution.

Flawed file type validation

When submitting HTML forms, your browser typically sends the provided data in a Post asking with the content type awarding/x-world wide web-form-url-encoded. This is fine for sending simple text like your name, address, and so on, but is not suitable for sending large amounts of binary information, such as an entire image file or a PDF certificate. In this case, the content type multipart/form-information is the preferred approach.

Consider a class containing fields for uploading an prototype, providing a description of it, and entering your username. Submitting such a form might event in a request that looks something similar this:

POST /images HTTP/1.1 Host: normal-website.com Content-Length: 12345 Content-Type: multipart/class-data; purlieus=---------------------------012345678901234567890123456 ---------------------------012345678901234567890123456 Content-Disposition: grade-data; proper name="image"; filename="example.jpg" Content-Type: epitome/jpeg [...binary content of example.jpg...] ---------------------------012345678901234567890123456 Content-Disposition: form-data; proper name="description" This is an interesting description of my image. ---------------------------012345678901234567890123456 Content-Disposition: form-information; proper name="username" wiener ---------------------------012345678901234567890123456--

Every bit yous can see, the message trunk is split up into carve up parts for each of the form's inputs. Each part contains a Content-Disposition header, which provides some basic information nearly the input field it relates to. These individual parts may likewise comprise their own Content-Blazon header, which tells the server the MIME type of the data that was submitted using this input.

One way that websites may attempt to validate file uploads is to check that this input-specific Content-Type header matches an expected MIME blazon. If the server is only expecting epitome files, for example, it may only permit types like image/jpeg and paradigm/png. Problems can arise when the value of this header is implicitly trusted by the server. If no further validation is performed to check whether the contents of the file actually match the supposed MIME type, this defense can be easily bypassed using tools like Burp Repeater.

Preventing file execution in user-accessible directories

While information technology'south clearly better to prevent dangerous file types being uploaded in the start place, the second line of defense force is to stop the server from executing any scripts that do slip through the cyberspace.

Equally a precaution, servers generally only run scripts whose MIME type they have been explicitly configured to execute. Otherwise, they may but return some kind of mistake message or, in some cases, serve the contents of the file as obviously text instead:

GET /static/exploit.php?command=id HTTP/1.1 Host: normal-website.com HTTP/1.1 200 OK Content-Type: text/plain Content-Length: 39 <?php echo organization($_GET['command']); ?>

This behavior is potentially interesting in its ain right, as information technology may provide a manner to leak source code, but it nullifies any attempt to create a web shell.

This kind of configuration often differs between directories. A directory to which user-supplied files are uploaded will likely have much stricter controls than other locations on the filesystem that are assumed to exist out of achieve for end users. If you can discover a style to upload a script to a dissimilar directory that'due south not supposed to comprise user-supplied files, the server may execute your script afterwards all.

Tip

Web servers often utilise the filename field in multipart/form-data requests to determine the proper name and location where the file should be saved.

You should also note that even though y'all may transport all of your requests to the same domain name, this often points to a reverse proxy server of some kind, such equally a load balancer. Your requests will frequently be handled by additional servers behind the scenes, which may also be configured differently.

Insufficient blacklisting of unsafe file types

One of the more than obvious ways of preventing users from uploading malicious scripts is to blacklist potentially dangerous file extensions similar .php. The practice of blacklisting is inherently flawed as information technology's difficult to explicitly cake every possible file extension that could be used to execute code. Such blacklists tin sometimes exist bypassed by using bottom known, alternative file extensions that may still be executable, such every bit .php5, .shtml, then on.

Overriding the server configuration

As we discussed in the previous section, servers typically won't execute files unless they have been configured to practise so. For instance, before an Apache server will execute PHP files requested by a customer, developers might have to add the following directives to their /etc/apache2/apache2.conf file:

LoadModule php_module /usr/lib/apache2/modules/libphp.and then AddType application/10-httpd-php .php

Many servers also allow developers to create special configuration files inside individual directories in guild to override or add to 1 or more of the global settings. Apache servers, for instance, will load a directory-specific configuration from a file called .htaccess if one is nowadays.

Similarly, developers can make directory-specific configuration on IIS servers using a web.config file. This might include directives such as the following, which in this instance allows JSON files to exist served to users:

<staticContent> <mimeMap fileExtension=".json" mimeType="awarding/json" /> </staticContent>

Web servers utilise these kinds of configuration files when present, only you're not normally allowed to access them using HTTP requests. Still, you may occasionally find servers that neglect to stop yous from uploading your own malicious configuration file. In this case, even if the file extension you lot need is blacklisted, you lot may be able to trick the server into mapping an capricious, custom file extension to an executable MIME type.

Obfuscating file extensions

Even the most exhaustive blacklists tin potentially be bypassed using archetype obfuscation techniques. Let's say the validation code is case sensitive and fails to recognize that exploit.pHp is in fact a .php file. If the lawmaking that subsequently maps the file extension to a MIME type is non example sensitive, this discrepancy allows yous to sneak malicious PHP files by validation that may somewhen exist executed by the server.

You can likewise achieve similar results using the following techniques:

  • Provide multiple extensions. Depending on the algorithm used to parse the filename, the post-obit file may be interpreted as either a PHP file or JPG paradigm: exploit.php.jpg
  • Add trailing characters. Some components volition strip or ignore trailing whitespaces, dots, and suchlike: exploit.php.
  • Try using the URL encoding (or double URL encoding) for dots, forrad slashes, and backward slashes. If the value isn't decoded when validating the file extension, merely is after decoded server-side, this tin can also allow you to upload malicious files that would otherwise be blocked: exploit%2Ephp
  • Add together semicolons or URL-encoded null byte characters before the file extension. If validation is written in a loftier-level linguistic communication like PHP or Java, simply the server processes the file using lower-level functions in C/C++, for example, this tin cause discrepancies in what is treated as the stop of the filename: exploit.asp;.jpg or exploit.asp%00.jpg
  • Endeavour using multibyte unicode characters, which may exist converted to zip bytes and dots afterwards unicode conversion or normalization. Sequences similar xC0 x2E, xC4 xAE or xC0 xAE may be translated to x2E if the filename parsed as a UTF-8 cord, but and then converted to ASCII characters before being used in a path.

Other defenses involve stripping or replacing unsafe extensions to prevent the file from beingness executed. If this transformation isn't practical recursively, you can position the prohibited string in such a way that removing it still leaves backside a valid file extension. For case, consider what happens if you strip .php from the following filename:

exploit.p.phphp

This is merely a small selection of the many ways it's possible to obfuscate file extensions.

Flawed validation of the file's contents

Instead of implicitly trusting the Content-Blazon specified in a request, more secure servers endeavor to verify that the contents of the file really match what is expected.

In the case of an image upload function, the server might try to verify sure intrinsic properties of an image, such equally its dimensions. If you try uploading a PHP script, for example, it won't have any dimensions at all. Therefore, the server tin deduce that it can't peradventure exist an prototype, and reject the upload appropriately.

Similarly, certain file types may always contain a specific sequence of bytes in their header or footer. These can be used similar a fingerprint or signature to determine whether the contents match the expected type. For example, JPEG files always begin with the bytes FF D8 FF.

This is a much more robust way of validating the file type, but fifty-fifty this isn't foolproof. Using special tools, such as ExifTool, information technology tin can be piddling to create a polyglot JPEG file containing malicious lawmaking within its metadata.

Exploiting file upload race conditions

Modernistic frameworks are more battle-hardened confronting these kinds of attacks. They generally don't upload files directly to their intended destination on the filesystem. Instead, they take precautions like uploading to a temporary, sandboxed directory start and randomizing the name to avert overwriting existing files. They then perform validation on this temporary file and just transfer it to its destination once it is deemed safe to practice so.

That said, developers sometimes implement their ain processing of file uploads independently of whatsoever framework. Not only is this fairly circuitous to do well, it can too innovate dangerous race atmospheric condition that enable an attacker to completely featherbed even the most robust validation.

For instance, some websites upload the file directly to the master filesystem and so remove it once again if information technology doesn't pass validation. This kind of beliefs is typical in websites that rely on anti-virus software and the like to check for malware. This may merely take a few milliseconds, but for the short time that the file exists on the server, the attacker tin potentially still execute it.

These vulnerabilities are often extremely subtle, making them difficult to detect during blackbox testing unless you can find a style to leak the relevant source code.

Race conditions in URL-based file uploads

Similar race conditions tin can occur in functions that allow you to upload a file by providing a URL. In this case, the server has to fetch the file over the net and create a local copy before it can perform any validation.

Equally the file is loaded using HTTP, developers are unable to apply their framework's built-in mechanisms for securely validating files. Instead, they may manually create their ain processes for temporarily storing and validating the file, which may not exist quite as secure.

For example, if the file is loaded into a temporary directory with a randomized proper noun, in theory, information technology should be impossible for an assaulter to exploit any race weather. If they don't know the name of the directory, they will exist unable to request the file in gild to trigger its execution. On the other manus, if the randomized directory name is generated using pseudo-random functions like PHP's uniqid(), it can potentially be brute-forced.

To make attacks like this easier, you can try to extend the amount of time taken to process the file, thereby lengthening the window for brute-forcing the directory proper noun. One way of doing this is by uploading a larger file. If it is processed in chunks, you can potentially take reward of this by creating a malicious file with the payload at the get-go, followed past a big number of capricious padding bytes.

Exploiting file upload vulnerabilities without remote code execution

In the examples we've looked at so far, we've been able to upload server-side scripts for remote code execution. This is the most serious upshot of an insecure file upload function, only these vulnerabilities tin can yet be exploited in other ways.

Uploading malicious client-side scripts

Although y'all might not be able to execute scripts on the server, you may still be able to upload scripts for client-side attacks. For example, if you can upload HTML files or SVG images, you can potentially apply <script> tags to create stored XSS payloads.

If the uploaded file then appears on a page that is visited by other users, their browser will execute the script when it tries to return the page. Note that due to same-origin policy restrictions, these kinds of attacks will merely work if the uploaded file is served from the same origin to which y'all upload information technology.

Exploiting vulnerabilities in the parsing of uploaded files

If the uploaded file seems to be both stored and served deeply, the final resort is to try exploiting vulnerabilities specific to the parsing or processing of different file formats. For instance, you lot know that the server parses XML-based files, such as Microsoft Function .md or .xls files, this may exist a potential vector for XXE injection attacks.

Uploading files using PUT

It's worth noting that some web servers may be configured to support PUT requests. If appropriate defenses aren't in identify, this tin provide an alternative means of uploading malicious files, even when an upload function isn't available via the web interface.

PUT /images/exploit.php HTTP/one.1 Host: vulnerable-website.com Content-Type: application/ten-httpd-php Content-Length: 49 <?php repeat file_get_contents('/path/to/file'); ?>

Tip

Y'all can attempt sending OPTIONS requests to different endpoints to test for any that advertise support for the PUT method.

How to forbid file upload vulnerabilities

Allowing users to upload files is commonplace and doesn't have to exist unsafe as long as you have the right precautions. In general, the most effective way to protect your own websites from these vulnerabilities is to implement all of the following practices:

  • Check the file extension confronting a whitelist of permitted extensions rather than a blacklist of prohibited ones. It'due south much easier to guess which extensions y'all might want to let than it is to estimate which ones an attacker might try to upload.
  • Make sure the filename doesn't contain any substrings that may be interpreted as a directory or a traversal sequence (../).
  • Rename uploaded files to avoid collisions that may cause existing files to be overwritten.
  • Do non upload files to the server's permanent filesystem until they accept been fully validated.
  • As much equally possible, use an established framework for preprocessing file uploads rather than attempting to write your own validation mechanisms.

browntramere.blogspot.com

Source: https://portswigger.net/web-security/file-upload

0 Response to "If I Upload a File Can Security Know"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel