3

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?

1 Answer 1

1

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))

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.