Skip to content

Commit

Permalink
html_safe option protects against comment injection
Browse files Browse the repository at this point in the history
When encoding with the html_safe option, also encode `<` into `\\u003C`
to protect against injecting `<!--` HTML comments into JSON.

Closes #109
  • Loading branch information
michalmuskala committed May 4, 2020
1 parent 91a4eaf commit 188e66b
Show file tree
Hide file tree
Showing 2 changed files with 4 additions and 3 deletions.
2 changes: 1 addition & 1 deletion lib/encode.ex
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ defmodule Jason.Encode do
slash_escapes = Enum.zip('\b\t\n\f\r\"\\', 'btnfr"\\')
surogate_escapes = Enum.zip([0x2028, 0x2029], ["\\u2028", "\\u2029"])
ranges = [{0x00..0x1F, :unicode} | slash_escapes]
html_ranges = [{0x00..0x1F, :unicode}, {?/, ?/} | slash_escapes]
html_ranges = [{0x00..0x1F, :unicode}, {?<, :unicode}, {?/, ?/} | slash_escapes]
escape_jt = Codegen.jump_table(html_ranges, :error)

Enum.each(escape_jt, fn
Expand Down
5 changes: 3 additions & 2 deletions test/encode_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,9 @@ defmodule Jason.EncoderTest do
assert to_json("☃a", escape: :unicode_safe) == ~s("\\u2603a")
assert to_json("𝄞b", escape: :unicode_safe) == ~s("\\uD834\\uDD1Eb")
assert to_json("\u2028\u2029abc", escape: :javascript_safe) == ~s("\\u2028\\u2029abc")
assert to_json("</script>", escape: :html_safe) == ~s("<\\/script>")
assert to_json(~s(<script>var s = "\u2028\u2029";</script>), escape: :html_safe) == ~s("<script>var s = \\\"\\u2028\\u2029\\\";<\\/script>")
assert to_json("</script>", escape: :html_safe) == ~s("\\u003C\\/script>")
assert to_json(~s(<script>var s = "\u2028\u2029";</script>), escape: :html_safe) == ~s("\\u003Cscript>var s = \\\"\\u2028\\u2029\\\";\\u003C\\/script>")
assert to_json("<!-- fake comment", escape: :html_safe) == ~s("\\u003C!-- fake comment")
assert to_json("áéíóúàèìòùâêîôûãẽĩõũ") == ~s("áéíóúàèìòùâêîôûãẽĩõũ")
assert to_json("a\u2028a", escape: :javascript_safe) == ~s("a\\u2028a")
assert to_json("a\u2028a", escape: :html_safe) == ~s("a\\u2028a")
Expand Down

0 comments on commit 188e66b

Please sign in to comment.