blog.mhartl | Michael Hartl's tech blog

2008-09-21

Mass assignment in Rails applications

Filed under: mass assignment, Ruby on Rails — mhartl @ 18:13

This is a brief review of mass assignment in Rails. See the follow-up post on Finding and fixing mass assignment problems in Rails applications for some more tips on how to find and fix mass assignment problems.

We’ll begin with a simple example. Suppose an application has a User model that looks like this:

# == Schema Information
# Table name: users
#
#  id                         :integer(11)     not null, primary key
#  email                      :string(255)     
#  name                       :string(255)     
#  password                   :string(255)
#  admin                      :boolean(1)      not null
class User < ActiveRecord::Base
  validates_presence_of :email, :password
  validates_uniqueness_of :email
  .
  .
  .
end

Note the presence of an admin boolean to identify administrative users. With this model, the Users controller might have this standard update code:

  def update
    @user = User.find(params[:id])

    respond_to do |format|
      if @user.update_attributes(params[:user])
        flash[:notice] = 'User was successfully updated.'
        format.html { redirect_to(@user) }
      else
        format.html { render :action => "edit" }
      end
    end
  end

This works fine, but note that the line

  if @user.update_attributes(params[:user])

performs an update to the @user object through the params hash, assigning all the @user attributes at once—that is, as a mass assignment.

The problem with mass assignment is that some malicious [cr|h]acker might write a script to PUT something like name=New+Name&admin=1, thereby adding himself as an administrative user! This would be a Bad Thing™. The standard solution to this problem is to use attr_accessible in the model to declare explicitly the attributes that can be modified by mass assignment. To protect our User model, for example, we would write

class User < ActiveRecord::Base

  attr_accessible :email, :name, :password

  validates_presence_of :email, :password
  validates_uniqueness_of :email
  .
  .
  .
end

Since :admin isn’t included in the attr_accessible argument list, the User model’s admin attribute is safe from unwanted modification.

This seems simple enough, but the rub is that remembering to protect against mass assignment is difficult. Using mass assignment doesn’t affect the normal operations of the site, so it’s hard to notice the problem. Moreover, although you could shut off mass assignment globally, often there are many models that are used internally and never get modified directly by a web interface. Not being able to use mass assignment for these models is inconvenient, and manually making all attributes attr_accessible is cumbersome and error-prone. So, what’s a Rails developer to do?

Spurred by an email from Eric Chapweske of Slantwise Design, I recently audited the Insoshi social network for mass assignment vulnerabilities. Doing this manually was annoying, so in the process I developed a simple plugin to find likely vulnerabilities automatically, by searching through the controllers for likely mass assignment and then looking in the models to see if they didn’t define attr_accessible. The result is a list of potential trouble spots.

To use the find_mass_assignment plugin, simply install it from GitHub as follows:

$ script/plugin install git://github.com/mhartl/find_mass_assignment.git

(You’ll need Git and Rails 2.1 or later for this to work.) The plugin defines a Rake task to find mass assignment vulnerabilities; running it on the example Users controller from above would yield the following:

$ rake find_mass_assignment

/path/to/app/controllers/users_controller.rb
  5  if @user.update_attributes(params[:user])

This tells us that line 5 in the Users controller has a likely mass assignment vulnerability.

The find_mass_assignment plugin doesn’t fix mass assignment problems automatically, but by making it more convenient to find them I hope it can significantly improve the odds that they will be caught (and fixed!) quickly.

About these ads

36 Comments

  1. […] alerting me to mass assignment vulnerabilities in the Insoshi social network sourcecode. (See my post on mass assignment for a quick review of the concept.) I quickly set to work fixing the problems, and within a few […]

    Pingback by Finding and fixing mass assignment problems in Rails applications « Insoshi Ruby on Rails blog — 2008-09-21 @ 18:22

  2. Nice article, thanks. Saved some time of mine.

    Comment by kyb3R — 2010-04-23 @ 01:02

  3. […] conseguenza degli assegnamenti di massa senza l’uso di attr_accessible, problema già noto da tempo tra gli sviluppatori Rails ma mai preso seriamente in […]

    Pingback by GitHub hackerato… per colpa di Rails! | Edit - Il blog di HTML.it — 2012-03-5 @ 01:42

  4. […] problem, famous as a mass assignment vulnerability, has been around given a ability to set a series of attributes in one call was introduced in Rails. […]

    Pingback by IT Secure Site » Blog Archive » GitHub security incident highlights Ruby on Rails problem — 2012-03-5 @ 05:21

  5. […] well-known Rails hack that has probably existed since the site’s inception. Ruby experts like Michael Hartl and Eric Chapweske have been writing (and warning) about the mass-assignment vulnerability since […]

    Pingback by GitHub hacked, millions of projects at risk of being modified or deleted | CD DISK — 2012-03-5 @ 06:50

  6. Just curious in your example could a hacker change the post form to supply the “id” of an administrative user, and change that users password to something the hacker knows. Then they can simply login as the administrative user without having to make themselves an administrator? Perhaps it is just because you are being brief in your examples but I see no protection against one user trying to modify another users record?

    Comment by Chris Beelby — 2012-03-5 @ 07:43

  7. Reblogged this on txwikinger's blog.

    Comment by txwikinger — 2012-03-5 @ 07:50

  8. […] którą do ataku wykorzystał Egor Homakov to znany od lat problem nazywany mass assignment). Ten występujący w Railsach błąd programistyczny, przypomina trochę PHP-owe problemy z […]

    Pingback by » Wpadka GitHuba: można było przejąć dowolny projekt, a przejęto Railsy -- Niebezpiecznik.pl -- — 2012-03-5 @ 08:02

  9. […] (Хомяков уже подтвердил это). Проблема, известная как уязвимость массового присвоения появилась в Rails с тех пор, как была добавлена […]

    Pingback by Новости компьютерного мира - В GitHub устранена уязвимость, допускающая внедрение кода в любой репозиторий — 2012-03-5 @ 08:22

  10. […] извecтнaя кaк уязвимocть мaccoвoгo приcвoeния пoявилacь в Rails c тeх пoр, кaк былa дoбaвлeнa вoзмoжнocть […]

    Pingback by В GitHub устранена уязвимость, допускающая внедрение кода в любой репозиторий | ManNix.ru — 2012-03-5 @ 08:58

  11. […] and scores of others. GitHub itself uses a vulnerable Ruby on Rails application framework, the root cause of the problem, leaving the code repository open to attack. Homakov reported this so-called mass […]

    Pingback by maccad » GitHub reinstates Russian who hacked site to expose flaw — 2012-03-5 @ 15:40

  12. […] and scores of others. GitHub itself uses a vulnerable Ruby on Rails application framework, the root cause of the problem, leaving the code repository open to attack. Homakov reported this so-called mass […]

    Pingback by ste williams » GitHub reinstates Russian who hacked site to expose flaw — 2012-03-5 @ 16:13

  13. […] Vulnerability” ist schon länger bekannt. Es entstand, als Rails die Möglichkeit einführte, mit einem Aufruf gleichzeitig mehrere Attribute zu setzen. Die Rails Security Guide erklärt das Problem. Zudem wird […]

    Pingback by GitHub-Sicherheitslücke kompromittiert alle Projekte | virtualfiles.net — 2012-03-5 @ 17:31

  14. […] with a Rails example. Github already linked to this fantastic post on the subject regarding Rails here. What I'm here to tell you is that this situation exists in ASP.NET MVC also. If you aren't […]

    Pingback by digitalBush » Mass Assignment Vulnerability in ASP.NET MVC — 2012-03-5 @ 19:54

  15. […] and well-known Rails hack that has probably existedsince the site’s inception. Ruby experts like Michael Hartl and Eric Chapweske have been writing (and warning) about the mass-assignment vulnerability since […]

    Pingback by GitHub hacked, millions of projects at risk of being modified or deleted « Surya R Praveen — 2012-03-5 @ 22:01

  16. […] Vulnerability” ist schon länger bekannt. Es entstand, als Rails die Möglichkeit einführte, mit einem Aufruf gleichzeitig mehrere Attribute zu setzen. Die Rails Security Guide erklärt das Problem. Zudem wird […]

    Pingback by GitHub-Sicherheitslücke kompromittiert alle Projekte | Edv Sicherheitskonzepte — 2012-03-5 @ 23:13

  17. […] well-known Rails hack that has probably existed since the site’s inception. Ruby experts like Michael Hartl and Eric Chapweske have been writing (and warning) about the mass-assignment vulnerability since […]

    Pingback by GitHub hacked, millions of projects at risk of being modified or deleted | Passcomms Laptop — 2012-03-5 @ 23:49

  18. […] well-known Rails hack that has probably existed since the site’s inception. Ruby experts like Michael Hartl and Eric Chapweske have been writing (and warning) about the mass-assignment vulnerability since […]

    Pingback by iHARDWARE Magazine Feed Reader » Blog Archive » GitHub hacked, millions of projects at risk of being modified or deleted — 2012-03-6 @ 16:41

  19. […] A couple of days ago the Ruby on Rails world got shocked by an old bug (or feature?) that could cause massive security issues sometimes. You can read about it here. […]

    Pingback by IronShay | Mass Assignment Vulnerability in ASP.NET MVC — 2012-03-7 @ 02:38

  20. […] A couple of days ago the Ruby on Rails world got shocked by an old bug (or feature?) that could cause massive security issues sometimes. You can read about it here. […]

    Pingback by Mass Assignment Vulnerability in ASP.NET MVC - IronShay — 2012-03-7 @ 03:29

  21. […] 2012 due to a whitehat exploit (See Github pub key verification) for details. For those into Ruby, Mass assignment in Rails is a good read as well. This exploit allows the attacker to add his public key to any existing repo […]

    Pingback by How to verify your SSH keys at github (after their mar 4 breach)Random thoughts of a warped mind... — 2012-03-7 @ 14:54

  22. Forgive me for what may be an uninformed rant; I’m a functional programmer (Racket), and just read this page following a redirect from GitHub, and if I understand correctly, this bug has nothing to do with mass assignment per se; the underlying assumption appears to be that if single assignments were done, then the programmer would check the user’s permissions. The obvious solution, then, is for mass assignment to be a “fold” over single assignment–that is, a sequence of single assignments–so that each assignment is checked.

    To put it another way; the problem is not that mass assignment behaves differently; it’s just that mass assignment makes it convenient to do a stupid thing.

    Right?

    Comment by John Clements — 2012-03-7 @ 15:50

  23. […] bagaimana dia memanipulasi aplikasi GitHub yang berbasis Rails.Masalah yang dikenal dengan nama mass assignment vulnerability, telah ada selama beberapa waktu sejak kemampuan untuk mengeset sejumlah atribut sekali waktu […]

    Pingback by Insiden Keamanan GitHub Membuka Masalah di Ruby on Rails | LinuxBox.Web.ID — 2012-03-7 @ 22:01

  24. […] problema, conhecido como vulnerabilidade de atribuições em massa (mass assignment vulnerability), existe desde que a habilidade de definir um número de atributos em apenas um chamado foi […]

    Pingback by Vulnerabilidade no Ruby on Rails | DPKG — 2012-03-8 @ 11:22

  25. […] and well-known Rails hack that has probably existedsince the site’s inception. Ruby experts like Michael Hartl and Eric Chapweske have been writing (and warning) about the mass-assignment vulnerability since […]

    Pingback by GitHub Hacked – Millions Of Projects At Risk : Virtual Threat — 2012-03-8 @ 21:44

  26. […] […]

    Pingback by Mass Assignment Vulnerability — 2012-03-8 @ 22:51

  27. […] Web Security GitHub: How can  github be more secure?https://github.com/blog/1068-pub…  http://blog.mhartl.com/2008/09/2… http://homakov.blogspot.in/2012/…Repost (1)Cannot add comment if you are logged out. […]

    Pingback by GitHub: How can  github be more secure? - Quora — 2012-03-9 @ 03:53

  28. […] More information about the way mass-assignment works in Rails can be found at Michael Hartl’s tech blog. […]

    Pingback by ChiliProject 3.1.0 released | ChiliProject Blog — 2012-04-4 @ 05:49

  29. […] More information about the way mass-assignment works in Rails can be found at Michael Hartl’s tech blog. […]

    Pingback by Upgrade to ChiliProject 3.1.0 - news.siduction.org — 2012-04-5 @ 01:23

  30. […] 문제에 대해서는 여러 문서에서 설명하고 있는데, 참고한 문서는 여기입니다. 네, 아쉽게도 한글 문서는 찾을 수 없었고, 영어에 약하지만 어쩔 […]

    Pingback by [Ruby on Rails] Mass assignment 문제 | 재석 — 2012-04-27 @ 09:22

  31. […] in the MVC architecture of different frameworks including Rails. This vulnerability is often named mass assignment , but it is also known as over posting or autobinding. Dinis Cruz  wrote an interesting post about […]

    Pingback by Exploiting Microsoft MVC vulnerabilities using OWASP O2 Platform « OWASP O2 Platform Blog — 2012-05-19 @ 21:03

  32. […] alerting me to mass assignment vulnerabilities in the Insoshi social network sourcecode. (See my post on mass assignment for a quick review of the concept, and don’t miss Eric’s mass assignment article for a […]

    Pingback by Finding and fixing mass assignment problems in Rails applications | blog.mhartl | Michael Hartl's tech blog — 2013-03-19 @ 19:19


RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

The Shocking Blue Green Theme. Blog at WordPress.com.

Follow

Get every new post delivered to your Inbox.

Join 78 other followers

%d bloggers like this: