Python 的 eval() 对不可信字符串的安全性? [英] Security of Python's eval() on untrusted strings?

查看:31
本文介绍了Python 的 eval() 对不可信字符串的安全性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我正在使用 eval() 评估 Python 字符串,并且有一个类似的类:

If I am evaluating a Python string using eval(), and have a class like:

class Foo(object):
    a = 3
    def bar(self, x): return x + a

如果我不信任该字符串,会有什么安全风险?特别是:

What are the security risks if I do not trust the string? In particular:

  1. eval(string, {"f": Foo()}, {}) 不安全吗?也就是说,您能否从 Foo 实例访问 os 或 sys 或不安全的内容?
  2. eval(string, {}, {}) 不安全吗?也就是说,我可以完全从 len 和 list 等内置函数访问 os 或 sys 吗?
  3. 有没有办法让内置函数在 eval 上下文中根本不存在?
  1. Is eval(string, {"f": Foo()}, {}) unsafe? That is, can you reach os or sys or something unsafe from a Foo instance?
  2. Is eval(string, {}, {}) unsafe? That is, can I reach os or sys entirely from builtins like len and list?
  3. Is there a way to make builtins not present at all in the eval context?

有一些不安全的字符串,比如[0] * 100000000",我不在乎,因为最坏的情况是它们会减慢/停止程序.我主要关心保护程序外部的用户数据.

There are some unsafe strings like "[0] * 100000000" I don't care about, because at worst they slow/stop the program. I am primarily concerned about protecting user data external to the program.

显然,没有自定义字典的 eval(string) 在大多数情况下是不安全的.

Obviously, eval(string) without custom dictionaries is unsafe in most cases.

推荐答案

您无法使用像这样的黑名单方法来保护 eval.请参阅 Eval 真的很危险,了解将导致 CPython 解释器出现段错误的输入示例,允许访问任何你喜欢的课程,等等.

You cannot secure eval with a blacklist approach like this. See Eval really is dangerous for examples of input that will segfault the CPython interpreter, give access to any class you like, and so on.

这篇关于Python 的 eval() 对不可信字符串的安全性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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