Link Search Menu Expand Document

Cross-Site Scripting in Ruby

Play SecureFlag Play Ruby Labs on this vulnerability with SecureFlag!

Prevention

Apply the recommended security controls depending on the framework and template engine of choice.

Ruby On Rails

Rails provides ERB (Embedded RuBy) as a template engine to generate dynamic web pages.

Before Rails 3.x, the function escapeHTML() (or its alias h()) needed to be called to escape HTML output in all templates, but in more recent versions, it is on by default in all of the view templates.

To bypass the automatic encoding in recent Rails versions, calling html_safe or prepending raw on a string sets the string as HTML Safe, and ERB inserts it unaltered into the output.

Strings in JavaScript contexts should be explicitly encoded by prepending escape_javascript or j to the variable. This escaping does not encode generic JavaScript code and should only be used with JavaScript string literals.

Context Code Rails >=3.x ERB Encoding mechanisms
HTML Code and Attribute <%= user-controlled-variable %> HTML Escaped
Encode data for use in HTML using HTML entity encoding
JavaScript Strings Literals <script>var id = '<%= escape_javascript user-controlled-variable %>';</script> Escapes carriage returns and single and double quotes for JavaScript strings.
Encode data for insertion inside a JavaScript string.

Slim Template Engine

Slim is an alternative template engine to Embedded RuBy. By default, special HTML characters are escaped. However, by using the == operator, data is inserted into the output unaltered. Ensure that the = operator, which escapes by default, is used wherever possible instead.

Additionally, Ruby provides the sanitize helper method to all templates. This method removes unsafe tags and attributes from a string before the escaping of characters. By using this method in conjunction with the = operator when inserting user input into a web page, risk can be minimized.

Code Output
= '<a href=javascript:xxx>link</a><img onerror=xxx />' &lt;a href=javascript:xxx&gt;link&lt;/a&gt;&lt;img onerror=xxx /&gt;
= sanitize <a href=javascript:xxx>link</a><img onerror=xxx />' link

References

OWASP - Cross-Site Scripting (XSS) OWASP - Code Review Guide OWASP - Cross-Site Scripting Prevention Cheat Sheet