Is it safe to call json_decode on user input?

Fabrício Matté picture Fabrício Matté · Sep 6, 2012 · Viewed 11.2k times · Source

I'm storing a JSON encoded array of integer indexes => integer values in a cookie.

Obviously cookies can be easily manipulated like any other user input, so here's my cookie getter validation:

if ($_COOKIE['myCookie']) { //if cookie exists
    $myCookie = json_decode($_COOKIE['myCookie'], true);
    if (!is_array($myCookie)) { //in case decoding fails or bad cookie
        $myCookie = array(); //sets it as empty array
    }
} else { //if cookie doesn't exist, uses an empty array instead
    $myCookie = array();
}

Then before using any of the values, I check if it exists in the array and test against a list of white-listed values - this part seems pretty safe but I'm posting it as it's part of the validation:

if (!empty($myCookie[$index])) { //checks if index exists and is truthy
    if ($myCookie[$index] !== 1 && $myCookie[$index] !== 2) { //values whitelist
        die('Hacking attempt through cookies exploit.');
    }
    //use the cookie data now
}

Back to the question, is it safe to call json_decode directly on the cookie? Can users manipulate the cookie to run arbitrary code?

I've been reading around many topics on SO so far and what I found is that unserialize() is dimmed unsafe because it calls constructors, but json_decode is technically safe. I've read through their php.net pages but those do not address security directly.

My addon is reaching the live beta very soon, so I'm wondering if calling json_decode directly on the cookie is safe enough or if I should run some type of validation before calling json_decode. I could run a preg_match too, but as I'm testing against a whitelist of values before using them, there should be no problem unless json_decode somehow runs arbitrary code, which it doesn't, right?

I know that json_encode returns NULL if it's not valid JSON, but I'm wondering if this is the right approach or should I add some kind of validation before calling json_decode?

Sorry if this is too stupid of a question, I just have very little experience with cookies/JSON and wouldn't like to be the one blamed for having our server's database dropped. Any help/info is appreciated. =]

Answer

xdazz picture xdazz · Sep 6, 2012

Using json_decode to decode the user input directly has no security problem.

It is just string parsing, won't do any string eval.

json_decode in php is like JSON.parse in javascript, and both of them could be used directly on the user input, they are safe at the decoding time.

But after being decoded, you have to validate the data for your requirement.