LoginSignup
1
0

More than 1 year has passed since last update.

Ruby on Rails のwhereメソッドの条件を文字列だけで構成するとはSQLインジェクションの危険がある。

Last updated at Posted at 2021-10-10

Railsのwhereメソッドの条件を文字列だけで構成することは危険なようです。

Webサービス作成する中で「あるカラムに値が設定されているレコードを取得する」為、下記のようにコーディングしていました。

値が設定されていないだったらRailsのwhereメソッドに「selling_day:nil」みたいな感じで取得してあげれば良いかと思いますが

stocks_controller.rb
@stock = Goal.where('selling_day like ?','%')

ただ、文字列だけで条件を指定するとSQLインジェクションのリスクがあるようです。
具体的には

stocks_controller.rb
@stock = Goal.where("selling_day = '#{params[:day]}'")

みたいに書くとparams[:day]に悪意のある文字列を設定され、認証をすり抜けるリスクがあります。
下記のように条件をハッシュ値で指定するか、配列で指定するようにするとリスク回避できるようです。

stocks_controller.rb
@stock = Stock.where(sold:true)

下記サイトを参考にしました。
https://railsguides.jp/active_record_querying.html
https://railsguides.jp/security.html#sql%E3%82%A4%E3%83%B3%E3%82%B8%E3%82%A7%E3%82%AF%E3%82%B7%E3%83%A7%E3%83%B3

1
0
2

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
1
0