JSON.stringify </script>

Alexander Jones alex at weej.com
Wed Sep 28 18:54:29 UTC 2016

Hi Michał

Embedding a JSON literal into HTML involves first encoding to JSON then
encoding that into HTML. Two stages which must not be confused. The
'encoding into HTML' part is best done in XHTML with CDATA, and the
encoding method is taken care of by whichever XML-generating library you're
using. If you hint it to use CDATA for such a text node, or if for any
other reason it chooses to use CDATA, rather than merely converting every
`<` to `<`, etc., then it will (or should) "escape" `]]>` as
`]]]]><![CDATA[>` or whatever equivalent. See
https://en.wikipedia.org/wiki/CDATA#Nesting for more info. Crucially, this
works for encoding ANY text data into a text node in an XML document, not
just JSON.

Having the specified JSON algorithm in ECMAScript deal with concerns of
embedding into legacy, non XML-based HTML (oh yes, I totally went there! ;)
) is a classic layer violation, which I would guarantee offends 99 out of
100 experienced programmers' sensibilities. :)

Aside, I'll repeat again that this would be largely ineffective - a lot of
JSON that might be dumbly pasted into a text stream of HTML would be
generated by implementations other than that specified by ECMAScript.

Hope this clears it up


On 28 September 2016 at 19:41, Michał Wadas <michalwadas at gmail.com> wrote:

> Actually CDATA suffer the same issue - for string "]]>". Mike Samuel has a
> very strong point here.
> And by saying "it's antipattern, don't do this" we will not make old
> vulnerable code go away. And we have a very good way to stop people from
> shooting their own feet - for free.
> On 28 Sep 2016 8:31 p.m., "Alexander Jones" <alex at weej.com> wrote:
> That's awful. As you say, it's an antipattern, no further effort should be
> spent on this. JSON produced by JavaScript has far more general uses than
> slapping directly into a script tag unencoded, so no-one else should have
> to see this. Also, there are many other producers of JSON than JavaScript.
> Instead, use XHTML and CDATA (which has a straightforward encoding
> mechanism that doesn't ruin the parseability of the code or affect it in
> any way) if you really want to pull stunts like this.
> Alex
> On Wednesday, 28 September 2016, Michał Wadas <michalwadas at gmail.com>
> wrote:
>> Idea: require implementations to stringify "</script>" as
>> "<\uxxxxscript>".
>> Benefits: remove XSS vulnerability when injecting JSON as content of
>> <script> tag (quite common antipattern).
>> Backward compatible: yes, unless binary equality is required and this
>> string is used.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20160928/22ad6c52/attachment-0001.html>

More information about the es-discuss mailing list