本文介绍了Python eval:如果我禁用内置函数和属性访问,这仍然很危险吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,即使您隐藏了危险的函数,因为您可以使用Python的自省功能深入挖掘并重新提取它们。例如,即使删除 __ builtins __ ,也可以使用

We all know that eval is dangerous, even if you hide dangerous functions, because you can use Python's introspection features to dig down into things and re-extract them. For example, even if you delete __builtins__, you can retrieve them with

[c for c in ().__class__.__base__.__subclasses__()
 if c.__name__ == 'catch_warnings'][0]()._module.__builtins__

但是,我所看到的每个示例都使用属性访问。如果我禁用所有内置函数,禁用属性访问(通过使用Python标记器标记输入并在具有属性访问标记的情况下拒绝输入,该怎么办)?

However, every example I've seen of this uses attribute access. What if I disable all builtins, and disable attribute access (by tokenizing the input with a Python tokenizer and rejecting it if it has an attribute access token)?

在您问不,在我的用例中,我不需要这两个,所以它不会太残废。

And before you ask, no, for my use-case, I do not need either of these, so it isn't too crippling.

我要做的是使SymPy的功能更安全。当前,它对输入进行标记化,对其进行一些转换,然后在名称空间中进行评估。但这是不安全的,因为它允许属性访问(即使确实不需要)。

What I'm trying to do is make SymPy's sympify function more safe. Currently it tokenizes the input, does some transformations on it, and evals it in a namespace. But it's unsafe because it allows attribute access (even though it really doesn't need it).

推荐答案

我要提及Python 3.6的新功能之一-。

I'm going to mention one of the new features of Python 3.6 - f-strings.

他们可以计算表达式,

>>> eval('f"{().__class__.__base__}"', {'__builtins__': None}, {})
"<class 'object'>"

,但是Python的标记器不会检测到属性访问:

but the attribute access won't be detected by Python's tokenizer:

0,0-0,0:            ENCODING       'utf-8'
1,0-1,1:            ERRORTOKEN     "'"
1,1-1,27:           STRING         'f"{().__class__.__base__}"'
2,0-2,0:            ENDMARKER      ''

这篇关于Python eval:如果我禁用内置函数和属性访问,这仍然很危险吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 05:23