Rails 3 activerecord order - 正确的sql注入工作是什么?

发布于 2024-12-10 12:43:10 字数 626 浏览 0 评论 0原文

假设我有一个用户列表页面,您可以按不同的列进行排序,当单击“电子邮件”时,它将传递 sort_by=email sort_direction=asc 或 desc ,

sort_by = "email" # really params[:sort_by]
sort_direction = "asc" # really params[:sort_direction]
User.order("#{sort_by} #{sort_direction}")
# SELECT "users".* FROM "users" ORDER BY email asc

以便按预期工作,但是如果我们现在更改 sort_by

sort_by = "email; DELETE from users; --"
User.order("#{sort_by} #{sort_direction}")
# SELECT "users".* FROM "users" ORDER BY email; DELETE from users; -- asc

我们有没有更多的用户:(

我可以手动构建有效 sort_by 的白名单并将 params[:sort_by] 与其进行比较,但希望有一些内置的方法来处理这种事情

let us say I have a list page of users and you can sort by the different columns, when clicking 'email' it will pass sort_by=email sort_direction=asc or desc

sort_by = "email" # really params[:sort_by]
sort_direction = "asc" # really params[:sort_direction]
User.order("#{sort_by} #{sort_direction}")
# SELECT "users".* FROM "users" ORDER BY email asc

so that works as expected, however if we change the sort_by

sort_by = "email; DELETE from users; --"
User.order("#{sort_by} #{sort_direction}")
# SELECT "users".* FROM "users" ORDER BY email; DELETE from users; -- asc

now we have no more users :(

I can manually build a whitelist of valid sort_by and compare params[:sort_by] to that, but was hoping there is some built in way to handle this kind of thing

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

仙女 2024-12-17 12:43:10

Ryan Bates 的方法:

在您的控制器中:

def index
  @users = User.order(sort_by + " " + direction)
end

private
  def sort_by
    %w{email name}.include?(params[:sort_by]) ? params[:sort_by] : 'name'
  end

  def direction
    %w{asc desc}.include?(params[:direction]) ? params[:direction] : 'asc'
  end

本质上您正在制定白名单,但它很容易做到并且不易受到注入。

Ryan Bates' method:

in your controller:

def index
  @users = User.order(sort_by + " " + direction)
end

private
  def sort_by
    %w{email name}.include?(params[:sort_by]) ? params[:sort_by] : 'name'
  end

  def direction
    %w{asc desc}.include?(params[:direction]) ? params[:direction] : 'asc'
  end

Essentially you're making a whitelist, but it's easy to do and insusceptible to injection.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文