是“safe_eval"吗?真的安全吗? [英] Is "safe_eval" really safe?

查看:55
本文介绍了是“safe_eval"吗?真的安全吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一个安全"的 eval 函数,以实现类似电子表格的计算(使用 numpy/scipy).

执行此操作的功能(rexec 模块)已被删除由于明显无法修复的安全问题,从 Python 2.3 开始.有几个第三方黑客声称这样做 - 我发现的最深思熟虑的解决方案是这个 Python Cookbok 食谱,safe_eval".

如果我使用它(或类似的东西)来防止恶意代码,我是否相当安全,或者我是否坚持编写自己的解析器?有没有人知道更好的选择?

我刚刚发现了 RestrictedPython,它是 Zope 的一部分.欢迎对此提出任何意见.

解决方案

我想这取决于你对安全的定义.很多安全性取决于您传入的内容以及允许在上下文中传递的内容.比如传入一个文件,我可以打开任意文件:

<预><代码>>>>名称['f'] = open('foo', 'w+')>>>safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names)>>>名字['baz']<在0x413da0处打开文件'baz',模式'w+'>

此外,环境非常受限制(您不能传入模块),因此,您不能简单地传入诸如 re 或 random 之类的实用函数模块.

另一方面,您不需要编写自己的解析器,您只需为 python ast 编写自己的评估器:

<预><代码>>>>导入编译器>>>ast = compiler.parse("打印'你好世界!'")

这样,希望您可以实现安全导入.另一个想法是使用 Jython 或 IronPython 并利用 Java/.Net 沙箱功能.

I'm looking for a "safe" eval function, to implement spreadsheet-like calculations (using numpy/scipy).

The functionality to do this (the rexec module) has been removed from Python since 2.3 due to apparently unfixable security problems. There are several third-party hacks out there that purport to do this - the most thought-out solution that I have found is this Python Cookbok recipe, "safe_eval".

Am I reasonably safe if I use this (or something similar), to protect from malicious code, or am I stuck with writing my own parser? Does anyone know of any better alternatives?

EDIT: I just discovered RestrictedPython, which is part of Zope. Any opinions on this are welcome.

解决方案

Depends on your definition of safe I suppose. A lot of the security depends on what you pass in and what you are allowed to pass in the context. For instance, if a file is passed in, I can open arbitrary files:

>>> names['f'] = open('foo', 'w+')
>>> safe_eval.safe_eval("baz = type(f)('baz', 'w+')", names)
>>> names['baz']
<open file 'baz', mode 'w+' at 0x413da0>

Furthermore, the environment is very restricted (you cannot pass in modules), thus, you can't simply pass in a module of utility functions like re or random.

On the other hand, you don't need to write your own parser, you could just write your own evaluator for the python ast:

>>> import compiler
>>> ast = compiler.parse("print 'Hello world!'")

That way, hopefully, you could implement safe imports. The other idea is to use Jython or IronPython and take advantage of Java/.Net sandboxing capabilities.

这篇关于是“safe_eval"吗?真的安全吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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