Categories


Loading feed
Loading feed
Loading feed

PHP Security Tip #8


Withing PHP security topics, there is always more than one way to accomplish a task. Many times it's by combining tactics that we achieve the best security. We've already talked about filtering but beyond filtering we still need to be vigilant and validate input coming in from a user. This brings us to our PHP security of the day.


Always validate user input.

Take for example the following code:

<?php
$myFile = filter_var($_GET['file'], FILTER_SANITIZE_STRING);
include($myFile);
?>


Calling http://example.com/file.php?file=home.php will cause your script to include the file home.php in your current directory. However, if someone comes along and requests http://example.com/file.php?file=badcode.php you will be potentially exposing yourself to executing their code, or your code that you do not want executed in that context.

Do not depend solely on file_exists(). Just because it's a local file does not mean that it's a valid file or even that it's your file. Don't give hackers an easy easy to execute their code on your server.



To protect against this, always filter and validate:

<?php
// filter
$myFile = filter_var($_GET['file'], FILTER_SANITIZE_STRING);

// Then validate
$valid = array('home.php', 'about.php');
If (!in_array($myFile, $valid)) {
            die('Leave, evil hacker');
}

include($myFile);

?>

Comments


Monday, March 12, 2007
=)
8:03PM PDT · russain
FILTER_VAR FOR FILTERING THE GET PARAMETER
10:04PM PDT · veerasekar
Tuesday, March 13, 2007
WHY FILTER?
5:20AM PDT · Piotr Borek [unregistered]
ALWAYS FILTER
6:49AM PDT · Cal Evans (editor)
WHY WOULD SOMEBODY DO THIS?
11:02AM PDT · marc [unregistered]
Monday, June 18, 2007
@CAL EVANS
11:42AM PDT · gilzow
@CAL EVANS
11:43AM PDT · gilzow
RE: ALWAYS FILTER
11:44AM PDT · gilzow
RE: ALWAYS FILTER
11:46AM PDT · gilzow
RE: ALWAYS FILTER
11:46AM PDT · gilzow
RE: ALWAYS FILTER
11:49AM PDT · gilzow
RE: ALWAYS FILTER
1:28PM PDT · gilzow
Loading feed