13

I want to allow the users of a web app that I'm building to write their own CSS in order to customize their profile page.

However I am aware of this opening up for many security risks, i e background: url('javascript:alert("Got your cookies! " + document.cookies').

Hence I am looking for a solution to sanitize the CSS while still allowing as much CSS functionality as possible for my users.

So my questions if anyone anyone knows of a gem or a plugin to handles this? I've googled my brains out already so any tips would be really appreciated!

Erik
  • 131
  • 1
  • 3
  • just curious, how are you storing your CSS? in database or as a file for each user? – Shripad Krishna Jun 16 '10 at 07:38
  • Wow.. crazy that you can execute javascript from CSS like that. No idea how to solve it though - sorry! – zaius Jun 16 '10 at 07:48
  • Shripad K: I'll store the CSS in the database. zaius: Yup! Check out this page: http://guides.rubyonrails.org/security.html#css-injection – Erik Jun 16 '10 at 07:55

2 Answers2

7

Rails has a built-in css sanitizer

See http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/sanitize_css and its parent http://apidock.com/rails/ActionView/Helpers/SanitizeHelper/sanitize

> ActionController::Base.helpers.sanitize_css('background:#fff')
=> "background: #fff;" 
> ActionController::Base.helpers.sanitize_css('javascript:alert("garr");')
=> "" 
mylescarrick
  • 1,680
  • 8
  • 10
  • Ok, thank you! But as I understand it this method is only used to sanitize a style attribute on a HTML element. It can't be used to sanitize an entire stylesheet…? – Erik Jun 16 '10 at 17:34
  • It should be just the same - one line or a stack of lines... it won't matter. – mylescarrick Jun 17 '10 at 06:55
  • 1
    It does not handle entire stylesheet. – Habax Mar 27 '13 at 16:19
  • `full_stylesheet.gsub(/\{([^}]*)\}/m){ '{' + ActionController::Base.helpers.sanitize_css($1) + '}'; }` could be enough. – Habax Mar 27 '13 at 16:37
1

There's also some code called css_file_sanitize: https://github.com/courtenay/css_file_sanitize

Comparing it to the Rails sanitize command I find that both use regular expressions to strip out undesirable portions of the CSS.

Here's the source for css_file_sanitize: https://github.com/courtenay/css_file_sanitize/blob/master/lib/css_sanitize.rb

Here's the source for Rails sanitize: https://github.com/rails/rails/blob/master/actionpack/lib/action_controller/vendor/html-scanner/html/sanitizer.rb

Purplejacket
  • 1,808
  • 2
  • 25
  • 43