i would like to know if there is a possible injection of code (or any other security risk like reading memory blocks that you weren’t supposed to etc…) in the following scenario, where unsanitized data from HTTP GET is used in code of PHP as KEY of array.
This supposed to transform letters to their order in alphabet. a to 1, b to 2, c to 3 …. HTTP GET “letter” variable supposed to have values letters, but as you can understand anything can be send to server:
HTML:
http://www.example.com/index.php?letter=[anything in here, as dirty it can gets]
PHP:
$dirty_data = $_GET['letter'];
echo "Your letter's order in alphabet is:".Letter2Number($dirty_data);
function Letter2Number($my_array_key)
{
$alphabet = array("a" => "1", "b" => "2", "c" => "3");
// And now we will eventually use HTTP GET unsanitized data
// as a KEY for a PHP array... Yikes!
return $alphabet[$my_array_key];
}
Questions:
- Do you see any security risks?
- How can i sanitize HTTP data to be able use them in code as KEY of an array?
- How bad is this practice?
I can’t see any problems with this practice. Anything you… errr… get from
$_GETis a string. It will not pose any security threat whatsoever unless you calleval()on it. Any string can be used as a PHP array key, and it will have no adverse effects whatsoever (although if you use a really long string, obviously this will impact memory usage).It’s not like SQL, where you are building code to be executed later – your PHP code has already been built and is executing, and the only way you can modify the way in which it executes at runtime is by calling
eval()orinclude()/require().EDIT
Thinking about it there are a couple of other ways, apart from
eval()andinclude(), that this input could affect the operation of the script, and that is to use the supplied string to dynamically call a function/method, instantiate an object, or in variable variables/properties. So for example:…would be a very bad idea, if you were to do it with sanitizing
$userdatafirst.However, for what you are doing, you do not need to worry about it.