我正在挑战以证明eval
和exec
是危险的,即使它们无法访问任何内置函数。挑战是这样的:
vars(__builtins__).clear()
del __builtins__
... # your code here
print('you win') # if this line doesn't crash, you win
我想出了一些疯狂的代码,可以访问残缺的builtins
模块并重新导入该模块以恢复其功能。这是我用来挑战的代码(已在CPython 3.7中测试):
type = ''.__class__.__class__
ABCMeta = type.__subclasses__(type)[0]
abc_globals = ABCMeta.register.__globals__
importlib_globals = abc_globals['__loader__'].get_data.__globals__
sys = importlib_globals['sys']
__builtins__ = sys.modules['builtins']
loader = sys.modules['_frozen_importlib'].BuiltinImporter
spec = sys.modules['_frozen_importlib'].ModuleSpec('builtins', loader)
loader.create_module(spec)
loader.exec_module(__builtins__)
__builtins__.__spec__ = spec
但是经过挑战之后,我注意到仍然缺少一些内置函数和类:
>>> print
<built-in function print>
>>> int
<class 'int'>
>>> exit
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'exit' is not defined
>>> KeyError
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'KeyError' is not defined
这是为什么?为什么BuiltinImporter.create_module(...)
恢复int
和print
而不恢复exit
和KeyError
?