Stop Accidental File Drops With File Upload

File upload vulnerabilities

In this section, yous'll learn how simple file upload functions can be used as a powerful vector for a number of high-severity attacks. Nosotros'll show you how to bypass mutual defense mechanisms in society to upload a web beat, enabling you to take full command of a vulnerable spider web server. Given how common file upload functions are, knowing how to examination 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 proper noun, type, contents, or size. Failing to properly enforce restrictions on these could hateful that even a basic image upload role tin be used to upload arbitrary and potentially dangerous files instead. This could even include server-side script files that enable remote code execution.

In some cases, the act of uploading the file is in itself enough to cause harm. Other attacks may involve a follow-upwardly HTTP request for the file, typically to trigger its execution by the server.

What is the bear upon of file upload vulnerabilities?

The impact of file upload vulnerabilities more often than not 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 so on.
  • What restrictions are imposed on the file once it has been successfully uploaded.

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

If the filename isn't validated properly, this could allow an attacker to overwrite disquisitional files simply by uploading a file with the same name. If the server is as well vulnerable to directory traversal, this could mean attackers are even able to upload files to unanticipated locations.

Declining to brand sure that the size of the file falls within expected thresholds could also enable a grade of denial-of-service (DoS) attack, whereby the attacker fills the bachelor disk space.

How practise file upload vulnerabilities arise?

Given the adequately obvious dangers, it's rare for websites in the wild to have no restrictions whatsoever on which files users are immune to upload. More commonly, developers implement what they believe to be robust validation that is either inherently flawed or can exist easily bypassed.

For example, they may try to blacklist dangerous file types, but fail to account for parsing discrepancies when checking the file extensions. Equally with whatever blacklist, information technology's too easy to accidentally omit more than obscure file types that may however be unsafe.

In other cases, the website may attempt to check the file type past verifying backdrop that tin be easily manipulated past an assailant using tools like Burp Proxy or Repeater.

Ultimately, even robust validation measures may be practical inconsistently beyond the network of hosts and directories that form the website, resulting in discrepancies that can be exploited.

Later in this topic, we'll teach y'all how to exploit a number of these flaws to upload a spider web shell for remote lawmaking execution. We've even created some interactive, deliberately vulnerable labs so that yous can practice what you've learned confronting some realistic targets.

How do web servers handle requests for static files?

Before nosotros look at how to exploit file upload vulnerabilities, it's important that you have a basic agreement 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:ane 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 directly relationship to the filesystem at all. Even so, spider web servers still deal with requests for some static files, including stylesheets, images, and so on.

The procedure for handling these static files is still largely the aforementioned. At some point, the server parses the path in the request to identify the file extension. Information technology then uses this to determine the type of the file being requested, typically by comparing information technology 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 epitome or a static HTML folio, the server may only send the file'due south contents to the client in an HTTP response.
  • If the file blazon is executable, such as a PHP file, and the server is configured to execute files of this type, it will assign variables based on the headers and parameters in the HTTP request before running the script. The resulting output may then be sent to the client in an HTTP response.
  • If the file blazon is executable, merely the server is not configured to execute files of this type, information technology will generally answer with an error. Still, in some cases, the contents of the file may still be served to the client as apparently text. Such misconfigurations can occasionally be exploited to leak source code and other sensitive data. Y'all tin can see an example of this in our information disclosure learning materials.

Tip

The Content-Type response header may provide clues equally to what kind of file the server thinks it has served. If this header hasn't been explicitly set by the application lawmaking, it normally contains the result of the file extension/MIME blazon mapping.

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

Exploiting unrestricted file uploads to deploy a web beat out

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

Web crush

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

If you're able to successfully upload a web vanquish, you effectively have full control over the server. This means yous can read and write arbitrary files, exfiltrate sensitive data, fifty-fifty use the server to pivot attacks against both internal infrastructure and other servers outside the network. For example, the following PHP one-liner could be used to read arbitrary files from the server's filesystem:

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

Once uploaded, sending a request for this malicious file will return the target file'southward contents in the response.

A more than versatile spider web shell may look something like this:

<?php echo system($_GET['command']); ?>

This script enables you to pass an arbitrary system control via a query parameter as follows:

GET /example/exploit.php?command=id HTTP/1.i

Exploiting flawed validation of file uploads

In the wild, information technology's unlikely that you'll find a website that has no protection whatsoever against file upload attacks similar nosotros saw in the previous lab. But just considering defenses are in place, that doesn't hateful that they're robust.

In this section, we'll look at some ways that spider web servers attempt to validate and sanitize file uploads, equally well as how you can exploit flaws in these mechanisms to obtain a spider web shell 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-www-form-url-encoded. This is fine for sending simple text similar your proper name, address, and and then on, but is non suitable for sending large amounts of binary data, such as an unabridged image file or a PDF document. In this instance, the content type multipart/form-information is the preferred approach.

Consider a form containing fields for uploading an image, providing a description of it, and entering your username. Submitting such a form might outcome in a asking that looks something like this:

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

As you can encounter, the message body is split into separate parts for each of the form's inputs. Each office contains a Content-Disposition header, which provides some basic data almost the input field it relates to. These private parts may too incorporate their own Content-Type header, which tells the server the MIME type of the information that was submitted using this input.

I way that websites may attempt to validate file uploads is to cheque that this input-specific Content-Type header matches an expected MIME type. If the server is only expecting image files, for example, information technology may only permit types like prototype/jpeg and prototype/png. Bug can ascend 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 friction match the supposed MIME blazon, this defence tin can be easily bypassed using tools like Burp Repeater.

Preventing file execution in user-accessible directories

While it'south conspicuously better to forbid dangerous file types being uploaded in the starting time identify, the 2nd line of defense force is to terminate the server from executing any scripts that practice skid through the net.

Equally a precaution, servers mostly but run scripts whose MIME blazon they take been explicitly configured to execute. Otherwise, they may only return some kind of error message or, in some cases, serve the contents of the file as plain text instead:

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

This behavior is potentially interesting in its own right, as it may provide a mode to leak source code, just it nullifies whatever endeavour to create a web shell.

This kind of configuration frequently differs between directories. A directory to which user-supplied files are uploaded volition likely have much stricter controls than other locations on the filesystem that are assumed to be out of accomplish for end users. If y'all can notice a way to upload a script to a different directory that's not supposed to contain user-supplied files, the server may execute your script after all.

Tip

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

You should also notation that even though you lot may send all of your requests to the same domain proper name, this frequently points to a reverse proxy server of some kind, such equally a load balancer. Your requests will oftentimes be handled by additional servers behind the scenes, which may also be configured differently.

Insufficient blacklisting of dangerous file types

Ane of the more 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 it's difficult to explicitly cake every possible file extension that could be used to execute code. Such blacklists can sometimes be bypassed by using lesser known, culling file extensions that may nonetheless be executable, such as .php5, .shtml, and 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 do so. For example, before an Apache server volition execute PHP files requested by a client, developers might have to add the post-obit directives to their /etc/apache2/apache2.conf file:

LoadModule php_module /usr/lib/apache2/modules/libphp.and then AddType awarding/ten-httpd-php .php

Many servers also permit developers to create special configuration files within individual directories in order to override or add to one or more of the global settings. Apache servers, for example, will load a directory-specific configuration from a file chosen .htaccess if one is present.

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

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

Web servers utilise these kinds of configuration files when nowadays, but you're non normally immune to admission them using HTTP requests. However, you may occasionally find servers that fail to terminate you lot from uploading your ain malicious configuration file. In this case, even if the file extension you need is blacklisted, yous may exist able to trick the server into mapping an arbitrary, custom file extension to an executable MIME type.

Obfuscating file extensions

Fifty-fifty the near exhaustive blacklists tin potentially be bypassed using classic 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 not case sensitive, this discrepancy allows you to sneak malicious PHP files past validation that may eventually be executed by the server.

You can as well accomplish 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 epitome: exploit.php.jpg
  • Add trailing characters. Some components will strip or ignore trailing whitespaces, dots, and suchlike: exploit.php.
  • Try using the URL encoding (or double URL encoding) for dots, forward slashes, and backward slashes. If the value isn't decoded when validating the file extension, only is later decoded server-side, this can also permit you to upload malicious files that would otherwise be blocked: exploit%2Ephp
  • Add semicolons or URL-encoded null byte characters before the file extension. If validation is written in a loftier-level language like PHP or Coffee, merely the server processes the file using lower-level functions in C/C++, for example, this can cause discrepancies in what is treated equally the end of the filename: exploit.asp;.jpg or exploit.asp%00.jpg
  • Effort using multibyte unicode characters, which may be converted to null bytes and dots after unicode conversion or normalization. Sequences like xC0 x2E, xC4 xAE or xC0 xAE may be translated to x2E if the filename parsed as a UTF-eight string, but then converted to ASCII characters before being used in a path.

Other defenses involve stripping or replacing unsafe extensions to prevent the file from being executed. If this transformation isn't practical recursively, you lot can position the prohibited cord in such a way that removing information technology however leaves behind a valid file extension. For example, consider what happens if you strip .php from the following filename:

exploit.p.phphp

This is just 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-Type specified in a request, more secure servers try to verify that the contents of the file actually friction match what is expected.

In the instance of an image upload part, the server might endeavour to verify certain intrinsic properties of an image, such every bit its dimensions. If you try uploading a PHP script, for example, information technology won't have any dimensions at all. Therefore, the server can deduce that information technology can't possibly exist an image, and pass up the upload appropriately.

Similarly, certain file types may always comprise a specific sequence of bytes in their header or footer. These can be used like a fingerprint or signature to decide 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 manner of validating the file blazon, but even this isn't foolproof. Using special tools, such as ExifTool, information technology tin can be picayune to create a polyglot JPEG file containing malicious code within its metadata.

Exploiting file upload race conditions

Modern 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 first and randomizing the name to avoid overwriting existing files. They then perform validation on this temporary file and only transfer it to its destination once it is accounted safe to do then.

That said, developers sometimes implement their own processing of file uploads independently of any framework. Not only is this fairly complex to practice well, information technology can besides innovate dangerous race conditions that enable an attacker to completely bypass even the virtually robust validation.

For case, some websites upload the file directly to the principal filesystem and then remove it again if it doesn't laissez passer validation. This kind of behavior is typical in websites that rely on anti-virus software and the like to check for malware. This may only take a few milliseconds, but for the short time that the file exists on the server, the attacker can potentially still execute it.

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

Race conditions in URL-based file uploads

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

As the file is loaded using HTTP, developers are unable to apply their framework'due south congenital-in mechanisms for securely validating files. Instead, they may manually create their own processes for temporarily storing and validating the file, which may not be quite as secure.

For example, if the file is loaded into a temporary directory with a randomized proper noun, in theory, it should be incommunicable for an attacker to exploit whatsoever race conditions. If they don't know the proper noun of the directory, they volition be unable to asking the file in club to trigger its execution. On the other manus, if the randomized directory proper name is generated using pseudo-random functions like PHP's uniqid(), information technology can potentially be beast-forced.

To make attacks like this easier, you can effort 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 lot can potentially take advantage of this by creating a malicious file with the payload at the start, followed past a large number of arbitrary padding bytes.

Exploiting file upload vulnerabilities without remote lawmaking execution

In the examples we've looked at so far, we've been able to upload server-side scripts for remote lawmaking execution. This is the most serious event of an insecure file upload office, but these vulnerabilities can still be exploited in other ways.

Uploading malicious client-side scripts

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

If the uploaded file then appears on a folio that is visited by other users, their browser volition execute the script when it tries to return the page. Note that due to aforementioned-origin policy restrictions, these kinds of attacks will only work if the uploaded file is served from the same origin to which you lot upload it.

Exploiting vulnerabilities in the parsing of uploaded files

If the uploaded file seems to be both stored and served deeply, the last resort is to effort exploiting vulnerabilities specific to the parsing or processing of dissimilar file formats. For example, yous know that the server parses XML-based files, such every bit Microsoft Part .doc or .xls files, this may exist a potential vector for XXE injection attacks.

Uploading files using PUT

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

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

Tip

You can try sending OPTIONS requests to dissimilar endpoints to test for any that advertise support for the PUT method.

How to prevent file upload vulnerabilities

Allowing users to upload files is commonplace and doesn't have to be dangerous as long as you take the right precautions. In full general, the most effective fashion to protect your own websites from these vulnerabilities is to implement all of the post-obit practices:

  • Check the file extension against a whitelist of permitted extensions rather than a blacklist of prohibited ones. It'south much easier to guess which extensions you might want to allow than information technology is to guess which ones an attacker might try to upload.
  • Brand 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 crusade existing files to be overwritten.
  • Exercise not upload files to the server's permanent filesystem until they accept been fully validated.
  • Equally much as possible, use an established framework for preprocessing file uploads rather than attempting to write your own validation mechanisms.

clemenswain1973.blogspot.com

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

0 Response to "Stop Accidental File Drops With File Upload"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel