python禁用内置函数,Python eval:如果我禁用内置函数和属性访问,这仍然很危险吗?...

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__

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.

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).

解决方案

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

They can evaluate expressions,

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

""

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 ''

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值