Reno, NV    +1 (800)0 621-0871

Go back

Internship

Input Sanitization in Rails

  |  July 23, 2015

Ruby on Rails already has a lot of security measures built into it to prevent different vulnerabilities. One safety measure that Rails does is that it escapes strings displayed in the views. It escapes HTML tags like <p>, <b>, <i>, and <a> to prevent the browser from parsing it as tags. It also escapes the <script> tag to prevent the user from injecting javascript. However, if you have a rich text editor and want to pass the data generated by the text editor into the views without destroying the tags generated by the editor, you may want to do

<%= raw @text%> or <%= @text.html_safe %> to prevent Rails from escaping HTML tags. However, any field that uses raw is a potential XSS target. If the user decided to enter this code as an input <script>window.location.href = “http://evilsite.com”; <script>, every user visiting the page will be redirected to evilsite.com which opens the possibility of a phishing attack. Using the html_safe actually tells rails that the string is HTML safe and doesn’t need escaping so any javascript code will not also be escaped. Developer can use the method sanitize that lets them whitelist allowed tags while also filtering out dangerous protocols like javascript. It retains tags like <p>, <b>,  or any tag that is whitelisted at the same time escaping potentially dangerous tags like <script>.

While searching through the web I also saw the gem brakeman. It analyses your Ruby on Rails application for possible security vulnerabilities. It also assigns confidence level to each warning to indicate how certain the tool that it is actually a problem. It doesn’t generate a comprehensive security report about your rails app but it’s a good tool to check common vulnerabilities. The Open Web Application Security Project (also known as OWASP) also has a quick cheat sheet for securing your Rails application.

Links: https://www.owasp.org/index.php/Ruby_on_Rails_Cheatsheet
https://github.com/presidentbeef/brakeman