Rails 3 搜索是否容易受到 SQL 注入攻击?

发布于 2024-10-04 14:21:31 字数 879 浏览 5 评论 0原文

假设我在 Rails 3 应用程序的页面上有一个搜索框,您可以在其中按公司名称或城市搜索客户。在我的控制器的索引方法中,我这样做:

if params[:search]
  @clients = Client.where("clients.business_name LIKE :business_name OR clients.city = :city", :business_name => "%#{params[:search]}%", :city => params[:search])

这些哈希值被替换到 SQL 中并用引号引起来。如果我在搜索框中的输入包含引号或其他危险字符,我会看到它们在开发日志中被转义,例如:

...WHERE (clients.business_name LIKE '%Something\' DROP TABLE Foo%'...

或者

...WHERE... OR clients.city = 'Something OR 1=1')

因此,由于 OR 1=1 位于 Rails 添加的引号内,它只会生成与城市名称不匹配的内容,并且由于 DROP TABLE 尝试中的引号是转义后,它也不会产生与企业名称的匹配。

这不是使用实际的准备好的语句,其中查询首先发送到数据库而不填充搜索值,然后将搜索值发送到数据库进行填充。我认为这是最安全的方法,但 Rails 没有这样做;我认为这是因为它并非在所有数据库中都可用,并且实现有所不同

这是否以某种方式对 SQL 注入开放?我没有看到它,但同样,它没有使用准备好的语句,所以我想知道如果存在漏洞,我怎样才能更安全地做到这一点?

Suppose I've got a search box on a page in a Rails 3 app where you can search for a client by business name or city. In my controller's index method I do this:

if params[:search]
  @clients = Client.where("clients.business_name LIKE :business_name OR clients.city = :city", :business_name => "%#{params[:search]}%", :city => params[:search])

Those hash values get substituted into the SQL and surrounded in quotes. If my input into the search box includes quotes or other dangerous characters, I'll see them being escaped in the development log, like:

...WHERE (clients.business_name LIKE '%Something\' DROP TABLE Foo%'...

Or

...WHERE... OR clients.city = 'Something OR 1=1')

So, since the OR 1=1 is inside the quotes Rails adds, it just produces no match for the city name, and since the quote in the DROP TABLE attempt is escaped, it also produces no match for the business name.

This isn't using actual prepared statements, where the query is sent to the database first without the search values filled in, then subsequently, the search values are sent to the database to fill in. I thought that was the safest approach, but Rails doesn't do it; I think this is because it's not available in all databases and implementations vary.

Is this open to SQL injection in some way? I don't see it, but again, it's not using prepared statements, so I wonder. If there's a vulnerability, how could I do this more safely?

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

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

发布评论

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

评论(1

夜光 2024-10-11 14:21:31

不,这里不存在 SQL 注入漏洞。 ActiveRecord 将对您作为第二个参数传递给 where 的哈希值调用 connection.quote,因此您是安全的。

我能想到的唯一潜在的 SQL 注入点是 connection.quote 中存在一些未被发现的错误,但这种情况不太可能发生。

No, there's not a SQL injection vulnerability here. ActiveRecord will call connection.quote on the values of the hash that you passed in as the second parameter to where, so you are safe.

The only potential SQL injection point I could think of would be if there were some undiscovered bug in connection.quote, which is pretty unlikely.

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