Mage: Should model.escape be used instead of model.get?

Today I read about Cross-Site Scripting (XSS) attacks. It seems that Backbone has model.escape('attr') built-in and from what I can say it should always be used instead of model.get('attr') to prevent these attacks.

I did an initial search, but did not find any recommendations of this kind. Should I always use model.escape('attr') when retrieving values ​​from a model?

+4
source share
4 answers

Using Underscore templates, I usually saw / did it like this:

 var TemplateHtml = "<div><%- someModelAttribute %></div>"; // Really, you should load from file using something like RequireJS var View = Backbone.View.extend({ _template: _.template(TemplateHtml), render: function() { this.$el.html(this._template(this.model.toJSON())); } }); 

When you use <%- someModelAttribute %> , Underscore knows to avoid the given values ​​(unlike <%= someModelAttribute %> , which directly enters the attribute without escaping).

+5
source

Instead of model.escape (), see _.escape when rendering. This way you can use your models however you want, but be careful to avoid rendering. Simply use _.escape in your template during rendering. This avoids XSS attacks.

See this method:

http://underscorejs.org/#escape

+3
source

Yes, for aviod xss attacks you can always use model.escape (), which is preferable, and also used to exit the html content ...

But if you are going to use the data right away ... you can just use model.get () ...

+1
source

I found a good article on when to use the escape function . The author claims that you should always use escape, except when you are definitely not going to execute the value of the model attribute. For example, if you checked the model attribute is not null :

 var model = new Backbone.Model({foo: "Bar"}); if (model.get("foo") != null) { //notice how here we did not use escape $("h1").html(model.escape("foo")); //but here we do } 

One related point to be aware of is that if you check the return value from model.escape("foo") , it will always return a string. Therefore, if you expect null , then you may be confused.

 console.log(model.get("foo")); // null console.log(model.escape("foo")); // "" 

However, as Jeremy Ashkenas points out in a pull report that requests this problem , it makes no sense to check for an attribute after avoiding it.

0
source

All Articles