Tips.PHP: Securing ViewSource.php

I’m in the process of creating Usage examples for the brand new version of RESTler. Take a look at the work in progress version here (I would love to hear your thoughts). One of the nice features in that is the ability to see the source code.

I’m using a getsource.php which will return the source code of any php file when the relative path is passed as a query parameter. It is dangerous as any one can take a peek at any of the PHP files in my server including Wordpress config files to reveal the database access details. Safe mode can only save folders outside my web root.

Scott Hurring has his version of source code viewer and does the following to protect sensitive php files from viewing

You may hide certain directories from the user via the use of the $protected array (see code). 

The script takes in the URL ($url), strips out all non-alphanums, all double dots (..), will pre-pend the $DOC_ROOT of your webserver, then resolve that (using realpath()) into a directory on the server. It will then verify that the resulting directory is NOT in the $protected array, and that the file actually exists on disk.

I’m using a different approach, by converting the relative path to realpath and making sure it starts with the same base path check the following code to see the implementation

<?php
if (isset($_GET['file'])) {
    $file = $_GET['file'];
    $require_comments=$file[0]=='.';
    $file = '../'.$file;
    $filepath = realpath($file);
    $basepath = realpath('../../');
    if(strpos($basepath,$filepath)===0){
        #trying to get the source outside restler examples
        die('not allowed');
    }
    if(!file_exists($file))die('file not found');
    $text = file_get_contents($file);
    $file = pathinfo($file, PATHINFO_FILENAME).'.php';
    if(!$require_comments)$text = strip_comments($text);
    die($file.'<pre id="php">'.htmlspecialchars($text)."</pre>");
}else {
    die('no file specified');
}

What else can be done? Please share your thoughts

Leave a Reply