Insecure Deserialization in CTF: Exploiting PHP and Python part 2

Depov

Moderator
Staff member
MODERATOR
ULTIMATE
SUPREME
PREMIUM
MEMBER
Joined
Feb 18, 2025
Messages
790
Reaction score
1,510
Python Pickle Exploitation: Reduce and the Path to RCE

Python pickle is a binary serialization protocol from the standard library. pickle.dumps()converts an object into a byte string, pickle.loads()Restores. The key difference from PHP: Python Pickle RCE doesn't require gadget chains or access to the application's source code. At all.

Method __reduce__determines how the object is reconstructed during deserialization. It returns a tuple (callable, args) - And pickle.loads()will cause callable(*args). Substituting os.systemas a callable, we get the execution of arbitrary code:

import pickle, base64

class Exploit:
def __reduce__(self):
import os
return (os.system, ('cat /flag.txt',))

payload = base64.b64encode(pickle.dumps(Exploit()))
print(payload.decode())

Result pickle.loads(base64.b64decode(payload))will perform os.system('cat /flag.txt')on the server. No additional classes are required on the application side. In PHP, RCE requires a suitable gadget chain with a sink function; in Python, any call pickle.loads()On untrusted data, it already yields a full RCE. This pickle Python exploitation is fundamentally simpler: the barrier to entry is lower, but the result is the same.

In CTFs, pickle tasks are most often disguised as cookies (base64-encoded), WebSocket messages, or POST bodies in Flask/Django APIs. Signature: bytes \x80\x04\x95at the beginning (protocol 4) or \x80\x05\x95(protocol 5). Protocol 0 is text-based and starts with (dp0 or cos\n.

For debugging, there is a built-in disassembler pickletools.dis(), showing each opcode:

import pickle, pickletools

class Exploit:
def __reduce__(self):
import os
return (os.system, ('id',))

pickletools.dis(pickle.dumps(Exploit()))

The output will show the sequence: GLOBAL 'posix system', SHORT_BINUNICODE 'id', TUPLE1, REDUCE, STOPEach opcode is a single-byte pickle instruction. Understanding this sequence is critical for filter bypass.
Pickle opcodes — manual assembly and filter bypass

On CTFs of medium and high difficulty it appears RestrictedUnpickler— a custom class that inherits pickle.Unpicklerand overriding method find_class()Typical filtering blocks imports. os, subprocess, builtins— standard modules for RCE. Standard __reduce__payload c os.systemIt won't work. This is where manual work with opcodes begins.
Pickle opcodes structure

Pickle is a stack-based virtual machine. Key opcodes: c(GLOBAL - import module and attribute), ((MARK — stack mark), t(TUPLE - assemble a tuple of elements up to MARK), R(REDUCE — call a callable with arguments), .(STOP - completion). Minimum payload for os.system('id')in protocol 0:

b"cos\nsystem\n(S'id'\ntR."

Eighteen bytes and RCE.

Parsing by opcodes: cimports os.system, (puts MARK, S'id'pushes a string onto the stack, tassembles a motorcade ('id',), Rcauses system('id'), .terminates execution. If pickletools.dis()shows an error: the opcode or its argument is incorrectly formed. Recompile.
Bypassing RestrictedUnpickler

Specific bypass methods depend on the filter's implementation. Here are a few tricks I've seen at CTFs:

If the filter checks the module name for an exact match with os, but does not block posix or nt— we call systemvia an alternative module name. On Linux os.systeminternally proxies through posixThe filter looks at the string "os"—and we slip in "posix." Missed.

If allowed builtins.getattr, the payload is collected through the chain: get a link to __import__through getattr, import the required module, call the function. This bypasses the filter on GLOBALfor a specific module.

If builtins.evalnot blocked - all filtering GLOBALfor individual modules it is meaningless because eval('__import__("os").system("id")')bypasses any restrictions at the opcode level. One unlocked eval— and all defenses fall apart.

For advanced tasks: opcode i(INST) and o(OBJ) - alternative ways to create objects that some filters do not take into account. Opcode b(BUILD) calls __setstate__, which can become a separate vector if the application defines this method.

The main tool when working with limited unpicklers is pickletools.dis()At each stage of payload assembly. If the payload is rejected, disassemble it, find the opcode that's blocking the filter, and replace it with an alternative. Methodically.
Web CTF deserialization — task-to-flag algorithm

A step-by-step workflow for ctf writeup deserialization that works for most tasks:

Step 1 - Determine the format. PHP serialization starts with O:, a:, s:. Pickle protocol 0 — с cos\n or (dp0. Pickle protocol 2+ — с \x80\x02 (or \x80\x04, \x80\x05). Java — c ac edin hex or rO0in base64. Base64-decode all cookies and hidden parameters.

Step 2 - Determine the language and framework. Response headers ( X-Powered-By: PHP/7.4, Server: Werkzeug), URL structure ( /index.php vs /api/v1/), configuration files ( composer.json or requirements.txtvia LFI / source disclosure).

Step 3: Build the payload. For PHP: grep -rn '__destruct\|__wakeup\|__toString'according to the source code, if available. The framework is known - phpggc -l <framework>For Python without filters - __reduce__payload c os.systemWith filters - analysis find_class()and selection of a workaround.

Step 4: Deliver. The encoding depends on the channel: base64 for cookies, URL-encode for GET, raw bytes for POST. Send via Burp Suite Repeater, check the response or side effect (file appearance, DNS request to a controlled domain).

Step 5 - Debugging. PHP: Recalculate string lengths and number of properties - unserialize()silently returns falseon error. Pickle: pickletools.dis()will show the broken opcode with the exact position.
PHP vs. Python: A Comparison of Approaches
Characteristic PHP unserialize Python pickle
Data format Text, readable Binary (opcodes)
The path to RCE Magic methods + gadget chain reduce directly
Source code needed Yes (for chain building) No
Main tool phpggc Manual assembly + pickletools
Typical defense allowed_classes RestrictedUnpickler
Complexity of basic operation Medium-high Low (without filters)
Difficulty with filters High Medium-high

At every other web CTF I've participated in over the past year, at least one problem is related to deserialization—PHP or Python. The difference between solving it in 15 minutes and getting stuck for two hours is understanding what's happening at the byte level, not having a ready-made script. Participants who copy payloads from someone else's writeup fail at the first non-standard filter: RestrictedUnpickler with a whitelist of modules. allowed_classes V unserialize(), HMAC на cookie.
 
Top Bottom