alexJoe
alexJoe

Reputation: 72

How to prevent users from downloading source code files using the PHP download option I have for downloading pdf files in my web application?

Download.php

<?php 
$file = $_GET['file'];
if(file_exists($file)) {
header('Content-Description: File Transfer');
header('Content-Type: application/octet-stream');
header('Content-Disposition: attachment; filename='.basename($file));
header('Content-Transfer-Encoding: binary');
header('Expires: 0');
header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
header('Pragma: public');
header('Content-Length: ' . filesize($file));
ob_clean();
flush();
readfile($file);
exit;
}
?>

Following is the JavaScript code I'm using to pass the url to php script: Download.js

init:function(){
    this.control({
        '#downloadSite': {
            load:function(tree, node, records, successful, eOpts)
            {

            },

            itemclick:  function(tree, record, item, index)
            {
                if(record.get('id') == 300){
                    window.open('Download.php?file=../TAB/'+record.get('url'));
                }
                else{
                    window.open('Download.php?file=../PDF/'+record.get('url'));
                }                   
            },
            beforeitemclick:  function(tree, record, item, index)
            {
                if(record.get('leaf') == false) return false;
            },
            beforeitemdblclick: function(){
                return false;
            }
        }
    });
}

If I am entering "Download.php?file=../web.config" in the url , web.config file is being downloaded. I want to prevent direct download of source code. the download option is for downloading pdf files that I have stored in the pdf's folder in the main directory.

Please help !!

Upvotes: 1

Views: 1499

Answers (2)

johnny
johnny

Reputation: 19735

Use this in web.config,

<authorization>
    <allow users="user1, user2"/>
    <deny users=”?”/>
</authorization>

https://support.microsoft.com/en-us/help/815151/how-to-restrict-specific-users-from-gaining-access-to-specified-web-re

Don't allow the code to circumvent this, as Michael M is saying.

Upvotes: 0

Michael M
Michael M

Reputation: 325

You've fallen fowl of a pretty bad design decision here that makes you vulnerable to file system traversal.

You might consider:

  1. Ensure the requested file ends in .pdf
  2. Ensure that the file being read ends in .pdf
  3. Drop any requests where the file parameter contains ..

Given Download.php doens't look to be ensuring requesters are authenticated at all, I would suggest maybe having your PDF documents live within a web accessible directory and just linking directly to them, instead of creating an attack vector that could compromise your server.

Upvotes: 1

Related Questions