Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1
Application Issues | 133

Hidden form fields


Rails makes simple CRUD (create, read, update, delete) operations on a single model
object so easy that it is easy to ignore the security implications. Here’s an example of
hownot to process a form.


app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
end


app/views/comment/new.rhtml
<% form_for :comment do |f| %>
<%= f.hidden_field :user_id %>
Comment: <%= f.text_field :comment %>
<% end %>


app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def new
@comment = Comment.new :user_id => get_current_user( )
end


def create
# Danger Will Robinson!
@comment = Comment.create params[:comment]
end
end

This looks innocuous enough, but it has one problem: the hidden field is trusted! By
not verifying that the params[:comment][:user_id] value received in the create
method is sane, we have just allowed anyone to create a comment attached to an
arbitrary user.


Rails can only handle so much for you. Theparamsobject is CGI-unescaped and
parsed into nested hashes, but that’s as much as the framework can do for you. Any
time you use theparamsobject, realize that it can contain anything the user wants. If
you need any stronger guarantees about the content of theparamsobject, you need to
use cryptography.


The implications of this are tremendous: every once in a while, some online store
gets in trouble for storing prices as hidden form fields, and not validating them when
an order is placed. Someone with at least a minimal knowledge of HTT Pthen
teaches them the “don’t trust the client” lesson by ordering a few plasma TVs for a
dollar each.


Client-side validation


A corollary of these form-processing principles is that validation should always take
place on the server. This is not to discount the importance of client-side validation,
but the application must be designed to be secure, no matter what is sent at the
HTTP level.

Free download pdf