Skip to content Skip to sidebar Skip to footer

How to Upload Source Code to Image Upload Hack

File upload vulnerabilities

In this section, y'all'll larn how simple file upload functions can exist used every bit a powerful vector for a number of loftier-severity attacks. We'll testify you how to bypass common defense mechanisms in guild to upload a web shell, enabling you to accept full command of a vulnerable web server. Given how mutual file upload functions are, knowing how to examination 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 similar their name, type, contents, or size. Failing to properly enforce restrictions on these could hateful that even a basic image upload role can exist used to upload capricious and potentially unsafe files instead. This could even include server-side script files that enable remote lawmaking execution.

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

What is the impact of file upload vulnerabilities?

The touch on of file upload vulnerabilities by and large depends on two key factors:

  • Which aspect of the file the website fails to validate properly, whether that exist its size, blazon, contents, and and so on.
  • What restrictions are imposed on the file once information technology has been successfully uploaded.

In the worst example 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 every bit code. In this case, an attacker could potentially upload a server-side code 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 allow an attacker to overwrite critical files just by uploading a file with the same name. If the server is besides vulnerable to directory traversal, this could mean attackers are even able to upload files to unanticipated locations.

Declining to brand certain that the size of the file falls within expected thresholds could too enable a form of denial-of-service (DoS) set on, whereby the attacker fills the bachelor disk infinite.

How exercise file upload vulnerabilities arise?

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

For example, 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'south too piece of cake to accidentally omit more than obscure file types that may still be dangerous.

In other cases, the website may endeavour to cheque the file type by verifying properties that can be easily manipulated past an aggressor using tools similar Burp Proxy or Repeater.

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

Later in this topic, we'll teach yous how to exploit a number of these flaws to upload a web beat for remote lawmaking execution. Nosotros've even created some interactive, deliberately vulnerable labs and so that you can exercise what you lot've learned confronting some realistic targets.

How do spider web servers handle requests for static files?

Before we look at how to exploit file upload vulnerabilities, information technology'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. Equally a result, the path of each request could be mapped one:1 with the hierarchy of directories and files on the server's filesystem. Nowadays, websites are increasingly dynamic and the path of a request oftentimes has no straight human relationship to the filesystem at all. However, web servers still deal with requests for some static files, including stylesheets, images, then on.

The procedure for handling these static files is still largely the same. At some point, the server parses the path in the request to identify the file extension. It then uses this to determine the type of the file being requested, typically by comparing information technology to a listing of preconfigured mappings between extensions and MIME types. What happens side by side depends on the file type and the server'due south configuration.

  • If this file type is not-executable, such every bit an image or a static HTML page, the server may just send the file's contents to the customer in an HTTP response.
  • If the file type 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 exist sent to the client in an HTTP response.
  • If the file type is executable, just the server is not configured to execute files of this type, information technology will generally respond with an mistake. However, in some cases, the contents of the file may even so be served to the client as plain text. Such misconfigurations can occasionally be exploited to leak source code and other sensitive information. You can see 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 it has served. If this header hasn't been explicitly fix by the application code, it normally contains the result of the file extension/MIME blazon mapping.

At present that you're familiar with the key concepts, let's wait at how yous can potentially exploit these kinds of vulnerabilities.

Exploiting unrestricted file uploads to deploy a web crush

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 it picayune to create your own web beat out on the server.

Spider web shell

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

If you're able to successfully upload a web shell, you effectively have full control over the server. This means you tin can read and write arbitrary files, exfiltrate sensitive data, even utilize the server to pivot attacks against both internal infrastructure and other servers outside the network. For case, the post-obit PHP one-liner could be used to read capricious files from the server's filesystem:

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

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

A more versatile web vanquish may await something similar this:

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

This script enables you lot to pass an capricious arrangement control via a query parameter as follows:

GET /case/exploit.php?control=id HTTP/1.1

Exploiting flawed validation of file uploads

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

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

Flawed file blazon 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 elementary text like your name, address, and so on, but is not suitable for sending large amounts of binary data, such equally an unabridged image file or a PDF document. In this example, the content type multipart/form-data is the preferred approach.

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

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

As yous tin see, the message body is split up into separate parts for each of the form's inputs. Each role contains a Content-Disposition header, which provides some basic information about the input field it relates to. These individual parts may also incorporate their ain 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 prototype files, for example, it may only allow types like image/jpeg and epitome/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-attainable directories

While it'southward conspicuously better to prevent dangerous file types existence uploaded in the beginning place, the second line of defense is to end the server from executing any scripts that practise slip through the net.

As a precaution, servers more often than not just run scripts whose MIME type they have been explicitly configured to execute. Otherwise, they may just return some kind of mistake message or, in some cases, serve the contents of the file as plain text instead:

GET /static/exploit.php?command=id HTTP/1.1 Host: normal-website.com HTTP/i.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 it may provide a manner to leak source lawmaking, 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 volition probable have much stricter controls than other locations on the filesystem that are assumed to be out of reach for terminate users. If you lot can notice a way to upload a script to a different directory that's not supposed to incorporate user-supplied files, the server may execute your script after all.

Tip

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

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

Insufficient blacklisting of dangerous file types

Ane of the more obvious means of preventing users from uploading malicious scripts is to blacklist potentially unsafe file extensions like .php. The practice of blacklisting is inherently flawed as it'southward difficult to explicitly block every possible file extension that could be used to execute code. Such blacklists can sometimes be bypassed by using lesser known, alternative file extensions that may nevertheless exist executable, such as .php5, .shtml, and and then on.

Overriding the server configuration

As we discussed in the previous department, servers typically won't execute files unless they have been configured to exercise and then. For case, earlier an Apache server volition 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.and so AddType application/ten-httpd-php .php

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

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

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

Spider web servers use these kinds of configuration files when present, but y'all're not normally allowed to admission them using HTTP requests. However, you may occasionally observe servers that fail to end you lot from uploading your own malicious configuration file. In this example, even if the file extension you need is blacklisted, you may be able to play a joke on the server into mapping an capricious, custom file extension to an executable MIME type.

Obfuscating file extensions

Even the most exhaustive blacklists can potentially be bypassed using classic obfuscation techniques. Let's say the validation lawmaking is instance sensitive and fails to recognize that exploit.pHp is in fact a .php file. If the lawmaking that afterward 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 somewhen be executed by the server.

You can too 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 image: 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, forrard slashes, and backward slashes. If the value isn't decoded when validating the file extension, just is later decoded server-side, this can also allow you lot to upload malicious files that would otherwise be blocked: exploit%2Ephp
  • Add semicolons or URL-encoded naught 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 cause discrepancies in what is treated as the cease of the filename: exploit.asp;.jpg or exploit.asp%00.jpg
  • Try using multibyte unicode characters, which may be converted to zip bytes and dots after unicode conversion or normalization. Sequences similar xC0 x2E, xC4 xAE or xC0 xAE may exist translated to x2E if the filename parsed as a UTF-8 string, but so converted to ASCII characters earlier being used in a path.

Other defenses involve stripping or replacing dangerous extensions to prevent the file from existence executed. If this transformation isn't applied recursively, you tin position the prohibited string in such a fashion that removing it still leaves behind a valid file extension. For example, consider what happens if you lot strip .php from the following filename:

exploit.p.phphp

This is simply a small-scale 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 really match what is expected.

In the case of an prototype upload function, the server might try to verify sure intrinsic properties of an epitome, such every bit its dimensions. If you try uploading a PHP script, for instance, it won't accept any dimensions at all. Therefore, the server can deduce that it can't possibly be an image, and reject the upload accordingly.

Similarly, sure file types may ever comprise a specific sequence of bytes in their header or footer. These can be used like a fingerprint or signature to determine whether the contents match the expected blazon. For example, JPEG files e'er brainstorm with the bytes FF D8 FF.

This is a much more robust fashion of validating the file blazon, only fifty-fifty this isn't foolproof. Using special tools, such as ExifTool, it can be trivial to create a polyglot JPEG file containing malicious code within its metadata.

Exploiting file upload race conditions

Mod 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 outset and randomizing the name to avert overwriting existing files. They and so perform validation on this temporary file and only transfer it to its destination one time it is deemed condom to do so.

That said, developers sometimes implement their own processing of file uploads independently of any framework. Not simply is this adequately complex to do well, it can also introduce dangerous race conditions that enable an assailant to completely featherbed even the well-nigh robust validation.

For example, some websites upload the file straight to the master filesystem and and so 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 check for malware. This may only have a few milliseconds, only for the short time that the file exists on the server, the aggressor can potentially still execute it.

These vulnerabilities are often extremely subtle, making them hard to observe during blackbox testing unless y'all tin notice 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 case, the server has to fetch the file over the internet and create a local re-create before it tin can perform whatsoever validation.

As the file is loaded using HTTP, developers are unable to utilize their framework'south built-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 name, in theory, it should be impossible for an attacker to exploit any race conditions. If they don't know the name of the directory, they will be unable to request the file in order to trigger its execution. On the other paw, if the randomized directory name is generated using pseudo-random functions like PHP's uniqid(), information technology can potentially be brute-forced.

To brand attacks like this easier, you can attempt to extend the corporeality of time taken to procedure the file, thereby lengthening the window for beast-forcing the directory name. I manner of doing this is past uploading a larger file. If it is processed in chunks, you can potentially take advantage of this by creating a malicious file with the payload at the get-go, followed by a large number of arbitrary 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 consequence of an insecure file upload part, but these vulnerabilities can all the same be exploited in other ways.

Uploading malicious customer-side scripts

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

If the uploaded file so appears on a page that is visited past other users, their browser will execute the script when it tries to render the page. Note that due to same-origin policy restrictions, these kinds of attacks volition simply work if the uploaded file is served from the aforementioned 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 effort exploiting vulnerabilities specific to the parsing or processing of different file formats. For case, you know that the server parses XML-based files, such as Microsoft Function .doc or .xls files, this may be 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 advisable defenses aren't in place, this can provide an alternative ways of uploading malicious files, even when an upload function isn't available via the web interface.

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

Tip

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

How to prevent file upload vulnerabilities

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

  • Bank check the file extension against a whitelist of permitted extensions rather than a blacklist of prohibited ones. It'southward much easier to judge which extensions yous might want to allow than information technology is to approximate which ones an aggressor might endeavor to upload.
  • Brand certain the filename doesn't contain whatsoever substrings that may be interpreted equally a directory or a traversal sequence (../).
  • Rename uploaded files to avert collisions that may cause existing files to be overwritten.
  • Do non upload files to the server's permanent filesystem until they have been fully validated.
  • As much equally possible, use an established framework for preprocessing file uploads rather than attempting to write your ain validation mechanisms.

norwoodpons1950.blogspot.com

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

Enviar um comentário for "How to Upload Source Code to Image Upload Hack"