Encode HTML tags in JSON

While not encoding the HTML tags in the JSON response is perfectly fine since we set the proper mimetype as well as disable content sniffing a lot of automated code scanner do report this as security bug. Encoding them leads to less discussions and a lot of saved time.
This commit is contained in:
Lukas Reschke 2015-09-03 00:44:46 +02:00
parent e2cc778947
commit f9e90e92d4
3 changed files with 22 additions and 8 deletions

View File

@ -167,6 +167,6 @@ class OC_JSON{
if (is_array($data)) { if (is_array($data)) {
array_walk_recursive($data, array('OC_JSON', 'to_string')); array_walk_recursive($data, array('OC_JSON', 'to_string'));
} }
return json_encode($data); return json_encode($data, JSON_HEX_TAG);
} }
} }

View File

@ -64,7 +64,7 @@ class JSONResponse extends Response {
* @throws \Exception If data could not get encoded * @throws \Exception If data could not get encoded
*/ */
public function render() { public function render() {
$response = json_encode($this->data); $response = json_encode($this->data, JSON_HEX_TAG);
if($response === false) { if($response === false) {
throw new \Exception(sprintf('Could not json_encode due to invalid ' . throw new \Exception(sprintf('Could not json_encode due to invalid ' .
'non UTF-8 characters in the array: %s', var_export($this->data, true))); 'non UTF-8 characters in the array: %s', var_export($this->data, true)));

View File

@ -66,13 +66,27 @@ class JSONResponseTest extends \Test\TestCase {
$this->assertEquals($expected, $this->json->render()); $this->assertEquals($expected, $this->json->render());
} }
/**
* @return array
*/
public function testRenderProvider() {
return [
[
['test' => 'hi'], '{"test":"hi"}',
],
[
['<h1>test' => '<h1>hi'], '{"\u003Ch1\u003Etest":"\u003Ch1\u003Ehi"}',
],
];
}
public function testRender() { /**
$params = array('test' => 'hi'); * @dataProvider testRenderProvider
$this->json->setData($params); * @param array $input
* @param string $expected
$expected = '{"test":"hi"}'; */
public function testRender(array $input, $expected) {
$this->json->setData($input);
$this->assertEquals($expected, $this->json->render()); $this->assertEquals($expected, $this->json->render());
} }