Smorgasbord - Politics, Lisp, Rails, Fencing, etc.

My musings on assortment of things ranging from politics, computer technology and programming to sports.

Wednesday, May 03, 2006


On this day:

Securing Rails application

Using Ruby on Rails has been fun. An important part of developing a web application is making sure that most of the security loopholes are plugged in. Here are few basic things which should be checked and fixed in any security audit:


  • User trying to execute javascript or inserting html statement, or Cross-Site Scripting (CSS/XSS).
    http://manuals.rubyonrails.com/read/chapter/44 provides a tutorial in this, but the basic idea is that use HTML-escaping function `h' or `sanitize' while displaying all data input by the user. Even the XML/RSS data which is displayed should be secured. Sanitize is generally safe but there may still be some hidden security flaws.

  • SQL Injection or user maliciously inserting sql statements in you queries.
    http://manuals.rubyonrails.com/read/chapter/43
    has again a tutorial chapter on this. The key point is not using sql directly, but in some cases where you need to then instead of embedding user input in sql by using
    " ..subject = #{param[:subject]} ..."

    use
    " ..subject = ? ...", param[:subject]

    Also, turn off the echo service on production web server.
    Rails makes it so easy to avoid common SQL injection attack, whereas I remember working in a corporate environment and using PHP, and in all most all sql statements in the code, it was possible to do SQL injection attack.

  • Creating records directly from form parameters.
    Another chapter http://manuals.rubyonrails.com/read/chapter/47 giving tutorial details. The key point is that to prevent some model fields being updated by the form parameters directly (or en masse), use `attr_protected' or the more secure `attr_accessible'.

  • Not exposing controller methods.
    Make controller methods which should not be accessible to the user as `private' or `protected'.

  • Checking file/attachment uploads.
    It is generally safer to store the files in the database. Check the size of the file being uploaded, and make sure that it doesn't exceeds the permissible limit. Also, check the file extension, and make sure that it is a valid extension and not `*.cgi', `*.php', `*.js' etc.

  • Be careful about ID parameters.
    For certain operations, for example say displaying email, a user should be only able to read his or her email. In this case, in the email displaying controller, a check should be made to verify that the user is authorized to read the email.

Remember a chain is as strong as the weakest link in it.