note 105439 deleted from mongo.security by danbrown
| From: | danbrown@php.net | Date: | Thu, 18 Aug 2011 16:47:58 +0000 |
| Subject: | note 105439 deleted from mongo.security by danbrown | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-182568@lists.php.net to get a copy of this message | ||
Note Submitter: Ludovic Vignals
----
I am looking at ways to prevent Request Injection Attacks and Script Injection Attacks while
minimizing the overhead at the same time.
I wrote this general purpose script to sanitize all form parameters received via an http request
while still being able to take advantage of nested arrays sometime passed in form parameters. It is
a bit of a brute force approach right now but since it is sometime needed to store data from HTTP
GET/POST without knowing the structure of data ahead of time I thought this would come handy. It may
not be bullet proof as is so please post a comment here if you find a hole in this sanitize function
approach or if you have improvement suggestions. Thanks for your feedback!
// Function to sanitize
function sanitize(&$httpreq) { // Use of reference allows for in place update
foreach ($httpreq as $key => &$value) { // Use of reference again
if (is_array($value)) {
sanitize($value); //recursion ensure that nested arrays get sanitized too
}
if (is_string($value)) {
$value = strip_tags($value);
$value = str_replace("$", " $ ", $value);
$value = str_replace("->", " - > ", $value);
$value = str_replace("[", " [ ", $value);
$value = str_replace("]", " ] ", $value);
$value = str_replace(")", " ) ", $value);
$value = str_replace(")", " ( ", $value);
$value = str_replace("\\", " \\ ", $value);
}
if (!is_array($value) && !is_string($value)) die("ERROR: UNEXPECTED VALUE! HTTP
FORM REQUEST ARE EXPECTED TO CONTAIN STRINGS AND/OR ARRAYS");
}
unset($value);
// break the reference with the last element.
// Reference of a $value and the last array element remain even after the foreach loop.
// It is recommended to destroy it by unset().
}
// Sample use
var_dump($_POST); //before
sanitize($_POST);
var_dump($_POST); //after