Access module "sys" without the use of imported equipment

Sandbox Python code is known to be complex due to the power of reflection objects embedded in the language. At a minimum, you need to remove the mechanism importand most of the built-in functions and global variables, and even then there are holes ( {}.__class__.__base__.__subclasses__()for example).

In both Python 2 and 3, the sys module is built into the interpreter and preloaded before the user code starts executing (even in mode -S). If you can get a module descriptor sys, then you will have access to the global list of loaded modules ( sys.modules), which will allow you to do all kinds of naughty things.

So, the question is: starting with an empty module, without using the import mechanism at all (without import, no __import__, no implibrary, etc.), and also without using anything usually found in __builtins__if you cannot process it with any other way, is it possible to get a link to sysor sys.modules? (Each points to another.) I am interested in the answers of both 2.x and 3.x.

+4
source share
1 answer

__builtins__usually can be restored by returning the path to __import__and therefore to any module.

For Python 3, this eryksun comment works, for example:

>>> f = [t for t in ().__class__.__base__.__subclasses__() 
...      if t.__name__ == 'Sized'][0].__len__
>>> f.__globals__['__builtins__']['__import__']('sys')
<module 'sys' (built-in)>

In Python 2, you just find another object :

>>> f = [t for t in ().__class__.__base__.__subclasses__()
...      if t.__name__ == 'catch_warnings'][0].__exit__.__func__
>>> f.__globals__['__builtins__']['__import__']('sys')
<module 'sys' (built-in)>

, ( ), . __globals__, __builtins__.

, "" __import__, __builtins__.

__globals__ sys. sys Python 3, , flash:

>>> next(getattr(c, f).__globals__['sys']
...      for c in ().__class__.__base__.__subclasses__()
...      for f in dir(c)
...      if isinstance(getattr(c, f, None), type(lambda: None)) and
...         'sys' in getattr(c, f).__globals__)
<module 'sys' (built-in)>

Python 2 , , :

>>> next(getattr(c, f).__func__.__globals__['sys']
...      for c in ().__class__.__base__.__subclasses__()
...      for f in dir(c)
...      if isinstance(getattr(c, f, None), type((lambda: 0).__get__(0))) and
...         'sys' in getattr(c, f).__func__.__globals__)
<module 'sys' (built-in)>
+3

Source: https://habr.com/ru/post/1617137/


All Articles