Rails methods vulnerable to SQL injection?

百般思念 提交于 2019-11-30 22:11:11

In Rails, where, order, limit and joins all have vulnerable forms. However, Rails limits the number of SQL operations performed to 1 so vulnerability is limited. An attacker cannot end a statement and execute a new arbitrary one.

Where

Where has one vulnerable form: string.

# string, unsafe
Model.where("name = '#{params[:name]}'")

# hash/parameterized string/array, safe
Model.where(name: params[:name])
Model.where("name = ?", params[:name])
Model.where(["name = ?", params[:name]])

Order

String form is vulnerable:

# unsafe
params[:order] = "1; --\n drop table users;\n --"
Model.order("#{params[:order]} ASC")

# safe
order_clause = sanitize(params[:order])
Model.order(order_clause)

Limit

Limit has no vulnerable forms, since Rails casts input to Integer beforehand.

Model.limit("1; -- \n SELECT password from users; -- ")
=> ArgumentError: invalid value for Integer(): "1; -- \n SELECT password from users; -- "

Joins

String form is vulnerable:

params[:table] = "WHERE false <> $1; --"
Model.where(:user_id => 1).joins(params[:table])
=> SELECT "models".* FROM "models" WHERE false <> $1 -- WHERE "models"."user_id" = $1 [["user_id", 1]]

Much more comprehensive information can be found at rails-sqli.org.

Generally: If you let the user input and save any text into your database, without escaping code, it could harm your system. Especially if these texts may contain tags/code snippets.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!