Ruby on Rails does a decent job in handling security concerns in the background. You will have to configure your application to avoid few security attacks while plugins would be required for many security concerns which are not at all or poorly managed by rails.
In this article I have described the security issues related to a ruby on rails web application. I have followed DRY by linking to articles with good explanation and solutions to security concerns wherever required. This guide can also be used as a quick security check for your current web application.
Table of Contents
Authentication
Authentication is the foremost requirement of most of the web applications to authenticate and give privileges to their users. Apart from normal authentication mechanism rails have plugins for OpenID, CAS and Access Control. Build your own authentication system only if your requirements are very unique or you do not trust other implementations.
Plugin - Restful Authentication (recommended) - easy to use and you can tweak it according to your requirements.http://code.google.com/p/rolerequirement/
http://agilewebdevelopment.com/plugins/activeacl_rails_authorization_system
Acts_as_authenticated - http://technoweenie.stikipad.com/plugins/show/User+Authentication
Super Simple Authentication - http://ariejan.net/2007/08/24/super-simple-...
- Model -
SQL Injection
The problem arises when metacharacters are injected into your queries to database. Rails has a very good support to avoid SQL injection if you follow conventions in issuing queries to your database.
Description : Alternate Solution - use hash for specifying conditions in#find
Activerecord Validation
To validate the contents of model object before records are created/modified in the database. Activerecord validations are very useful over database data-type constraints to ensure values entered into the database follow your rules. You might have javascript validations for forms but javascript can easily be switched off. Use javascript validations only for better user experience.
Description : Conditional validation using:on and :if options. Checkout this cool video
Be careful using validates_uniqueness_of, it has problems when used with :scope option. Open bug tickets :
http://dev.rubyonrails.org/ticket/9235
http://dev.rubyonrails.org/ticket/8811
http://dev.rubyonrails.org/ticket/8774
- Its easy to manage 'nil' values using
:allow_nil, its quite handy. For ex: set:allow_nil => truein validates_uniqueness_of to check uniqueness of non-nil values and ignore nil values - validates_presence_of is not required if you are using validates_format_of, unless regular expression accepts empty string.
Creating records directly from parameters
While creating database records directly from form params, a malicious user can add extra fields into the params and manually submit the web page which will set values of fields which you do not want user to set.
Description : Alternate Solution - Trim the parameters to keep the required keys and remove the others.- Controller -
Exposing methods
Use private and protected in controller for methods which should not be actions. Actions are pubic methods and can be invoked from the browser.
hide_action : If non-action controller methods must be public, hide them using hide_action. Be careful of bypassing private and protected using meta-programmingAuthorize parameters
Always authorize user request. By tweaking form parameters or url a user can send request to view/modify other users information if there is no proper authorization of parameters.
For example :1 2 3 4 5 6 7 |
## To find information of an order which belongs to a particular user. #Incorrect : @order = Order.find(order_id) #Correct : @order = @user.orders.find(order_id) |
Filter sensitive logs
Prevent logs of sensitive unencrypted data using #filter_parameter_logging in controller. The default behavior is to log request parameters in production as well as development environment, and you would not like logging of password, credit card number, etc.
Cross Site Reference(or Request) Forgery (CSRF)
In a CSRF attack, the attacker makes victim click on a link of his choice which would contain a GET/POST request and causes web application to take malicious action. The link could be embedded in a iframe or an img tag. Its recommended to use secret token while communicating with user to avoid this attack.
Its little complex to understand this attack. So, only those readers who are very enthusiastic to know about it, please read the Description below. Rest can directly move ahead to use the plugin.
Description : Use Get and Post appropiately (note : Both get and post are vulnerable to CSRF) Example - Gmail CSRF security flaw Plugin - CSRF Killer (recommended) - it requires edge railshttp://activereload.net/2007/3/6/your-requests-are-safe-with-us
Security extension - http://svn.aviditybytes.com/rails/plugins/security_extensions/
Minimize session attacks
If an attacker has session-id of your user, he can create HTTP requests to access user account. An attacker can get session-id by direct access to user machine or is able to successfully run malicious scripts at user machine. In this section we will talk about how to avoid or minimize the risk if attacker has user session-id. Following steps are helpful:
- Store IP Address, but creates problem if user moves from one network to another.
- Create a new session everytime someone logs in.
- Expire session on user logout, user is idle for a time period or on closing of browser/tab. For maximum security expire sessions on all the three conditions.
1 2 3 4 5 6 7 8 9 10 11 |
## Timeout after inactivity of one hour. MAX_SESSION_PERIOD = 3600 before_filter :session_expiry def session_expiry reset_session if session[:expiry_time] and session[:expiry_time] < Time.now session[:expiry_time] = MAX_SESSION_PERIOD.seconds.from_now return true end |
ActionController::Base.session_options[:session_expires] = <i>say after two years</i> |
Stop spam on your website from DNS Blacklist
Avoid access to your website from IP addresses which are present in DNS Blacklist(DNSBL).
Plugin - DNSBL checkCaching authenticated pages
Page caching does bypass any security filters in your application. So avoid caching authenticated pages and use action or fragment caching instead.
- View -
Cross site scripting(XSS) attack
Cross Site Scripting is a technique found in web applications which allow code injection by malicious web users into the web pages viewed by other users. An attacker can steal login of your user by stealing his cookie. The most common method of attack is to place javascript code on a website that can receive the session cookie. To avoid the attack, escape HTML meta characters which will avoid execution of malicious Javascript code. Ruby on Rails has inbuilt methods like escape_html() (h()), url_encode(), sanatize(), etc to escape HTML meta characters.
Description Can we avoid tedious use of h() in views? Sanitize() is used to escape script tags and other malicious content other than html tags. Avoid using it ... its unsecure. Use white_list instead. White_list pluginAnti-spam form protection
Use Captcha or Javascript based form protection techniques to ensure only human can submit forms successfully.
When using Captcha do ensure the following :
- Images are rendered on webpage using
send_dataand are not stored at the server, because its not required to store images and are redundant. - Avoid using algorithm used by standard Catpcha plugins as they can easily be hacked, instead tweak an existing algorithm or write your own.
- Use a Captcha which does not store secret code or images in filesystem, as you will have trouble using Captcha with multiple servers.
Inverse Captcha for Mephisto - http://www.artweb-design.de/projects/mephisto-plugin-inverse...
JavaScript based Form Spam Protection - http://form-spam-protection.googlecode.com/svn/form...
Hide mailto links
Mailto links in a webpage can be attacked by e-mail harvesting bots. Use the plugin CipherMail to generate a 1024 bit random key and obfuscate the mailto link.
Plugin - CipherMailUse password strength evaluators
A lot of people have used password strength evaluators simply because its used by google in their registration form. You can use it to help your users register with strong password. But I don't think its a must have security addon. Uptill now I have not found a good algorithm to assess strength of a password, but some of them are reasonable.
Also, if there is an open source tool or algorithm for evaluating password strength, it can easily be broken. So, you might consider tweaking the algorithm or building one from scratch.
Tools- Miscellaneous -
Transmission of Sensitive information
Use SSL to encrypt sensitive data between transfer from client to server. SSL hits server performace, so you might consider using SSL only for few pages which transfer sensitive data to and fro.
Plugin ssl_requirement Mongrel, rails, apache and SSL Controller in SSL subdomain Sample SSL code in railsFile upload
Be very careful when you allow your users to upload files and make them available for other users to download.
Description Must read - Section 26.7 of Agile web development with rails - 2nd edition In place file upload 3 plugins for file upload reviewed at :Secure your setup / environment
Proper Mysql configuration
Use good passwords
Security plugins directory
http://www.railslodge.com/plugins
http://railsify.com/categories/security-production
Note : I will keep this security guide updated. Any additions/improvements are welcome.

great article which totally save my time while I am buliding campus on rails and heading for deployment soon….. thanks!
:-)
For the security minded I recently modified restful_authentication to use bcrypt instead of sha1 (among some other changes):
http://code.google.com/p/acts-as-authentable/
Your a star my good chap
Great, gonna translate it in .fr
Great write up, the more info on security the better.
Great article man, thanks a whole lot.
Just wanted to swing by and thank you for linking to me. Never thought I’d be linked on a site like this :)
SSL Requeriment redirects, which means a login action can in fact travel without encryption. I think Secure Actions (http://agilewebdevelopment.com/plugins/secure_actions) provides a better solution. I explained a couple of tricks for this plugin here (http://www.advogato.org/person/fxn/diary/470.html).
Talking about captchas to prevent automated form submissions: here’s an Inverse Captcha plugin for Mephisto comments. Relies only on CSS (no JS, no user action) and therefor will only work for not-so-critical things like blog comments etc., but does a really good job for these.
Thanks for writing up a short version of my blog articles
Thanks for mentioning my plugin, I appreciate it. I’ve delicious’d this page and I am sure I’ll come back often since I’ve seen great tips already. Thanks!
@sven fuchs
Thanks for the pointer … using CSS to avoid spam is an interesting technique. It should be good enough for less critical systems until dumb bots adapt to it.
I have updated the guide!
Aren’t attr_protected and attr_accessible designed to prevent form injection?
The tip linked in your “Creating records directly from parameters” section advises to remove the unwanted keys from the params hash in the controller. Using the protected/accessible methods in the model definition seems to solve the problem much closer to where it is actually happening.
http://rubyforge.org/projects/asgoogleaccount/ is flagged ‘alpha status’, so does anyone know how stable and secure it is? Anyone using in production?
This is a great checklist. Thanks!
Thanks, Quarks! Appreciate that :)
Hi,
I am using Simple Captcha, as explained a good choice here http://www.codeandcoffee.com/2007/06/20/implementing-a-captcha-with-ruby-on-rails-in-10-minutes-or-less/ and at many more places too, in many of my projects and I found it really useful and simplest to implement. Are there specific reasons/flaws that we should not use it ?
@jon
In one of my projects I used Simple Captcha because everyone said its awesome. I do agree its very simple to use, but I faced following problems using Simple Captcha :
1. It stores images which is not required, send_file or send_data should have been used instead. Also, unused captcha images are not deleted until a next user request for captcha is made. Moreover, it stores images in {RAILS_ROOT}/public/simple_captcha with directory permission 777.
2. It stores secret code in {RAILS_ROOT}/tmp/data. Why filesystem? I ran into trouble while moving my development to production having multiple servers. The only option I was left with was to modify code of Simple Captcha to store secret code in db or memcached, which was impossible as the plugin is not properly written.
3. The images it generates would be simple for any good attacker to break. If Captcha is required in less critical system, better to use user-friendly options like CSS or Javascript based form protection techniques. If your system is critical I would recommend using ReCaptcha.
4. At any time only image is valid per session. It breaks when user opens the form from multiple tabs. Its a small and rare thing but gives a bad user experience.
After a lot of trouble with Simple Captcha, I find it much better to spend a little more time in using ReCaptcha.
The rule is, when you want to secure your site, you use the most powerful option rather than using the most simplest to use.
@david sidlinger
“Removing the unwanted keys from the params hash in the controller” is marked as an alternate solution incase you are more comfortable with this approach. Its quite natural … this was the first solution I thought of.
Using attr_protected and attr_accessible is the best technique.
Surprisingly, ur comment was marked as spam by Akismet (comment spam protection tool).
@xavier noria :
The sole benefit of using secure action is “If a link is generated to a secure action (using url_for, link_to, etc) that link will be an https:// link.”, which would avoid redirection to an extent.
As far as login action is considered, I think its a good practice to make both login_page and login_submit as secure actions. If your login_page is https, then user submitted login information would travel in encrypted format.
Also, your users would be more confident if the login page is https. I hardly find any good purpose on why ‘secure actions’ plugin was made.
@raphael :
acts_as_google_account is not stable and secure. A good opportunity to write a plugin for rails enthusiasts.
Great guide guys keep up the good work.
An excellent article – I’m sure I’m going to get a lot of use out of this. Was a few things I’d not seen/thought of before, particularly the Authorize parameters issue. Thanks for putting this all together =)
Dave
This is a fantastic article. Thanks for putting it together.
Great article! This is an excellent primer to rails security.
Hi,
Your explanation is not justified, even the google’s captcha doesn’t work on two tabs of the browser sharing the session. Moreover your statement that “the plugin is not properly written” just for the reason that you were not able to modify it is not making much sense… the only problem that people are facing is I think the dependency on RMagick as some people finds it hard to install and get working, rest everything seems quite fine.
Anybody else here can suggest any good reason for moving from SimpleCaptcha to anything else ? probably as this site is suggesting ReCaptcha.
This is the best rails security post I’ve ever seen! With your permission, I’ll store in my computer for reference!
Thanks!
Felipe Giotto
@felipe:
sure not a problem, but I would recommend to visit this post once in a while as I keep updating this guide.
@Quark:
That’s fine, and in that case you generate a secure link to your login page with a regular link_to. The point is that you declare secure actions at the controller level, and the regular idioms for link generation get the protocol right.
I think that approach is better than having a redirection. Why would we prefer to have an insecure link and declare a redirection when we can have the right link directly and with the same effort?
Agreed, this is top of the list in security posts for rails!
I’d shout you a beer if you had a link.
SSL Requeriment redirects, which means a login action can in fact travel without encryption. I think Secure Actions (http://agilewebdevelopment.com/plugins/secure_actions) provides a better solution. I explained a couple of tricks for this plugin here (http://www.advogato.org/person/fxn/diary/470.html).
Thanks for very interesting article. I really enjoyed reading all of your posts. It?s interesting to read ideas, and observations from someone else?s point of view? makes you think more. So please keep up the great work.
All the best
This guide is pretty cool and will save a lot of my time.Thanks : )
Is there a way to counter CSRF by checking where the POST came from? Meaning: is there a way to check the host referrer of the POST/GET to make sure it came from the same domain, and if not, then don’t process the request? That seems like the best logical option, if available.
This is an excellent security guide – Thanks.
Those of you using attr_accessible and attr_protected to control mass assignment, one note. Things like “find_or_initialize_by_blah” will be subject to that as well, even though “blah” does not intuitively imply “mass” assignment.
The tricky part is that if attribute “blah” is not in your attr_protected list and at some point you do find_or_initialize_by_blah and no matching object is found (i.e. you hit the “initialize” case), you will happily be handed your new initialized model object, but the “blah” field will silently be set to nil instead of what you expect.
We ended up writing our own mass-setter model methods instead.
Cool article , thank you so much.
thanks for article. looks very interesting.
Thanks for the great article!
I am developing an ROR application where I would like session information to be removed when the browser window is closed (multiple users, same computer). Are there any secure suggestions for doing this?
Thank you!
hi @serchan,
I have explained about deleting session information at : http://quarkruby.com/2007/10/21/sessions-and-cookies-in-ruby-on-rails#sstale
Every browsers maintains its own cookies, which means different session for different browsers. So, even when firefox is closed user logged in from IE will not be affected.
This is what i was looking for a long time. a security guide on ruby. we all know the security problem with php and we have to take special care on security in ruby as well. Thank for the hard work
Will there be a possibility to collect the cookies from all the well known browsers and put them together in one folder to use them together. is the cookie sotrage the same in IE and in Firefox?
Thanks for the nice article as well from my side. helped me much in understanding! Thomas
I’ve written a Ruby binding to cracklib, which you may find useful for password strength checking:
http://rubyforge.org/projects/rubylibcrack/
I’ve written a Ruby binding to cracklib, which you may find useful for password strength checking:
http://rubyforge.org/projects/rubylibcrack/
Thanks for this guide, i found it very handy and useful. I am going to writing an article on your your on my blog. Great work!
Regards, Meteko
Thanks.. Nice article
Thanks for this good article..
Best Regards
Excellent stuff, Nakul!
Keep it coming! :-)
-Dan
nice. keep the great work up. thx
Hammm… Nice article… Interesting.
Great tutorial, they are very easy to understand. Thanks!
Brilliant tutorial! I think CSRF protection is now included in rails (version 2.2). Does anyone know something about this?
Hi Simao,
Yes it is a part of rails 2.0 and above.
Soon I will come up with security updates from rails 1.2 to 2.0.
Thanks for the useful article. Best regards…
you expect that the user will be redirected to the main action, preserving all the parameters. But if an attacker adds &host=www.attacker.com to the URL, it will redirect the victim to that host.
Incorrect :
@order = Order.find(order_id)
Correct :
@order = @user.orders.find(order_id)
i can’t download super simple authentication plugin and generator
The svn repository seems to be down for now.
I have the same problem. How I can download the plugin and generator? Please help. I must get this.
I can’t download the plugin. Can aynone help me? Thanks in advance. Regards…
I’ve written a Ruby binding to cracklib, which you may find useful for password strength
Excelent work! Extremely useful. Thank you!
Thanks for very interesting article.
Wondering if there are any opinions with regard to a choice between Ruby on Rails versus Cake PHP with regard to security.
Excellent security guide – I did not know about this security risks in ruby.
Security is very important in the work we do0, so thanks for that
Good article.
Thanks Quark for useful comment.
NJ - NY
There are alot of issues that affect the overall security of a web applications. This has been guide has been very helpful. Thanks Quark.
What about server-side code obfuscation (like zend) ? // im nob in ruby
Biggest problem with security is bad passwords, people using the same password, one gets comprmised then they all do.
Cool article , thank you so much.
This is a fantastic article. Thanks for putting it together.
This is an excellent security guide – Thanks.
I am proud of you guys. http://blog.bhushangahire.net/?p=33 .
This way we both will follow each other.
very clear and nice article. thaks for sharing with us Video Youtube | Kuaför Malzemeleri | kiralık ev kiralık daire
Excellent article, thanks. I made a couple of apps in Ruby on Rails and implemented a range of security features similar to the ones outlined above. Please check out our portfolio to find out more. Cheers!
Thank you for the article
Cool article , thank you so much.
Cool aticle. very nice. thanks
Thanks for this guide, i found it very handy and useful.
Thanks for the quality guide!
Thanks for very interesting article.
thanks your post this article is very interesting bayrakçı
Thanks for writing up a short version of my blog articles
Looks very interesting. Thanks for article.
thanks nice
thank you so much
I love this blog! Congratulations!
thank aloat quarkruby
Its easy to manage ‘nil’ values using :allow_nil, its quite handy. For ex: set :allow_nil => true in validates_uniqueness_of to check uniqueness of non-nil values and ignore nil values
Thanks anyway for all the work.
thanx your articles
This guide is pretty cool and will save a lot of my time.Thanks : ) Thanks for writing up a super article here! Greetings hamann
Brilliat information thank you
Yes i also like Ruby on Rails. it has a good potential. so security issue should be added.
Thanks for providing this info
thanks
Hi Guys, this article is a blast and saves us a lot of time for research. Thanks for the great work!
One word Thank you quarkruby
thank you so much. this is nice article.
thank you so much. this is nice article.
Cool aticle. very nice. thanks
thank you so much. this is nice article
dreambox
thank you so much. this is nice article
Very useful (guide) information thank you
This is the best rails security post I’ve ever seen!
Thanks!
Ruby security is an important issue, thanks for the great article
Security is very important in the work we do0, so thanks for that !
V good info
Thanxxx youur articless
Marvelous thank you
Thank you so much.
Thank you
I think that approach is better than having a redirection. Why would we prefer to have an insecure link and declare a redirection when we can have the right link directly and with the same effort?
Thank you for your invaluable help this information will myself very useful
Thank you for your
Thank you for this!
Thanks for the help.
This is an excellent security guide – Thanks.
I am using Simple Captcha and at many more places too, in many of my projects and I found it really useful and simplest to implement.
Ruby on Rails Security Guide thank aloan im the about
Thanks
Ruby security is an important issue, thanks for the great article
Great article man, thanks a whole lot
Thank you so much looks interesting. Happy sharing.
Thank you
Thank you for your help
Thanks, learned quite a bit.
Thank you all
Ruby security is an important issue, thanks for the great article
Thanks so much. It is very helpful and useful.