05.05.2013 Views

Programming PHP

Programming PHP

Programming PHP

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

HTTP or FTP URL as a filename, and the document identified by the URL will be<br />

opened. Here’s some exploitable code:<br />

<br />

If $username is set to "http://www.example.com/myfile", a remote file is opened, not a<br />

local one.<br />

The situation is even more dire if you let the user tell you which file to include( ):<br />

<br />

If the user passes a theme parameter of "http://www.example.com/badcode.inc" and<br />

your variables_order includes GET or POST, your <strong>PHP</strong> script will happily load and<br />

run the remote code. Never use parameters as filenames like this.<br />

There are several solutions to the problem of checking filenames.You can disable<br />

remote file access, check filenames with realpath( ) and basename( ), and use the<br />

open_basedir option to restrict filesystem access.<br />

Check for Relative Paths<br />

When you need to allow the user to specify a filename in your application, you can<br />

use a combination of the realpath( ) and basename( ) functions to ensure that the<br />

filename is what it ought to be.The realpath( ) function resolves special markers<br />

such as “.” and “..”. After a call to realpath( ), the resulting path is a full path on<br />

which you can then use basename( ).The basename( ) function returns just the filename<br />

portion of the path.<br />

Going back to our welcome message scenario, here’s an example of realpath( ) and<br />

basename( ) in action:<br />

$filename = $_POST['username'];<br />

$vetted = basename(realpath($filename));<br />

if ($filename !== $vetted) {<br />

die("$filename is not a good username");<br />

}<br />

In this case, we’ve resolved $filename to its full path and then extracted just the filename.If<br />

this value doesn’t match the original value of $filename, we’ve got a bad filename<br />

that we don’t want to use.<br />

Once you have the completely bare filename, you can reconstruct what the file path<br />

ought to be, based on where legal files should go, and add a file extension based on<br />

the actual contents of the file:<br />

include("/usr/local/lib/greetings/$filename");<br />

288 | Chapter 12: Security<br />

This is the Title of the Book, eMatter Edition<br />

Copyright © 2002 O’Reilly & Associates, Inc. All rights reserved.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!