Link Search Menu Expand Document

Cross-Site Scripting in Ruby


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.


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