Level 5: Apache's htaccess trick to execute benign files as PHP

Let’s move on to the Level 5 section. 

In this section, if we try to upload the .php file, we will receive the following error message. 

Let’s try to upload "phpinfo.php" again after changing the content type. 

But similar to the previous, we have received the same problem.

If we try to upload a gif file, we will receive a successful upload message. 

Since, the uploaded file is in form of image format, which means it can’t run as a PHP file.

Similar to the previous level, if we try to change the file format name to PHP, we will receive a similar "Failed" message. 

The following PHP code does not allow HTML, or PHP files during the upload process:

<?php
$blacklist = array(".php","html","shtml",".phtml", ".php3", ".php4",".php7");
foreach ($blacklist as $item) {
if(preg_match("/$item\$/", $_FILES['uploadedfile']['name'])) {
  if(isset($_FILES['uploadedfile'])){echo "We do not allow HTML , PHP files\n";}
exit;
               }
        }
$uploaddir = 'uploads/';
  $uploadfile = $uploaddir . basename($_FILES['uploadedfile']['name']);
if (move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $uploadfile)) {
echo "File is valid, and was successfully uploaded.\n";
}
 ?>
 <?php if($uploadfile!= '') { echo "<a href=\"$uploadfile\">Uploaded</a>"; } ?>

There are two ways in which we can trick Apache to execute a file with a safe extension as PHP. 

  • The SetHandler method
  • The AddType method


Using Set Hander Method

We uploaded the following .htaccess file, which tricks Apache to execute any file containing ".gifas a valid PHP file by forcing through the SetHandler directive:

Open a text editor and type the following code. 

Now save it as .htaccess

Remember to save this file in a fresh directory(like Download, Document), where there will be no hidden files and directories.

Now, We will have to upload the .htaccess file, which tricks Apache to execute any file containing .gif as a valid PHP file by forcing through the SetHandler directive.

Now, we upload the file with the name phpinfo.gif

Once it is uploaded, we can access the file.

As you can notice, this safe .gif file gets executed as a valid PHP file.


Using the AddType method

Similar to the SetHandler method, here, we instead map a new file extension, such as .lol, which gets executed as a PHP file.

To achieve this, we upload the following as the .htaccess file.

Then we upload a file with .lol as the file extension, say phpinfo.lol, and then, access the file from a browser.

Observe the file extension in the URL, it's .lol, which gets mapped to PHP and is executed accordingly.

Post a Comment

If you have any doubts or any queries you can specify here.

Previous Post Next Post