'eval' 应该是讨厌的吗? [英] Is 'eval' supposed to be nasty?

查看:50
本文介绍了'eval' 应该是讨厌的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经多次使用 ruby​​ 的 eval 特性.但我听说有人说 eval 很讨厌.当被问到为什么以及如何使用它时,我永远找不到令人信服的理由不使用它.他们真的很恶心吗?如果是,以什么方式?什么是可能的更安全"的评估选项?

I have been using eval feature of ruby many a times. But I have heard people saying evals are nasty. When asked, why and how, I could never get a convincing reason not to use it. Are they really nasty? If yes, in what way? What are possible "safer" options to eval?

推荐答案

如果您正在eval一个由用户提交或可由用户修改的字符串,这无异于允许任意代码执行.想象一下,如果字符串包含对 rm -rf/ 或类似的操作系统调用.也就是说,在您知道字符串被适当限制的情况下,或者您的 Ruby 解释器被适当地沙箱化,或者理想情况下,eval 可能会非常强大.

If you are evaling a string submitted by, or modifiable by the user, this is tantamount to allowing arbitrary code execution. Imagine if the string contained an OS call to rm -rf / or similar. That said, in situations where you know the strings are appropriately constrained, or your Ruby interpreter is sandboxed appropriately, or ideally both, eval can be extraordinarily powerful.

这个问题类似于 SQL 注入,如果您熟悉的话.这里的解决方案类似于注入问题的解决方案(参数化查询).也就是说,如果您要eval 的语句已知具有非常特定的形式,并且不需要用户提交所有语句,则只需一个一些变量、数学表达式或类似的东西,您可以从用户那里获取这些小片段,必要时对其进行清理,然后在将用户输入插入适当位置的情况下评估安全模板语句.

The problem is analogous to SQL injection, if you're familiar. The solution here is similar to the solution to the injection problem (parameterized queries). That is, if the statements you would like to eval are known to be of a very specific form, and not all of the statement need be submitted by the user, only a few variables, a math expression, or similar, you can take in these small pieces from the user, sanitize them if necessary, then evaluate the safe template statement with the user input plugged in in the appropriate places.

这篇关于'eval' 应该是讨厌的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆