Thursday, March 5, 2009

PHP Form, Code Injection

A HTML form, can be used to inject a piece of code to produce results that the hacker wants. An unprotected  form can be used to run a simple php code like ' echo "hello world";'  or a more destructive code.... 

To stop the form from being hacked I use the following steps:

Step 1. Check the data via JavaScript;

Call the JavaScript function by putting onsubmit='return checkform()' in the form tags

The folowing code checks that the password is alpha numerical, and if so returns and processes the form. The main reaon for the JavaSrcipt is to validate the form for the standard user, making sure that the correct data format is entered.

function checkform()
{
re = "no";
repass = /^[0-9A-Za-z]+$/;
if(repass.test(document.form.password.value))
{
re='yes';
}
else
{
alert('Please make sure the password is alpha numeric');
document.form.password.select();
document.form.password.focus();
return false;
}
if(re=="yes")
{
return true
}
}

Step 2.  Check the data via PHP

This code recieves the data from the forms textbox, makes sure that the data is alpha numeric. If the data is not apha numeric the error message is displayed, and the code stops running. 

The main purpose for this extra code, is that the hacker would not be using the form provided, thus rendering the JavaScript useless, so if a hacker or spammer enters any thing but numbers or letters then the code will cease.

$pw = $_POST['password'];

$passpattern = '/^[0-9A-Za-z]+$/';

$errormessage = " field, has invalid information and needs to be changed.";

if (!preg_match("$passpattern", "$pw")) 
{
echo "Your Password $errormessage"; 
exit();
}

Step 3. Preparing the data for MYSQL

The mysql_escape_string() function replaces characters that have a special meaning in MySQL with an escape sequence. eg " is replaced with \" and ' is replaced with \'. This will stop any code being written to the database and executed as it will be displayed as plain text.

If you use  mysql_real_escape_string() as the preffered alternative then you will need to be connected to the database before you run the code.

$pw = mysql_escape_string($pw);

Step 4. Use my examples as a basis to do your own research, and if find and alternative please post.

No comments:

Post a Comment