Protecting the crown jewels: stopping your critical PHP from leaking onto the web

Despite what you may be thinking about this blog turning into a Facebook blog (its not - I promise!), I noted with interest the recent news about some of Facebook’s source code getting leaked into the web, apparently due to a misconfigured web server sending out the PHP source code unprocessed. Based on what has been happening lately, I bet there were a few red faces that day…

I’ve not taken a look at the source for various reasons so I don’t know how critical the code was, but there are some simple steps that we can all take to protect some of the most crucial bits of source code in our PHP applications from suffering the same fate.

What do I mean by critical? Well, do you store database hostnames, usernames and passwords in your PHP? Details of stored procedures? Raw SQL? Authentication or other security code? Can you imagine what would happen if someone got hold of the raw source for that?! Luckily for us there is a very simple step that mitigates the accidental serving of your PHP in its unprocessed state.

Store critical PHP above the root

On probably all web hosts these days, you’ll have a “web root” folder (often called “public_html”) of some sort that is the absolute “root” or base of your site - this is where your index.html (for example) lives and is the place the server looks when someone visits. Provided it is configured correctly, a server will never serve any files above the root folder, but the server’s PHP process has access to this folder. In this image below of the folder structure of the hypothetical “mysite.com”, both the public_html and public_ftp files (green arrow) will be served by the server (as the names suggest!), but those folders above the root (red arrow) will not be served.

Webroot

So for this example, we could happily put our super-secret critical PHP files in the “lib” directory, using simple includes like so:


<?php

include("../lib/myCriticalCode.php");

// ... any non-critical code, such as other includes to critical files.

?>

So now if the server breaks, all anyone will see is some includes to the real files hidden away where they wont be able to get them! And there is no reason why you have to only “hide” just critical code this way - you could simply have “dummy” PHP files in the root that have a single include to the “real” file if you are really paranoid!

Its worth remembering that although this will prevent the accidental release of your code, if someone has gained access to your server directly, there isn’t much you can do at all.

Leave a Comment

Please note: Comment moderation is enabled and may delay your comment. There is no need to resubmit your comment.