0

I have a PHP script as below:

10. $json_sanitized = ds($json);
11. echo json_encode ( $json_sanitized );

The ds() function has few rules to sanitize the $json data.

function ds($text, $double = true, $charset = null) {
  if (is_array($text)) {
    // Some code
  } elseif (is_object($text)) {
    // Some code
  } elseif (is_bool($text)) {
    // Some code
  }

  $defaultCharset = 'UTF-8';

  if (is_string($double)) {
    $charset = $double;
  }

  return htmlspecialchars($text, ENT_QUOTES, ($charset) ? $charset : $defaultCharset, $double);
}

But the HP Fortify Scanner still says, Line #11, sends unvalidated data to a web browser, which can result in the browser executing malicious code.

Can anyone help on this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Tarun Upadhyay
  • 724
  • 2
  • 7
  • 16

1 Answers1

0

Per a few other answers on this site, the json_encode function in PHP is generally safe, and there are some options that can help make it safer though additional escaping.

Using the following helps to escape more potentially unsafe characters that Fortify picks up:

echo json_encode($json_sanitized,JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);

Per the json_encode docs and the json constants docs, these constants provide the following (optional) conversions:

  • JSON_HEX_QUOT - All " are converted to \u0022.
  • JSON_HEX_TAG - All < and > are converted to \u003C and \u003E.
  • JSON_HEX_AMP - All &s are converted to \u0026.
  • JSON_HEX_APOS - All ' are converted to \u0027.

You may be able to skip the escaping of the single and double quotes, as I imagine the biggest gripe is that <> are able to be printed unescaped.

Json: PHP to JavaScript safe or not? Is json_encode Sufficient XSS Protection?

kchason
  • 2,836
  • 19
  • 25