imedo Development Blog

there is no charge for awesomeness

Secure coding with Ruby on Rails 2: Output escaping

without comments

While input validation prevents the malicious manipulation of an application by users, proper output data escaping prevents failures in other applications which receive the generated data, but lack input validation.

Improper encoding or escaping of output is therefor the number two of the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors. A popular example for this kind of vulnerability are browsers which are manipulated by malicious JavaScript code injected into user-generated content of web applications. This kind of attack is called cross-site scripting (XSS).

In client-server environments applications communicate over APIs using more or less well defined protocols. Server and client applications can be developed by different parties unaware of the other side’s source code. A server which expects input data in a certain format can run into serious problems when a client application sends data in a wrong encoding or does not escape SQL, OS, or other commands. This is even more dangerous if the client application constructs the output from user input, e.g. a chat client which does not escape control commands.

Of course, it should be common knowledge that input data needs to be validated, but as long as it cannot be verified, e.g. by reviewing the source code, proper output encoding and escaping should be provided.

The most common output formats of a Rails web application are HTML and JSON. For escaping those formats Ruby on Rails provides the following mechanisms.

  • The ERB method html_escape() or its alias h() for HTML output
  • The SanitizeHelper methods to escape HTML output
  • The SafeERB plugin for enforcing the escaping of strings in rhtml templates
  • The ERB method json_escape() or its alias j() for JSON output

If other output formats are needed it is highly recommended to use provided escape methods or to write a custom output escaper.

Popularity: 1% [?]

Written by tkadauke

September 21st, 2009 at 6:31 pm

Leave a Reply