馃摝

HKCERT CTF 2023: Secure Python 2 (Pwn)

In this challenge, we are tasked with bypassing a Python sandbox that restricts certain function calls, such as exec and __import__, through AST (Abstract Syntax Tree) transformations. The goal is to execute system commands despite these restrictions.

Key Concepts:

  1. Sandbox Restrictions:
      • The sandbox blocks certain functions (e.g., exec, __import__, and input) by analyzing the Python code's AST.
      • However, decorators (e.g., @exec, @input) aren't always treated the same way and may bypass the restrictions.
  1. Using Decorators:
      • By applying @exec and @input as decorators to a class definition, we can indirectly execute the system command without triggering the sandbox's AST filters.
      • The input function, which usually reads user input, can accept a payload that isn't filtered out by the sandbox when applied through decorators.
  1. Unicode Characters as Identifiers:
      • Python 3 allows using non-ASCII characters as variable names or function names.
      • By using visually similar Unicode characters for exec and input, we can bypass the blacklist because these characters look like the restricted keywords but are different enough to be accepted.

Exploit Strategy:

  1. Payload:
      • We use Unicode characters to replace exec and input:
        • @锝厁ec @锝塶put class X: pass
      • When we run this, the sandbox doesn鈥檛 block the decorators because they are non-ASCII. Then, we input the payload:
        • __import__("os").system("cat flag.txt")
  1. Why It Works:
      • The decorators aren鈥檛 filtered out because of the Unicode trick.
      • The payload gets executed through the input function, bypassing the usual AST filters and running the system command.

Exploit in Action:

# Step 1: Use Unicode decorators to bypass the sandbox @锝厁ec @锝塶put class X: pass # Step 2: Input the payload to execute the system command >>> __import__("os").system("cat flag.txt")

Reference Link:

For more details about this challenge, you can visit the official GitHub page of the challenge: