Reputation: 1985
I'm building an application that has a HTML GUI interface to create, move and edit boxes (div
) inside a container div
. These boxes get assigned inline styles when editing, these inline styles are saved to the database and are output in the views:
<%= sanitize raw(@slide.content) %>
I want to sanitize the HTML itself, to avoid someone hacking in, for instance, a script tag, through sending that by editing what's sent to the server when the boxes are saved.
Rails 4 has a helper method sanitize
available through the class ActionView::Helpers::SanitizeHelper. When I use this with a test content
value that contains a malicious <script>
tag, the script gets removed just fine. But sanitizing the content also strips CSS properties inside the style tag that are necessary for the boxes, like top
, left
, position
, etc.
In the linked documentation, it's stated that sanitize
will automatically use the function sanitize_css
when it comes across a style attribute:
sanitize_css(style)
Sanitizes a block of CSS code. Used by sanitize when it comes across a style attribute.
I do not want this behaviour of sanitize
. How can I disable sanitize using sanitize_css
, to sanitize the HTML, but not the CSS?
Upvotes: 1
Views: 2776
Reputation: 324
In your config/application.rb
file:
config.action_view.sanitized_allowed_tags = nil
config.action_view.sanitized_allowed_attributes = nil
safe lists found here: loofah html5 safelist
Upvotes: 1
Reputation: 3079
You can allow any attributes and tags you need, so rails will skip them.
sanitize raw(@slide.content), tags: %w(table tr td ul li), attributes: %w(style href title)
Speaking about CSS rules themselves, it's a bit harder to allow additional rules, but still possible. You can monkey patch the HTML::WhiteListSanitizer
class (https://github.com/rails/rails/blob/c71c8a962353642ee44b5cc6ed68dc18322eea72/actionpack/lib/action_view/vendor/html-scanner/html/sanitizer.rb). There are several attributes that can help.
Upvotes: 3