PHP Form Script Security
Wednesday, January 4th, 2006Some ideas to tighten up form script security … more specifically to counter form spoofing and cross browser attacks.
(1) Check for extra _POST variables, and disallow any _GET variables.
{
$limit_post=count($_POST);
$limit_get=count($_GET);
if ($limit_post>8||$limit_get>0)
{
include (”formhead.php”);
echo “Submission failed.”;
include (”form2.php”);
exit;
}
}
(2) Prevent the exceeding of maximum field length from the server side in the script - setting form field maximum length inputs is not sufficient.
{
$length = strlen($_POST[’Name’] || $_POST[’Email’] || $_POST[’Address’] || etc);
if($length>30)
{
include (”formhead.php”);
echo “Too many characters.”;
include (”form2.php”);
exit;
}
}
(3) Check for legal use of characters (white list approach).
{
if (eregi(”[^-a-z]+$”, $_POST[’Name’]) || eregi(”[^-/\.a-z0-9]+$”, $_POST[’Address’]) || eregi(”[^-a-z]+$”, $_POST[’City’]) etc)
{
include (”formhead.php”);
echo “Invalid characters.”;
include (”form2.php”);
exit;
}
}
(4) Check for well-formed email address.
{
if (!eregi(”^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*$”, $_POST[’Email’]))
{
include (”formhead.php”);
echo “Please enter a valid email.”;
$_POST[’Email’]=”";
include (”form2.php”);
exit;
}
}
(5) Use quotemeta to filter output (note that quotemeta doesn’t filter the pipe character - hence the productiveness of using the previous eregi function).
(6) Use the Session token method described at http://shiflett.org/archive/96 to further prevent XSS attacks.
eg.
In the document head:
<?php $token = md5(uniqid(rand(), true));
$_SESSION[’token’] = $token; ?>
In the form:
<input type="hidden" name="sekret" value="<?php echo $token; ?>" />
In the script:
{
if ($_SESSION[’token’] != $_POST[’token’])
{
echo “Invalid submission.”;
//go to error page
exit;
}
}
References:
http://phpsec.org/projects/guide/2.html
http://www.devshed.com/c/a/PHP/Reconsidering-PHP-variables/
http://au.php.net/manual/en/function.quotemeta.php
http://shiflett.org/
