Code Uploaded to a Server

File upload vulnerabilities

In this section, you'll learn how simple file upload functions tin be used every bit a powerful vector for a number of loftier-severity attacks. We'll show you how to bypass common defense force mechanisms in order to upload a web shell, enabling you to have total control of a vulnerable web server. Given how mutual file upload functions are, knowing how to test them properly is essential knowledge.

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. Declining to properly enforce restrictions on these could hateful that even a basic image upload office can exist used to upload arbitrary and potentially dangerous files instead. This could fifty-fifty include server-side script files that enable remote code execution.

In some cases, the human activity of uploading the file is in itself enough to cause harm. Other attacks may involve a follow-up 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 two key factors:

  • Which aspect of the file the website fails to validate properly, whether that exist its size, type, contents, then on.
  • What restrictions are imposed on the file once 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 every bit .php and .jsp) to be executed as code. In this case, an attacker could potentially upload a server-side lawmaking file that functions as a web beat out, effectively granting them full control over the server.

If the filename isn't validated properly, this could let an attacker to overwrite critical files but by uploading a file with the aforementioned name. If the server is also vulnerable to directory traversal, this could hateful attackers are even able to upload files to unanticipated locations.

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

How practise file upload vulnerabilities arise?

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

For instance, they may attempt to blacklist dangerous file types, but neglect to account for parsing discrepancies when checking the file extensions. As with any blacklist, it's too piece of cake to accidentally omit more obscure file types that may still be dangerous.

In other cases, the website may try to cheque the file type by verifying properties that can exist easily manipulated by an attacker using tools like Burp Proxy or Repeater.

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

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

How practise web servers handle requests for static files?

Before we look at how to exploit file upload vulnerabilities, information technology's important that you take a basic agreement of how servers handle requests for static files.

Historically, websites consisted almost entirely of static files that would exist served to users when requested. As a result, the path of each request could be mapped 1: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 direct relationship to the filesystem at all. Nonetheless, web servers still deal with requests for some static files, including stylesheets, images, and then on.

The process for treatment these static files is still largely the same. At some indicate, the server parses the path in the request to place the file extension. It so uses this to decide the blazon of the file being requested, typically by comparing it to a list of preconfigured mappings between extensions and MIME types. What happens next depends on the file blazon and the server's configuration.

  • If this file type is non-executable, such as an image or a static HTML folio, the server may merely send the file'due south contents to the customer 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 blazon, it will assign variables based on the headers and parameters in the HTTP request before running the script. The resulting output may and then be sent to the client in an HTTP response.
  • If the file type is executable, simply the server is not configured to execute files of this type, information technology will generally respond with an error. However, in some cases, the contents of the file may still be served to the client equally plain text. Such misconfigurations tin occasionally be exploited to leak source code and other sensitive data. Y'all can see an example of this in our data disclosure learning materials.

Tip

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

Now that y'all're familiar with the key concepts, permit's expect at how you tin potentially exploit these kinds of vulnerabilities.

Exploiting unrestricted file uploads to deploy a web beat

From a security perspective, the worst possible scenario is when a website allows you to upload server-side scripts, such as PHP, Java, or Python files, and is also configured to execute them as code. This makes information technology lilliputian to create your ain web trounce on the server.

Web trounce

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

If you're able to successfully upload a web beat, you finer have full control over the server. This means you tin read and write arbitrary files, exfiltrate sensitive data, even use the server to pivot attacks against both internal infrastructure and other servers outside the network. For example, the following PHP 1-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's contents in the response.

A more versatile spider web beat out may await something similar this:

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

This script enables you to pass an arbitrary organisation command via a query parameter as follows:

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

Exploiting flawed validation of file uploads

In the wild, it's unlikely that you'll detect a website that has no protection whatever against file upload attacks like we saw in the previous lab. But merely because defenses are in place, that doesn't hateful that they're robust.

In this section, we'll look at some means that spider web servers effort to validate and sanitize file uploads, besides every bit how you can exploit flaws in these mechanisms to obtain a web shell for remote lawmaking execution.

Flawed file type validation

When submitting HTML forms, your browser typically sends the provided data in a Mail asking with the content blazon awarding/x-www-form-url-encoded. This is fine for sending simple text like your 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 clarification of information technology, and inbound your username. Submitting such a class might result in a asking that looks something like this:

Mail service /images HTTP/1.i Host: normal-website.com Content-Length: 12345 Content-Type: multipart/form-data; boundary=---------------------------012345678901234567890123456 ---------------------------012345678901234567890123456 Content-Disposition: form-information; name="paradigm"; filename="instance.jpg" Content-Type: image/jpeg [...binary content of instance.jpg...] ---------------------------012345678901234567890123456 Content-Disposition: form-information; name="description" This is an interesting clarification of my epitome. ---------------------------012345678901234567890123456 Content-Disposition: class-information; name="username" wiener ---------------------------012345678901234567890123456--

As you can meet, the message trunk is split into separate parts for each of the form's inputs. Each function contains a Content-Disposition header, which provides some basic data about the input field it relates to. These individual parts may too contain their own Content-Type 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 type. If the server is only expecting image files, for example, it may merely permit types like image/jpeg and image/png. Problems can arise when the value of this header is implicitly trusted by the server. If no further validation is performed to bank check whether the contents of the file actually match the supposed MIME type, this defense force tin be easily bypassed using tools similar Burp Repeater.

Preventing file execution in user-accessible directories

While it'south clearly meliorate to prevent dangerous file types beingness uploaded in the first place, the second line of defence force is to finish the server from executing any scripts that do slip through the internet.

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

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

This beliefs is potentially interesting in its ain right, as it may provide a way to leak source code, but it nullifies whatever attempt to create a web shell.

This kind of configuration oftentimes differs betwixt 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 be out of reach for end users. If you can find a style to upload a script to a different directory that'south not supposed to contain user-supplied files, the server may execute your script after all.

Tip

Spider web servers often use the filename field in multipart/form-data requests to make up one's mind the proper name and location where the file should exist saved.

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

Insufficient blacklisting of dangerous file types

One of the more obvious means of preventing users from uploading malicious scripts is to blacklist potentially dangerous file extensions like .php. The practice of blacklisting is inherently flawed equally it'south difficult to explicitly cake every possible file extension that could be used to execute lawmaking. Such blacklists can sometimes be bypassed by using lesser known, alternative file extensions that may still exist executable, such every bit .php5, .shtml, and and so 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 will execute PHP files requested by a client, developers might have to add the following directives to their /etc/apache2/apache2.conf file:

LoadModule php_module /usr/lib/apache2/modules/libphp.so AddType application/x-httpd-php .php

Many servers besides allow developers to create special configuration files within individual directories in club to override or add together to one or more of the global settings. Apache servers, for case, will load a directory-specific configuration from a file called .htaccess if i is nowadays.

Similarly, developers tin can make directory-specific configuration on IIS servers using a web.config file. This might include directives such every bit the post-obit, which in this instance allows JSON files to be served to users:

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

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

Obfuscating file extensions

Even the most exhaustive blacklists can potentially be bypassed using classic obfuscation techniques. Permit'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 lot to sneak malicious PHP files past validation that may somewhen exist executed by the server.

You can also achieve similar results using the post-obit techniques:

  • Provide multiple extensions. Depending on the algorithm used to parse the filename, the post-obit file may exist interpreted as either a PHP file or JPG image: exploit.php.jpg
  • Add together trailing characters. Some components will strip or ignore abaft 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 tin can as well allow you to upload malicious files that would otherwise be blocked: exploit%2Ephp
  • Add together semicolons or URL-encoded zip byte characters before the file extension. If validation is written in a high-level language like PHP or Java, but the server processes the file using lower-level functions in C/C++, for example, this can crusade discrepancies in what is treated every bit the end of the filename: exploit.asp;.jpg or exploit.asp%00.jpg
  • Try using multibyte unicode characters, which may be converted to aught bytes and dots later 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 cord, but so converted to ASCII characters before existence used in a path.

Other defenses involve stripping or replacing unsafe extensions to prevent the file from beingness executed. If this transformation isn't applied recursively, you can position the prohibited string in such a fashion that removing it nevertheless leaves backside a valid file extension. For example, consider what happens if you lot strip .php from the post-obit filename:

exploit.p.phphp

This is only a small selection of the many means 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 endeavour to verify that the contents of the file actually lucifer what is expected.

In the case of an image upload function, the server might effort to verify certain intrinsic properties of an image, such equally its dimensions. If y'all endeavour uploading a PHP script, for example, it won't have whatsoever dimensions at all. Therefore, the server tin deduce that information technology tin can't perhaps exist an prototype, and reject the upload accordingly.

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 lucifer the expected type. For example, JPEG files always begin with the bytes FF D8 FF.

This is a much more robust style of validating the file type, but even this isn't foolproof. Using special tools, such every bit ExifTool, information technology can be lilliputian to create a polyglot JPEG file containing malicious lawmaking within its metadata.

Exploiting file upload race atmospheric condition

Modern frameworks are more battle-hardened against these kinds of attacks. They mostly don't upload files direct to their intended destination on the filesystem. Instead, they take precautions like uploading to a temporary, sandboxed directory first and randomizing the proper noun to avoid overwriting existing files. They then perform validation on this temporary file and but transfer it to its destination once it is accounted rubber to practice then.

That said, developers sometimes implement their own processing of file uploads independently of any framework. Not only is this adequately complex to do well, it tin can also introduce dangerous race conditions that enable an attacker to completely bypass even the near robust validation.

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

These vulnerabilities are oftentimes extremely subtle, making them hard to observe during blackbox testing unless you lot can find a way to leak the relevant source lawmaking.

Race weather 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 case, the server has to fetch the file over the net and create a local copy before it can perform any validation.

Every bit the file is loaded using HTTP, developers are unable to use their framework's born 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 name, in theory, it should be impossible for an attacker to exploit any race weather condition. If they don't know the name of the directory, they volition be unable to request the file in order to trigger its execution. On the other hand, if the randomized directory proper noun is generated using pseudo-random functions like PHP'southward uniqid(), it tin 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 animal-forcing the directory name. One way of doing this is by uploading a larger file. If information technology is processed in chunks, yous can potentially take reward of this by creating a malicious file with the payload at the start, followed by a big 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 code execution. This is the most serious outcome of an insecure file upload part, only these vulnerabilities can even so be exploited in other ways.

Uploading malicious client-side scripts

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

If the uploaded file then appears on a page that is visited by other users, their browser volition execute the script when information technology tries to return the page. Note that due to same-origin policy restrictions, these kinds of attacks will just piece of work if the uploaded file is served from the same origin to which you 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 attempt exploiting vulnerabilities specific to the parsing or processing of different file formats. For example, you lot know that the server parses XML-based files, such as Microsoft Office .doc 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 place, this can provide an alternative means of uploading malicious files, even when an upload office isn't available via the spider web interface.

PUT /images/exploit.php HTTP/ane.i 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 different endpoints to test for any that annunciate support for the PUT method.

How to forestall file upload vulnerabilities

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

  • Check the file extension against a whitelist of permitted extensions rather than a blacklist of prohibited ones. It's much easier to guess which extensions you might want to let than information technology is to gauge which ones an aggressor might endeavour to upload.
  • Make sure the filename doesn't contain any substrings that may exist interpreted as a directory or a traversal sequence (../).
  • Rename uploaded files to avert collisions that may cause existing files to be overwritten.
  • Do not upload files to the server'south permanent filesystem until they have been fully validated.
  • Every bit much as possible, utilise an established framework for preprocessing file uploads rather than attempting to write your ain validation mechanisms.

turnerandeld.blogspot.com

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

Related Posts

0 Response to "Code Uploaded to a Server"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel