imedo Development Blog

there is no charge for awesomeness

Secure coding with Ruby on Rails 1: Input validation

without comments

Improper input validation is the number one error according to the 2009 CWE/SANS Top 25 Most Dangerous Programming Errors listing. It can be exploited by changing input values in such a way so as to cause the application to crash, confidential information to be revealed or the flow of the program to be changed in an unexpected way. This kind of exploit is called input validation attack. The following example demonstrates how lazy input handling can lead to unwanted effects. It shows a piece of code which calculates the price of a sale by multiplying a product’s fixed price with the quantity provided by the user. Afterwards it charges the user’s account with the total price.


class Sale < ActiveRecord::Base
 belongs_to :user

 def buy
   total_price = single_price * quantity
   user.account.charge(total_price)
 end

end

sale = Sale.new(:single_price => 10, :quantity => params[:quantity], :user => buying_user)
sale.buy

Consider the case a user provides a negative value for the quantity. The total price would be negative as well and therefore the user or attacker is able to increase the amount on his account for free.

In order to prevent misuse, input data which is provided by the user should never be trusted. Proper input validation is absolutely necessary. For the example above a check for integer values greater or equal to zero would prevent the exploit of the code. Ruby on Rails already brings a set of easy to use input validation methods which usage is demonstrated in the following.


class Sale < ActiveRecord::Base
 belongs_to :user
  validates_numericality_of :quantity,
    :o nly_integer => true
    :greater_than_or_equal_to => 0

 def buy
   total_price = single_price * quantity
   user.account.charge(total_price)
 end

end

sale = Sale.new(:single_price => 10, :quantity => params[:quantity], :user => buying_user)
sale.buy

More Rails validation methods can be found under Module
ActiveRecord::Validations::ClassMethods
.

Popularity: 1% [?]

Written by ehartung

September 1st, 2009 at 7:06 am

Leave a Reply