在javascript中转义</ script>标记

Cam*_*mel 9 javascript ruby haml ruby-on-rails backbone.js

我正在使用骨干,以及在页面加载时传递集合的一般方法

window.router = new Routers.ManageRouter({store: #{@store.to_json});
Run Code Online (Sandbox Code Playgroud)

这很好,效果很好,直到有人决定将文本" <script>alert("owned")</script>" 添加到其中一个商店字段.最后</script>明显关闭了javascript.怎么能绕过这个呢?

  :javascript
    $(function() {
      window.router = new Dotz.Routers.ManageRouter({store: #{@store.to_json}});
      Backbone.history.start();
    });
Run Code Online (Sandbox Code Playgroud)

以上输出:

<script>
    //<![CDATA[
      $(function() {
        window.router = new Dotz.Routers.ManageRouter({store: '{"_id":"4f3300e19c2ee41d9a00001c", "points_text":"<script>alert(\"hey\");</script>"'});
        Backbone.history.start();
      });
    //]]>
  </script>
Run Code Online (Sandbox Code Playgroud)

Phr*_*ogz 15

在一个<script>块中,在语法上非法的,</后面跟着一个名字 - 不只是 - 所以</script>你需要在任何可能出现的地方逃脱.例如:

:javascript
   var foo = { store: #{@store.to_json.gsub('</','<\/')} };
Run Code Online (Sandbox Code Playgroud)

这将<\/在JS字符串中创建序列,该序列被解释为与之相同</.确保在gsub替换字符串中使用单引号,否则gsub( "</", "<\\/" )由于Ruby中单引号和双引号之间的区别而使用.

显示在行动中:

irb:02.0> s = "<b>foo</b>" # Here's a dangerous string
#=> "<b>foo</b>"

irb:03.0> a = [s]          # Wrapped in an array, for fun.
#=> ["<b>foo</b>"]

irb:04.0> json = a.to_json.gsub( '</', '<\/' )  # Sanitized
irb:05.0> puts json        # This is what would come out in your HTML; safe!
#=> ["<b>foo<\/b>"]

irb:06.0> puts JSON.parse(json).first  # Same as the original? Yes! Yay!
#=> <b>foo</b>
Run Code Online (Sandbox Code Playgroud)

如果您使用的是Rails(或ActiveSupport),则可以启用JSON转义:

ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
Run Code Online (Sandbox Code Playgroud)

看到行动:

irb:02.0> a = ["<b>foo</b>"]
irb:03.0> puts a.to_json # Without the magic
#=> ["<b>foo</b>"]

irb:04.0> require 'active_support'
irb:05.0> ActiveSupport::JSON::Encoding.escape_html_entities_in_json = true
irb:06.0> puts a.to_json # With the magic
#=> ["\u003Cb\u003Efoo\u003C/b\u003E"]
Run Code Online (Sandbox Code Playgroud)

它生成的JSON比解决这个特定问题所需的更冗长,但它是有效的.