Click to See Complete Forum and Search --> : SQL Injection Help.....


jesseainskeep
07-11-2007, 11:41 AM
As of now, I have a form people fill out that then generates an email and sends it to me. I take the info, go to the CMS I created, key in (copy and paste) the information in and it goes to the website.

I want to take the form and have it send to a holding table, so I can view the records on the holding table and then just move them over to the live table, if this makes sense, but I'm worried about a hacker being able to dump my tables or causing problems.

On the validate page, after the form is submitted, here is what I have....


if($_SERVER['HTTP_REFERER'] == "http://mysite.com/form"){
foreach ($_POST as $key=>$val){
$_POST[$key] = strip_tags($val);
$_POST[$key] = htmlspecialchars($val);
$_POST[$key] = addslashes($val;)
}

//Do other hygiene and submit to database from here.
}else{
echo "Error";
}


Now I'm mostly just worried about SQL Injections. Someone hacking the database and things like that. How secure does this look?

MrCoder
07-11-2007, 12:45 PM
Check the post I made here (http://www.webdeveloper.com/forum/showthread.php?t=151334)

pcthug
07-11-2007, 07:28 PM
1. If a hacker has gone to the trouble of form spoofing there's no reason they won't also send along the HTTP Referer headers you are looking for, so you can probably save a nanosecond or two if you don't check the HTTP Referer value.

2. Generally, it's best to store the raw version of your data (no strip_tags() or htmlspecialchars()). Though if you are converting all applicable characters to HTML entities there is no real need to use strip_tags() is there?

3. Use mysql_real_escape_string() or your equivalent database function. In GBK, misinterpretation of a multi-byte character by addslashes() results in a slash being passed through and thus leading to a SQL injection vulnerability.

So something like this


if (!empty($_POST))
{
foreach ($_POST as $key => $value)
{
$_POST[$key] = sanitize($value);
}
}
else
{
// No POST Data
}

function sanitize($mixed)
{
if (is_array($mixed))
{
foreach ($mixed as $key => $value)
{
$mixed[$key] = sanitize($value);
}

return $mixed;
}
elseif (ctype_digit($mixed))
{
return (int)$mixed;
}
else
{
return mysql_real_escape_string(htmlspecialchars($mixed, ENT_QUOTES, 'UTF-8'));
}
}

jesseainskeep
07-12-2007, 08:38 AM
On this line:

return mysql_real_escape_string(htmlspecialchars($mixed, ENT_QUOTES, 'UTF-8'));

Isn't htmlspecialchars() redundant? I thought mysql_real_escape_string took care of everything except % and _.

pcthug
07-12-2007, 08:15 PM
htmlspecialchars() prevents HTML being displayed on output and is one step towards protecting yourself from XSS attacks. Though if you wish to exclude the htmlspecialchars() call you will still be safe from SQL Injection. Although I'd suggest you use htmlspecialchars() when outputting this data.