CSS Injection in Rails

CSS Injection happens when a malicious party is able to alter your webpage by making use of user-defined styles. If your Rails application allows users to define a color which is then served back through CSS using a view:

<div style="background: <%= user.background_color %>;">

Then a user could supply a value which alters the page layout or content.

What are the risks?

A major risk of CSS injection is abuse of the content directive to rewrite a page’s content. Additionally, if a user is able to edit the style of forms seen by others, they could trick those users into putting personal data in the public.

How can I prevent CSS Injection?

The easiest way to prevent injection attacks is to validate user-provided values. Instead of giving end users the ability to set their own values, you can also give users a pre-defined list which you’ve already validated.