How Secured is your Rails App?

Cats: General| No Comments »

What do you prefer in terms of Authentication?

Plugin - Restful Authentication (recommended) - easy to use and you can tweak it according to your requirements.

Build your own authentication. You should rarely need to do this … Restful Authentication is quite flexible.

OpenID - a universal authentication system to avoid use of multiple username and password on the Internet. OpenID is getting quite famous now-a-days.

Access Control : To easily proivde different priviliges to your users. There are a lot of cool plugins available for access control.

Centralized Authentication Server - is used to implement single login/password for your users across multiple application. It can also be used for a single sign-on system. For example, Gmail and Google Reader have a single sign-on between them.

Use Google Authentication API to let your users login using their google username and password.

More Plugins :

Description :

Alternate Solution - use hash for specifying conditions in #find

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 :

Use :allow_blank to pass validations if value is nil or empty string

Testing Validations - do read the comments in this article

Useful Tips

  • 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
  • validates_presence_of is not required if you are using validates_format_of, unless regular expression accepts empty string.

Creating records directly from parametersWhile 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.

hide_action : If non-action controller methods must be public, hide them using hide_action.

Be careful of bypassing private and protected using meta-programming

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
8

## 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)

Do not ignore hidden fields - a user can easily modify their value, so suspect them similar to params[:id]

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.

Video Tutorial

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 rails

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:

  1. Store IP Address, but creates problem if user moves from one network to another.
  2. Create a new session everytime someone logs in.
  3. 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.

Code for session expiry on timeout

1
2
3
4
5
6
7
8
9
10
11
12

## 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

Plugin - Session Expiration for session expiry on timeout

Do not put expiry time in the cookie unless your cookie information is properly encrypted. If not, use server side session expiry.

Persistent session / login in rails - global setting in enviornment.rb

1
2

ActionController::Base.session_options[:session_expires] = <i>say after two years</i>

Persistent session / login in rails - to give your users a feature - remember me

Avoid access to your website from IP addresses which are present in DNS Blacklist(DNSBL).

Plugin - DNSBL check

Page caching does bypass any security filters in your application. So avoid caching authenticated pages and use action or fragment caching instead.

How secured is your 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 plugin

Use Captcha or Javascript based form protection techniques to ensure only human can submit forms successfully.

When using Captcha do ensure the following :

  1. Images are rendered on webpage using send_data and are not stored at the server, because its not required to store images and are redundant.
  2. Avoid using algorithm used by standard Catpcha plugins as they can easily be hacked, instead tweak an existing algorithm or write your own.
  3. Use a Captcha which does not store secret code or images in filesystem, as you will have trouble using Captcha with multiple servers.

Tutorial - a nice article on concepts of captcha

Plugin - ReCaptcha (recommended)

Plugin - BrainBuster - a logic captcha based on simple puzzles, math and word problems. By default, it has limited set of problems and you would have to come up with large set of your own problems.

Plugin - Simple Captcha (not recommended) as it breaks all the must have features of a good Captcha implementation.

For less critical systems like blogs, a more user-friendly option can be use of CSS based technique or JavaScript based plugin unlike Captcha. Both JavaScript and CSS based techniques can only avoid spam from dumb or general bots. If an hacker specifically targets your site or bot is smart enough, you are dead, so be careful.

Captcha with Multiple Servers

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 - CipherMail

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

Plugin ssl_requirement

Mongrel, rails, apache and SSL

Controller in SSL subdomain

Sample SSL code in rails

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 :

Ubuntu 9.10 running in low-graphics mode

Cats: General| 4 Comments »

After the installation from update manager, and every time I boot up my machine, I get a error with three options out of which I am forced to click OK for “Run Ubuntu in low-graphics mode for just one session” option.

Resolution upon reference from url (http://ubuntuforums.org/archive/index.php/t-1242813.html) for Ubuntu 9.10:

Take a backup and edit xorg.conf file:

sudo cp /etc/X11/xorg.conf /etc/X11/xorg.conf_bkp
sudo gedit /etc/X11/xorg.conf

Delete this Section Device:

Section “Device”
Identifier     “Device0″
Driver         “nvidia”
VendorName     “NVIDIA Corporation”
BoardName      “GeForce 8400M GS”
EndSection

And Edit the Section Screen as:

Section “Screen”
Identifier     “Screen0″
Device         “Device0″
Monitor        “Monitor0″
DefaultDepth    24
SubSection     “Display”
Depth       24
Modes “1440×990″
EndSubSection
EndSection

Here we go, no more low graphics mode issues.

Windows 7 and ROXIO

Cats: General| 1 Comment »

I recently got my XPS M1330 notebook upgraded from Windows Vista to Windows 7.It happened that one day I need to burn a CD and found that ROXIO DVD Creator is no more working though I have used it less. I have found the collection of CDs given by Dell and re-installed ROXIO Creator 9.  Thats it ! I made my own Axe on neck. Everytime I boot up my notebook. a pop up near the windows toolbar stating “This driver has got compaitibity issues with windows blah… blah…” and then the following errors appear:Microsoft Visual C++ Runtime LibraryRuntime Error!Program:…ommon Files\RoxioShare\9.0\SharedCom\(application).exeThe application has requested the Runtime to terminate it in an unusual way.Please contact the applications support team for more information - OR - Microsoft Visual C++ Runtime LibraryRuntime Error!Program: C:\Program Files\Roxio\(application folder)\(application name).exeR6025- pure virtual functional call I should say its more than a nightmare. This error keep popping up by freezing my notebook every 10-15 minutes approx. I tried all my ways of uninstalling it by following this support url of ROXIO.http://kb.roxio.com/search.aspx?URL=/content/kb/Creator/000127CR&PARAMS=But No Go !The error continued  for several Days..  Irritated and frustrated, today i just sat for hours to fix it. Finally I did it. Took almost 6 hours to google it and fix it though.I am blogging it to help another “Sufferer” of Roxio.Step 1:  I have got ROXIO installed as many Programs infact using the Roxio Creator 9 CD given by Dell.

  • “Roxio Audio”
  • “Roxio MyDVD”
  • “Roxio Drag and Disc” etc.. with update manager included.

Step 2: Instead of uninstalling the programs through Control Panel remove programs. Uninstall themFrom Program Files -> roxio XXX -> UninstallFollow this support url ->   http://kb.roxio.com/search.aspx?URL=/content/kb/Creator/000127CR&PARAMS= Step 3: I did everything but I couldnt delete Program Files -> Commom Files -> Roxio Shared/Sonic Shared.It says that it is used by some other application. Those are nothing but# RoxWatchTray9.exe# RoxMediaDB9.exe# VideoWave9.exe# MyDVD9.exe# MediaManager9.exe# DiscCopier9.exe# RXLabelCreator.exeStep 4:  I opened Task Manager in Windows 7 , it didn’t showed me any of these processes running. Here lies the main story. Due to which I couldnt delete the Roxio Shared under common files folder which is the root cause of Runtime error Popping up now and then.I even ran to buy Perfect uninstaller Software by reading this :http://www.squidoo.com/uninstallroxioI used that software and got ROXIO uninstalled though.Later I found “Show all process from all users” tab under Task Manager wherein you can end that process of roxioxxx.exe running and easily delete that Roxio shared folder under common files.Great ! those Perfect uninstaller people are earning on Roxio. Kudos to them! Kicks to roxio! and Sorries for other Users (like me)! But dont worry, just try the above steps.

Rails 2.3.3 Released

Cats: Ruby on Rails| No Comments »

new release of Rails is available - Rails 2.3.3.Among the usual bug fixes, a few new features were added, from the release notes:

  • touch is a convenient method to update a record’s timestamp and nothing else. This is extracted from apps whose models “touch‚” others when they change, such as a comment updating the parent.replies_changed_at timestamp after save and destroy.[..]
  • :primary_key option for belongs_to for broader support of legacy schemas and those using a separate UUID primary key: belongs_to :employee, :primary_key => ‘SSN’, :foreign_key => ‘EMPID’ [..]
  • leaner user-facing encoding [JSON] API.
  • decoding backends for the json and yajl libraries. Both are significantly faster than the default YAML backend.

Meanwhile, the work on Rails 3 continues. Yehuda Katz has posted a few blog entries on the new architecture for Rails 3, as well as lessons learned from refactoring a large code base as Rails.One of the goals of Rails 3 is to bring Merb’s modularity and well defined internal APIs to the Rails codebase; Yehuda’s article on the interface between ActionController and ActionView gives some insight in what’s going on on that front. What becomes clear is that the fusion of Merb and Rails is a major project and is still underway.The work on Rails 3 also has an impact on the development of Merb. A recent discussion on the Merb mailing list addressed the state of Merb 1.1, which was due a few months ago. The current plan is to make sure a smooth migration path to Rails 3 is possible - which, of course, requires to know what Rails 3 architecture will be.With all that said, Merb is still a viable solution for many projects, as Ezra Zygmuntowicz (Merb’s creator) points out:

I’d like to chime in and say that I am still happily building apps with merb, http://engineyard.com/solo is built on merb. I don’t find that there is anything I’m missing or that there are any features or major bugs stopping me from building apps with merb.

For another glimpse at plans for Rails 3, David Heinemeier Hansson’s RailsConf’09 talk is available online.

 

Driver Error: Svn Merge

Cats: Ruby on Rails, Technology| No Comments »

The ’svn merge’ command compares two trees, generates a patch, then
applies that patch to a working copy. Yes, you have complete freedom
to compare any two trees, and thereby generate any patch you want. But
that does *not* mean that ’svn merge’ always will do what you want.
It’s *your* responsbility to make sure that the patch being produced
makes sense, and cleanly applies to your working copy.      
Skipped ’src’
Skipped ’src’
Skipped ’src\au’
Skipped ’src\au\com’
Skipped ’src\au\com\forward’
Skipped ’src\au\com\forward\codeSections’
A src\au\com\forward\codeSections\DesignNotes.txt
A src\au\com\forward\codeSections\CodeSections.java
Skipped ’src\au\com\forward\codeSections\testFiles’
A src\au\com\forward\codeSections\testFiles\testin.cs
Skipped ‘docs’
Skipped ‘docs’
A docs\htmldoc.exe 

See those skipped messages? That indicates driver error. The merge
command is trying to add and remove certain directories because they’re
not related to each other at all. Please read this section of chapter
4, regarding ancestry:

http://svnbook.red-bean.com/en/1.1/ch04s03.html#svn-ch-4-sect-3.2.4

Then after reverting, try the merge again with the –ignore-ancestry
command.

So, It is like this what I have implemented,

> Taken a latest production copy as my_working_copy

> Merged the dev branch with production branch under  my_working_copy

svn merge –ignore-ancestry prod_branch_url dev_branch_url my_working_copy/

> And this is how we avoid the driver error.

> Check for conflicts under my_working_copy

Fix the conflicts always in favour of Clients Requirements.

Else if no conflicts, check in the merge to production

Finally, Say The END to the project !!!

Next is What ?  [ Samsung Adv :) ]

Avoid SVN updates for External Rails Plugins in your Application

Cats: General| No Comments »

Make sure you are in the root of your app and do:
svn propedit svn:externals vendor/plugins
Just delete the line(s) of the plugins you no longer want.

If you get the following error then you need to set your environment variable.
svn: None of the environment variables SVN_EDITOR, VISUAL or EDITOR is set, and no ‘editor-cmd’ run-time configuration option was found

For example, you can set the SVN_EDITOR to use Vi editor from your unix prompt like

export SVN_EDITOR=’”/bin/vi”‘

In Windows, instead of export, it is

set SVN_EDITOR=c:/windows/notepad.exe (for notepad)

or

set SVN_EDITOR=”C:\Program Files\Posix Tools\bin\vi” (for Vi editor)

I need an individual file to be migrated in Rails

Cats: Ruby on Rails| No Comments »

Rails migrations are great, they allow continual evolution of database schema. Sometimes, especially when prototyping, I hate to run migrations down and up and load data, just to make small independent change in database table. In this situations I run only specific migration:

ruby script/runner 'require "db/migrate/005_create_blogs"; \n
CreateBlogs.migrate(:down)'
ruby script/runner 'require "db/migrate/005_create_blogs";\n
 CreateBlogs.migrate(:up)'

This is much typing (for just one migration at least ;) so here is the rake task to do the same:

namespace :db do
  task :migrate_one => :environment do
    file = Dir["db/migrate/#{ENV["VERSION"]}_*.rb"].first
    require(file)
    migration_class = file.scan(
/([0-9]+)_([_a-z0-9]*).rb/)[0][1].camelize.constantize
    migration_class.migrate(:down) unless ENV["DIRECTION"] == 'up'
    migration_class.migrate(:up) unless ENV["DIRECTION"] == 'down'
  end
end

Put this rake task in lib/tasks and you can call it with rake db:migrate_one VERSION=005. This would run migration down and up. You can also add DIRECTION=up or DIRECTION=down to control direction.

Thanks to Bojan Mihelac.

Enni Gundelu aaa?

Cats: General| No Comments »

“Enni Gundelu aaa?” Its a normal saying in telugu asking How dare you? But the exact words translation is “How many hearts you have haan?” Hmm… Well… I have two hearts !!!

Weird, Rare… and what not !

Cats: General| 2 Comments »

Apart from Redhat Linux, I’m also trying to set up my Rails app on a Win XP Pro machine to clarify some Ajax effects in IE. IE used system hosts file very well. But at the same time, on the same OS,  my latest Mozilla Firefox version 3.0.1 ignores the same hosts file. And this only happens when Proxy Server is used.

I didn’t understand why the configuration works only with IE, but not with
Mozilla. Makes no sense to me at all.

I am sure that I have set no proxy for localhost, and I have even tried setting no proxy for the local IP range like 192.168.3.0/24 where my working IP lies in between. Glory ! it worked…!!!

Ofcourse, I googled with suggestions of clearing cache and subscription to 5$ monthly plan to know the solution. So this info.. is for those who uses proxy and gets weird cases like this… Enjoy the solution,  absolutely free…! :)

Ubuntu + ROR + Mysql + Svn +VPN

Cats: Ruby on Rails, Ubuntu| No Comments »

Every time we install Ruby/Rails/Mysql/Rmagick/Vpn on Ubuntu Gutsy or Hardy we face the same  errors again and again. Lets reduce the installation time and have a loop-back-fix-free or smooth installation experience.

After you run the CD or install Ubuntu, make sure of your Network Proxies if any, if so, you need to add the proxy url at System->preferences->Network Proxy.

then from terminal, make sure this passes…

sudo apt-get update

then for Mysql/Rails installation follow this:

http://articles.slicehost.com/2007/11/23/ubuntu-gutsy-mysql-and-ror

and for VPN installation/connection on Ubuntu, this is the best guide:

http://www.cs.umn.edu/help/offsite/vpn.php#ubuntu_config