I'm writing a script which takes user supplied Json files runs it through json_decode($string, true) and prints the arrayvalues. Looking at the $GLOBALS array I found out that the CMS I'm using(Drupal 7) is exposing db credentials in plain text.
Is there a way that somebody can inject code like var_dump($GLOBALS) via a supplied JSON file? Do i need to check the array supplied via json_decode for malicious code?
Example Code:
<?php
$jsTestString = '{ "identifier":{"inject":var_dump($GLOBALS) }}';
$jsonTestArray = json_decode($jsTestString, true);
print($jsonTestArray['identifier']['inject']);
// this thankfully doesn't work
My Answer:
Yes, it is important to sanitize user-supplied JSON data before decoding it with json_decode. This is because JSON data can contain malicious code that could potentially be executed when decoded. One way to sanitize the JSON data is to use a combination of functions like filter_var, htmlentities, and htmlspecialchars to remove any potentially harmful characters or code.
Here is an example of how you can sanitize user-supplied JSON data before decoding it:
php
// Sanitize user-supplied JSON data
$user_json = filter_var($_POST['json_data'], FILTER_SANITIZE_STRING);
$user_json = htmlentities($user_json, ENT_QUOTES, 'UTF-8');
$user_json = htmlspecialchars($user_json, ENT_QUOTES, 'UTF-8');
// Decode the sanitized JSON data
$array = json_decode($user_json, true);
// Print the array values
print_r($array);
By sanitizing the user-supplied JSON data before decoding it, you can help prevent any potential security vulnerabilities in your script.
Rate this post
4 of 5 based on 1955 votesComments