LoginSignup
18
17

More than 5 years have passed since last update.

strong_parametersについて

Last updated at Posted at 2013-07-09

Rails4.0で導入されたstrong_parameters、gemで入れるだけでRials3系でも動くというのを教えてもらったので試してみた

strong_parameters ?

mass_assignment脆弱性を解決する仕組み

mass_assignment脆弱性 ?

  • mass_assignment
    • ActiveRecordの値をハッシュで一度に設定できる機能
# こんなの
def signup
  params[:user] # => {:name => “hogehoge”, :email => "fugefuge@example.com"}
  @user = User.new(params[:user])
end
  • Userオブジェクトがadmin属性を持っててparams[:user]に :admin => true もあると、@user.admin #=> true になっちゃって困る、これがmass_assignment脆弱性
    • Rails アプリにありがちな脆弱性の一つ
    • PHPでは古くから(に?)あった脆弱性らしいです
  • こんなこともあったみたい

Rails3での対応

  • 一般的にはモデルで対応
    • 代入の許可/制限を ActiveRecord#attr_accessible/ActiveRecord#attr_protected でコントロールする
class User < ActiveRecord::Base
  attr_protected :admin
end

user = User.new(:admin => true)
user.admin # nil due to attribute protection

PHPでの取り組み

  • CakePHPのはなし
    • SecurityComponent でフォームの改ざんを検出する

strong_parameters(Rails4)

  • Rails4ではstrong_parametersによりコントローラでパラメータの検証を行う
# こうなる
def signup
  params[:user] # => {:name => “hogehoge”, :email => "fugefuge@example.com"}
  @user = User.new(params.require(:user).permit(:name, :email)
end
  • 許可されていないパラメータが渡された場合、ActiveModel::ForbiddenAttributesエラーが発生

Rails3.2.13で使う

  • 公式の README にも書いてある

1. Gemfileに追記、bundle install

gem 'strong_parameters'

2. 使用したいクラスで以下のようにモジュールをinclude

class Post < ActiveRecord::Base
  include ActiveModel::ForbiddenAttributesProtection
end
  • あるいは
ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

3. config/application.rbに下記の設定が true になっている場合は false に変更

config/application.rb
config.active_record.whitelist_attributes = false

  • セキュリティの考えとして入力段階で不正なデータを取り除いた方がより安全ということらしいので、コントローラで防ぐ方がモデルでやるよりもセキュアになりやすいらしい
    • もちろんモデルでやるやり方でも適切にやれば何の問題もない
    • より前段で防いだ方が問題が起きにくいというだけ
18
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
18
17