Reputation: 10825
In an application I am working on, a client-side view is generated based on some records in the database. I am first generating JSON of the records, saving it in a variable in my page, then using JS to build the interface.
The problem is that the records contain user-generated fields, and the application is thus susceptible to XSS. If you let the JSON pass through escape_html
(by not calling html_safe
on it), it will screw up the quotes.
To get to the code. In my model:
Class Foo
# ...
def describe_for_view
[{:title => "hello", :content => "<script>I.Am.Evil()</script>"}]
end
end
Somewhere in my view:
<script>
var describedForView = $.parseJSON("<%= escape_javascript(@foo.describe_for_view.to_json).html_safe %>");
</script>
Then in my javascript:
$("body").append("title: " + describedForView[0].title + ", content: " + describedForView[0].content);
What I am currently doing is that I am wrapping the access to the user-generated fields with a call to $.sanitize
as defined by:
$.sanitize = function(str) {
return $("<div/>").text(str).html();
};
Things work this way, but I don't think it is clean.
Any suggestions?
Upvotes: 3
Views: 1281
Reputation: 5055
Rails 3 has a built in SanitizeHelper which takes a whitelist approach. I would either call it on user data before persisting it to the database, or in your escape_javascript call:
escape_javascript(sanitize(some_stuff.to_json))
Upvotes: 1