javascript Backbone.js 和 XSS/HTML 转义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12586899/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Backbone.js and XSS/HTML escaping
提问by hupf
I'm building a Backbone.js application and am wondering what's the best way to deal with XSS respectively HTML escaping when using Backbone.js.
我正在构建一个 Backbone.js 应用程序,我想知道在使用 Backbone.js 时分别处理 XSS 和 HTML 转义的最佳方法是什么。
In the basic Todos example applicationfrom the official Backbone.js documentation, the data is not escaped. Since this data is used in the template to render the todo entries, it is possible to execute Javascript codeby entering the following text (can be reproduced at the link above):
在官方 Backbone.js 文档中的基本Todos 示例应用程序中,数据没有被转义。由于此数据在模板中用于渲染 todo 条目,因此可以通过输入以下文本来执行 Javascript 代码(可以在上面的链接中复制):
"><script>alert('xss');</script>
When using a REST server as storage backend, this XSS is persistent for every user.
当使用 REST 服务器作为存储后端时,这个 XSS 对每个用户都是持久的。
How do you solve this problem?
你怎么解决这个问题?
My idea is to escape the data on the server, so the then returned data is safe to be used in a template. Do I then have to always use wait: true
, to make sure no unescaped data is rendered? And for editing, add another attribute with the unescaped data, that can then be used to fill the textfield using .val()
?
我的想法是对服务器上的数据进行转义,因此返回的数据可以安全地用于模板中。那么我是否必须始终使用wait: true
, 以确保没有呈现未转义的数据?对于编辑,使用未转义的数据添加另一个属性,然后可以使用.val()
?
Or do you do none of this and escape the data on the client, before rendering the template?
或者在渲染模板之前,您不执行这些操作并转义客户端上的数据?
回答by Rob W
The Todo example is not the cleanest example. It uses underscore's template engine, as follows:
Todo 示例并不是最干净的示例。它使用underscore 的模板引擎,如下:
<input class="edit" type="text" value="<%= title %>" />
To correctly escape the HTML, use <%-
instead of <%=
:
要正确转义 HTML,请使用<%-
代替<%=
:
<input class="edit" type="text" value="<%- title %>" />
回答by Levsero
The standard way in backbone is to use model.escape(attribute)
.
主干中的标准方法是使用model.escape(attribute)
.
From the backbone docs backbonejs.org/#Model-escape:
从主干文档backbonejs.org/#Model-escape:
"Similar to get, but returns the HTML-escaped version of a model's attribute. If you're interpolating data from the model into HTML, using escape to retrieve attributes will prevent XSS attacks."
“类似于 get,但返回模型属性的 HTML 转义版本。如果您将模型中的数据插入 HTML,使用转义检索属性将防止 XSS 攻击。”
var hacker = new Backbone.Model({
name: "<script>alert('xss')</script>"
});
alert(hacker.escape('name'));