Dos Program to Upload Files to the Web
File upload vulnerabilities
In this section, yous'll learn how unproblematic file upload functions tin can exist used as a powerful vector for a number of loftier-severity attacks. Nosotros'll show you lot how to bypass mutual defence force mechanisms in gild to upload a spider web beat out, enabling yous to accept total control of a vulnerable web server. Given how common file upload functions are, knowing how to test them properly is essential knowledge.
Labs
If y'all're already familiar with the bones concepts behind file upload vulnerabilities and simply desire to get practicing, yous can access all of the labs in this topic from the link below.
View all file upload labs
What are file upload vulnerabilities?
File upload vulnerabilities are when a 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 mean that even a bones image upload office can 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 impairment. 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 impact of file upload vulnerabilities mostly depends on ii cardinal factors:
- Which aspect of the file the website fails to validate properly, whether that be its size, type, contents, and so on.
- What restrictions are imposed on the file once it has been successfully uploaded.
In the worst case scenario, the file'due south type isn't validated properly, and the server configuration allows certain types of file (such as .php and .jsp) to be executed as lawmaking. In this case, an assailant 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 allow an assailant to overwrite disquisitional files only by uploading a file with the same name. If the server is also vulnerable to directory traversal, this could mean attackers are fifty-fifty able to upload files to unanticipated locations.
Failing to make sure that the size of the file falls within expected thresholds could too enable a grade of denial-of-service (DoS) attack, whereby the attacker fills the bachelor disk space.
How practice file upload vulnerabilities arise?
Given the fairly obvious dangers, it's rare for websites in the wild to take no restrictions whatsoever on which files users are allowed to upload. More unremarkably, developers implement what they believe to exist robust validation that is either inherently flawed or tin be hands bypassed.
For instance, they may attempt to blacklist unsafe file types, merely fail to account for parsing discrepancies when checking the file extensions. Equally with any blacklist, it's also easy to accidentally omit more obscure file types that may still exist unsafe.
In other cases, the website may attempt to check the file type by verifying backdrop that can be easily manipulated by an assaulter using tools similar Burp Proxy or Repeater.
Ultimately, even robust validation measures may be applied inconsistently across the network of hosts and directories that grade 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 trounce for remote code execution. We've even created some interactive, deliberately vulnerable labs and then that you can exercise what you've learned against some realistic targets.
How do web servers handle requests for static files?
Earlier nosotros look at how to exploit file upload vulnerabilities, information technology's important that yous take a basic understanding 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 upshot, 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 human relationship to the filesystem at all. Yet, spider web servers even so deal with requests for some static files, including stylesheets, images, and and then on.
The process for treatment 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 and so 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'due south configuration.
- If this file type is non-executable, such as an image or a static HTML page, the server may just send the file'southward contents to the client in an HTTP response.
- If the file type is executable, such every bit a PHP file, and the server is configured to execute files of this type, it volition assign variables based on the headers and parameters in the HTTP asking before running the script. The resulting output may then 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 by and large respond with an fault. Notwithstanding, in some cases, the contents of the file may still exist served to the customer as obviously text. Such misconfigurations tin can occasionally exist exploited to leak source lawmaking and other sensitive data. You can see an example of this in our information disclosure learning materials.
Tip
The Content-Blazon 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 up by the application code, it normally contains the result of the file extension/MIME type mapping.
Now that you're familiar with the key concepts, let's await at how you tin can potentially exploit these kinds of vulnerabilities.
Exploiting unrestricted file uploads to deploy a spider web shell
From a security perspective, the worst possible scenario is when a website allows y'all to upload server-side scripts, such as PHP, Coffee, or Python files, and is also configured to execute them every bit lawmaking. This makes it piddling to create your own web vanquish on the server.
Web shell
A web beat out 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 crush, you lot effectively have total command over the server. This ways you can read and write capricious files, exfiltrate sensitive information, fifty-fifty use the server to pin attacks against both internal infrastructure and other servers outside the network. For example, the post-obit 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 asking for this malicious file will return the target file's contents in the response.
A more versatile web shell may look something like this:
<?php repeat arrangement($_GET['command']); ?>
This script enables you to laissez passer an arbitrary organisation command via a query parameter every bit follows:
GET /example/exploit.php?command=id HTTP/1.1
Exploiting flawed validation of file uploads
In the wild, information technology's unlikely that y'all'll find a website that has no protection whatsoever against file upload attacks like nosotros saw in the previous lab. But just because defenses are in place, that doesn't hateful that they're robust.
In this section, we'll await at some ways that web servers attempt to validate and sanitize file uploads, every bit well as how you can exploit flaws in these mechanisms to obtain a web crush for remote code execution.
Flawed file blazon validation
When submitting HTML forms, your browser typically sends the provided information in a POST request with the content type awarding/10-www-form-url-encoded. This is fine for sending simple text similar your name, accost, and and so on, but is not suitable for sending large amounts of binary data, such as an entire image file or a PDF certificate. In this case, the content type multipart/form-data is the preferred approach.
Consider a form containing fields for uploading an image, providing a clarification of it, and inbound your username. Submitting such a form might result in a asking that looks something like this:
Mail service /images HTTP/1.1 Host: normal-website.com Content-Length: 12345 Content-Type: multipart/form-information; purlieus=---------------------------012345678901234567890123456 ---------------------------012345678901234567890123456 Content-Disposition: form-data; name="prototype"; filename="example.jpg" Content-Type: image/jpeg [...binary content of case.jpg...] ---------------------------012345678901234567890123456 Content-Disposition: form-data; proper name="description" This is an interesting description of my image. ---------------------------012345678901234567890123456 Content-Disposition: form-data; name="username" wiener ---------------------------012345678901234567890123456--
As y'all can run across, the message body is dissever into separate parts for each of the form's inputs. Each part contains a Content-Disposition header, which provides some basic information about the input field information technology relates to. These individual parts may also contain their own Content-Blazon header, which tells the server the MIME type of the information that was submitted using this input.
One fashion that websites may attempt to validate file uploads is to check that this input-specific Content-Blazon header matches an expected MIME blazon. If the server is only expecting epitome files, for example, it may only permit types like paradigm/jpeg and image/png. Issues can arise when the value of this header is implicitly trusted past the server. If no farther validation is performed to bank check whether the contents of the file actually friction match the supposed MIME type, this defense can exist easily bypassed using tools like Burp Repeater.
Preventing file execution in user-attainable directories
While it's clearly meliorate to forestall dangerous file types being uploaded in the beginning place, the second line of defense is to stop the server from executing any scripts that practise slip through the internet.
Equally a precaution, servers generally only run scripts whose MIME type they have been explicitly configured to execute. Otherwise, they may just 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.1 Host: normal-website.com HTTP/1.one 200 OK Content-Type: text/plain Content-Length: 39 <?php echo system($_GET['control']); ?>
This beliefs is potentially interesting in its own right, as it may provide a way to leak source lawmaking, but it nullifies whatever endeavour to create a web beat.
This kind of configuration often differs between directories. A directory to which user-supplied files are uploaded will probable have much stricter controls than other locations on the filesystem that are causeless to be out of reach for end users. If you can find a way to upload a script to a different directory that's non supposed to incorporate user-supplied files, the server may execute your script after all.
Tip
Spider web servers often use the filename field in multipart/form-information requests to determine the name and location where the file should exist saved.
You should too note that even though you 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 volition often be handled by boosted servers behind the scenes, which may besides be configured differently.
Insufficient blacklisting of dangerous file types
One of the more obvious ways of preventing users from uploading malicious scripts is to blacklist potentially dangerous file extensions like .php. The practise of blacklisting is inherently flawed as it's 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 still exist executable, such as .php5, .shtml, and 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 practice so. For case, earlier an Apache server will execute PHP files requested by a customer, developers might have to add the post-obit 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 too allow developers to create special configuration files within individual directories in guild to override or add to i or more of the global settings. Apache servers, for example, volition load a directory-specific configuration from a file called .htaccess if one is nowadays.
Similarly, developers can brand directory-specific configuration on IIS servers using a web.config file. This might include directives such every bit the following, which in this example allows JSON files to be served to users:
<staticContent> <mimeMap fileExtension=".json" mimeType="application/json" /> </staticContent>
Web servers apply these kinds of configuration files when present, only you're not normally allowed to access them using HTTP requests. Notwithstanding, you may occasionally find servers that neglect to cease you from uploading your own malicious configuration file. In this case, even if the file extension y'all demand is blacklisted, yous may exist able to trick the server into mapping an arbitrary, custom file extension to an executable MIME blazon.
Obfuscating file extensions
Even the virtually exhaustive blacklists can potentially exist bypassed using archetype obfuscation techniques. Allow'due south say the validation code is example sensitive and fails to recognize that exploit.pHp is in fact a .php file. If the code that later on maps the file extension to a MIME type is not instance sensitive, this discrepancy allows you to sneak malicious PHP files past validation that may eventually be executed by the server.
You tin can also achieve similar results using the following techniques:
- Provide multiple extensions. Depending on the algorithm used to parse the filename, the following file may be interpreted every bit either a PHP file or JPG image:
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, forwards slashes, and backward slashes. If the value isn't decoded when validating the file extension, but is later decoded server-side, this can also allow 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 high-level language similar PHP or Java, only 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;.jpgorexploit.asp%00.jpg - Try using multibyte unicode characters, which may be converted to zero bytes and dots after unicode conversion or normalization. Sequences similar
xC0 x2E,xC4 xAEorxC0 xAEmay be translated tox2Eif the filename parsed as a UTF-8 string, but then converted to ASCII characters earlier being used in a path.
Other defenses involve stripping or replacing dangerous extensions to forbid the file from existence executed. If this transformation isn't applied recursively, you tin can position the prohibited cord in such a way that removing it nonetheless leaves behind a valid file extension. For example, consider what happens if y'all 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'south contents
Instead of implicitly trusting the Content-Blazon specified in a request, more secure servers endeavor to verify that the contents of the file actually match what is expected.
In the case of an image upload function, the server might try to verify sure intrinsic backdrop of an prototype, such as its dimensions. If you lot effort uploading a PHP script, for instance, it won't have any dimensions at all. Therefore, the server can deduce that it tin't perhaps exist an image, and refuse the upload accordingly.
Similarly, certain file types may ever incorporate a specific sequence of bytes in their header or footer. These tin be used like a fingerprint or signature to determine whether the contents match the expected type. For example, JPEG files e'er begin with the bytes FF D8 FF.
This is a much more than robust way of validating the file blazon, just even this isn't foolproof. Using special tools, such as ExifTool, it can exist trivial to create a polyglot JPEG file containing malicious code inside its metadata.
Exploiting file upload race conditions
Modernistic frameworks are more than battle-hardened against these kinds of attacks. They more often than not don't upload files directly to their intended destination on the filesystem. Instead, they take precautions like uploading to a temporary, sandboxed directory get-go 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 safety to practice so.
That said, developers sometimes implement their own processing of file uploads independently of any framework. Not just is this fairly complex to do well, it can also introduce dangerous race conditions that enable an attacker to completely featherbed even the well-nigh robust validation.
For example, some websites upload the file directly to the main filesystem and then remove it once more 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, just for the curt fourth dimension that the file exists on the server, the attacker tin can potentially still execute it.
These vulnerabilities are often extremely subtle, making them difficult to discover during blackbox testing unless you can find a way to leak the relevant source lawmaking.
Race weather in URL-based file uploads
Like race atmospheric condition tin can occur in functions that let 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 copy before it can perform whatsoever validation.
Equally the file is loaded using HTTP, developers are unable to utilise 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 proper name, in theory, it should be incommunicable for an attacker to exploit whatever race atmospheric condition. If they don't know the name of the directory, they will exist unable to request the file in club to trigger its execution. On the other hand, if the randomized directory name is generated using pseudo-random functions like PHP's uniqid(), it can potentially exist creature-forced.
To make attacks similar this easier, you can attempt to extend the amount of time taken to process the file, thereby lengthening the window for brute-forcing the directory proper name. Ane way of doing this is by uploading a larger file. If information technology is candy in chunks, you can potentially take advantage of this by creating a malicious file with the payload at the commencement, followed past a large number of arbitrary padding bytes.
Exploiting file upload vulnerabilities without remote code execution
In the examples we've looked at and then far, we've been able to upload server-side scripts for remote code execution. This is the nearly serious event of an insecure file upload role, but these vulnerabilities can withal be exploited in other ways.
Uploading malicious customer-side scripts
Although y'all might not 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, y'all tin potentially apply <script> tags to create stored XSS payloads.
If the uploaded file and so appears on a folio that is visited by other users, their browser will execute the script when information technology tries to render the page. Notation that due to aforementioned-origin policy restrictions, these kinds of attacks will simply work if the uploaded file is served from the same origin to which you upload information technology.
Exploiting vulnerabilities in the parsing of uploaded files
If the uploaded file seems to be both stored and served securely, the concluding resort is to endeavour exploiting vulnerabilities specific to the parsing or processing of dissimilar file formats. For case, you lot know that the server parses XML-based files, such as Microsoft Office .md 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 appropriate 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 spider web interface.
PUT /images/exploit.php HTTP/ane.1 Host: vulnerable-website.com Content-Type: awarding/ten-httpd-php Content-Length: 49 <?php repeat file_get_contents('/path/to/file'); ?>
Tip
You can try sending OPTIONS requests to different endpoints to test for whatever that advertise back up 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 every bit you have the right precautions. In general, the most effective style 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. Information technology's much easier to guess which extensions yous might want to allow than information technology is to judge which ones an aggressor might try to upload.
- Make sure the filename doesn't comprise whatever 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 not upload files to the server's permanent filesystem until they have been fully validated.
- Every bit much as possible, use an established framework for preprocessing file uploads rather than attempting to write your own validation mechanisms.
alexanderjoat1981.blogspot.com
Source: https://portswigger.net/web-security/file-upload
Belum ada Komentar untuk "Dos Program to Upload Files to the Web"
Posting Komentar