coconuts hereYou get a suspicious APK. You throw it into jadx, ready to read some Java, and you find… nothing. A couple of activities, a bridge class with a weird name, a handful of SDKs, and that’s it. No game logic, no network calls worth looking at, nothing that explains what this thing actually does. And then you scroll down and see a huge native library called libcocos.so.
Congratulations, you’ve got yourself a Cocos game.
Mobile games are the perfect disguise. Nobody finds it weird that a game asks for network access, downloads updates in the background, or ships a pile of unreadable assets. That makes them a favourite wrapper for adware, data harvesting, and all sorts of shady SDKs, which is why they keep landing on my desk. And Cocos games are a special kind of annoying, because the code you want to read is there, it’s just encrypted.
So, in this post, I’ll show you how Cocos hides its scripts, and how I get them back with a tool I wrote, coconuts, which races static analysis against Frida to find the decryption key. Spoiler: the key is always in the app. It has to be.
A game is just a fancy browser Link to heading
Cocos2d-JS and its successor Cocos Creator are hugely popular engines, especially for casual mobile games. The trick is that the engine itself is native C++ (living in libcocos.so or libcocos2djs.so), but the game logic is written in JavaScript and runs on an embedded JS engine (SpiderMonkey in older versions, V8 in newer ones).
Which means that if you open the APK, the interesting stuff isn’t in the classes.dex at all. It’s sitting in the assets/ folder:
unzip -l game.apk | grep -E 'libcocos|\.jsc$'
You’ll see something along these lines:
lib/arm64-v8a/libcocos.so
assets/jsb-adapter/jsb-builtin.jsc
assets/src/project.jsc
...
Wait, .jsc? Not .js? Yep. That c stands for “good luck”.
libcocos.so and libcocos2djs.so are just the default names. The library can be called anything: the Cocos activity doesn’t hardcode it, it reads it from a <meta-data> entry named android.app.lib_name in the AndroidManifest.xml, with the value being the name without the lib prefix and .so extension:
<meta-data android:name="android.app.lib_name" android:value="cocos" />
So if there’s no libcocos*.so in sight but the .jsc files are there, check the manifest (with apktool or aapt dump xmltree) to find out which library is actually the engine.
How Cocos hides its scripts Link to heading
Cocos ships with a built-in way to “protect” your scripts, and pretty much every game uses it. When building the game, the developer sets a key, and every .js file gets encrypted with XXTEA (and usually compressed first) before being packed as a .jsc. At runtime, the native side sets the key early on (in AppDelegate::applicationDidFinishLaunching, through jsb_set_xxtea_key or setXXTeaKey), and every time a script is loaded, it’s decrypted in memory and handed to evalString.
On top of that, there are a few quirks you need to get right, otherwise you’ll stare at garbage for hours:
- The key is always 16 bytes. Shorter keys are zero-padded, longer ones are truncated. So a key like
abc123is reallyabc123\0\0\0\0\0\0\0\0\0\0. - It’s not “standard” XXTEA padding. Cocos stores the plaintext length in the last 32-bit word of the decrypted data, instead of using PKCS#7.
- There may be a signature. Some builds prepend a fixed string to every
.jsc(viasetXXTEAKeyAndSign), which has to be stripped before decrypting. - Decrypted doesn’t mean readable. The result can be gzip-compressed JS, a ZIP, plain text, or even compiled SpiderMonkey bytecode.
- Not everyone uses XXTEA. Some developers swap it for a simple repeating XOR, and some builds use x-studio’s
EncryptManager, which encrypts every asset (not just scripts) with AES-256-CBC.
So, to get the code, we need the key. And the key, by definition, has to be somewhere in the app, because the app itself needs it to run. We just need to find it.
Enter coconuts Link to heading
There are two classic ways to find a key like this:
- Statically: dig through
libcocos.sountil you find it. No device needed, but it’s guesswork and can be slow. - Dynamically: run the game with Frida and hook the function that receives the key. Fast and precise, but only if you know where to hook, and if the game doesn’t crash or detect you first.
I kept doing one, then the other, then going back to the first one. So I wrote coconuts, which does the obvious thing: it does both at the same time, and whoever finds the key first wins.
Under the hood, it’s two threads, a static track and a dynamic track, each with an “abort” flag that the other can raise. The moment one of them finds a key, it signals the other one to stop, and the tool moves on to decrypting everything. The output tells you which track is talking, so you can watch the race as it happens:
[*] Racing the static key search against Frida...
[*] static: Found 42 .jsc asset(s) across 1 input path(s).
[*] frida: xxtea_decrypt found in the symbol table at 0x...
[+] static: Key found (candidate #3, 12.4 ms): '...'
[*] frida: Static track found the key first; stopping Frida.
The static track Link to heading
The static track pulls the APK(s) from the device with adb (or uses the ones you give it), collects every assets/*.jsc, and then tries to recover the key without ever running the game.
Step 0: Is there a signature? Link to heading
Before trying any key, it looks at all the .jsc files and checks for a common prefix. Encrypted data should look random, so if every single file starts with the same bytes, that’s the signature, and it gets stripped. It’s also smart enough to make sure what’s left is still a multiple of 4 bytes, since XXTEA works on 32-bit words.
Step 1: The free win, XOR Link to heading
If the developer went with XOR instead of XXTEA, we don’t even need to look at the library. Some files are identical in every Cocos game, like jsb-builtin.jsc, which always starts with the same boilerplate:
(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){
And XOR has a very inconvenient property for whoever is using it to hide things: ciphertext ^ plaintext = key. So coconuts XORs the start of the file with that known plaintext, looks for a repeating pattern in the result, and there’s the key. This is a classic known-plaintext attack, and it takes less than a millisecond. The same trick works on compiled bytecode, which always starts with the same SpiderMonkey magic bytes.
Step 2: Ranked key candidates Link to heading
If it’s XXTEA, then we hunt for the key inside libcocos.so. Instead of blindly trying every string in a huge binary, the candidates are ranked by how likely they are:
| Tier | Where it looks |
|---|---|
| 0 | On stripped arm64 builds, a pointer at a fixed offset of .data.rel.ro that leads straight to setXXTeaKey. Then, string literals referenced directly inside applicationDidFinishLaunching, jsb_set_xxtea_key or setXXTeaKey, found with radare2 by disassembling just those functions, not the whole library. |
| 1 | Strings sitting right next to well-known Cocos boot strings like main.js, jsb-adapter/jsb-builtin.js, project.jsc or the signature itself. Compilers love to put related constants together. |
| 2 | Strings that match the typical shapes of Cocos keys (e.g. xxxxxxxx-xxxx-xx, or 16 alphanumeric characters). |
| 3 | Everything else that looks like a plausible key: 4 to 32 printable characters, no spaces, paths or format specifiers. |
Each candidate is tested against the three smallest .jsc files, since they’re the quickest to decrypt. A key is only accepted if it decrypts all of them into something that looks like a script, and here’s where the Cocos length word comes in really handy:
raw = _xxtea_raw_decrypt(payload, key16)
n = len(raw)
m = struct.unpack_from("<I", raw, n - 4)[0]
if m < n - 7 or m > n - 4:
return None
If the length stored at the end doesn’t make sense, the key is wrong, no need to even look at the content. Most wrong keys are thrown out right there.
coconuts uses the xxtea C extension, which is about 150 times faster than XXTEA in pure Python. It doesn’t trust it blindly, though: the first result is checked against a pure-Python reference implementation, and if they ever disagree, it falls back to the slow-but-correct one.The dynamic track Link to heading
While the static track is grinding through candidates, the dynamic track gets ready to hook the game.
First, it uses radare2 to figure out where to hook. It always tries the cheap paths first: looking up xxtea_decrypt and ScriptEngine::evalString in the symbol table, or using that .data.rel.ro trick. Only if those fail does it fall back to a full radare2 analysis, which can take a while on a big library. And because it’s a race, it waits for the static track to finish tiers 0 to 2 first. There’s no point in burning a minute on code analysis if the key was sitting right in applicationDidFinishLaunching. If the static track wins in the meantime, the radare2 process is killed on the spot.
Then it spawns the game with Frida and injects a script that:
- Hooks the dynamic linker (
do_dlopen), so the hooks are installed as soon as the engine is loaded, before the game has a chance to set the key. And it doesn’t go by the file name: it recognises the engine by itsJavascriptJavaBridgeJNI export, the bridge every Cocos JS engine needs to talk to Java. So whateverandroid.app.lib_namesays, it finds the right library. - Hooks
xxtea_decrypt,jsb_set_xxtea_keyandsetXXTeaKeyto grab the key, whether it’s passed as a raw buffer or as a C++std::string(and yes, it parses the libc++ short/long string layout to read it). - Hooks
evalStringto dump every script as it’s executed, already decrypted. This also catches scripts that aren’t in the APK at all, like hot updates downloaded at runtime. That’s exactly where shady behaviour likes to hide! - Hooks
EncryptManager::setEncryptEnabledto grab the AES key, the IV and the flags in one go.
Once it has a key, Frida stays attached for a few more seconds (5 by default) to keep collecting live scripts.
There’s one more thing: a key from Frida stops the static search, so it’d better be right. Before trusting it, coconuts tries it on the .jsc files from the APK. If it doesn’t decrypt them, the captured key is thrown away and the static search picks up where Frida cut it short.
frida-server running and a proxy like OWASP ZAP watching the traffic. While coconuts grabs the scripts, you can see in ZAP exactly which hot updates the game is downloading.When it’s AES Link to heading
EncryptManager is a different beast. Instead of protecting just the scripts, it encrypts every asset: scripts, images, audio, configs. Each file is laid out like this:
file = AES-256-CBC( zlib(plaintext) ) + 16-byte signature block
The signature block at the end is what makes it interesting. It’s encrypted separately with AES-128-ECB, using a key derived from the main key and IV by running AES on itself a number of times (the roll, 5 by default). Once decrypted, it holds two 32-bit words that must XOR to 0xDEADBEEF, plus the flags and the original size:
sig = AES.new(sign_key, AES.MODE_ECB).decrypt(data[-16:])
mask, sigval = struct.unpack_from("<II", sig, 0)
if (mask ^ sigval) != AES_DEADBEEF:
return None
That gives us the same kind of free check as the XXTEA length word: if the signature doesn’t come out as 0xDEADBEEF, the key, IV or roll is wrong.
And this is where the Frida hook pays off. The roll isn’t stored anywhere in the files, but it is stored in the upper 16 bits of the flags argument passed to setEncryptEnabled. So when Frida captures the key, it gets the IV and the roll for free, and you don’t have to guess anything.
When decrypting, coconuts first checks the key against the .jsc files, since those are always encrypted. Once the key is confirmed, any other file that doesn’t decrypt isn’t a failure, it’s just a resource the developer chose not to encrypt, so it’s copied as-is. You get the whole assets/ folder back, readable.
And the winner is… Link to heading
Doesn’t really matter! Once there’s a key, coconuts moves to offline extraction: it decrypts every .jsc (or every asset, for AES), strips the signature, decompresses whatever was compressed, and writes everything to the output folder with the right extension (.js, .zip, or .mozjs.jsc for SpiderMonkey bytecode).
A couple of details I’m quite happy with:
- Live dumps take precedence. If Frida already captured a script while the game was running, the offline copy doesn’t overwrite it.
- Nothing is lost. If no key works, all the raw
.jscfiles are saved in araw_jsc/folder for manual digging. And if a “key” decrypts nothing at all, it tells you it’s probably wrong instead of pretending everything went fine. - No path traversal. Every output path, offline or live, is checked to make sure it stays inside the output folder. A file named
../../.bashrcinside a malicious APK is not going anywhere. You’re analysing potentially malicious apps, after all: safety glasses first!
Using it Link to heading
coconuts is a Python package with a coconuts command, so the easiest way to install it is with pipx, which takes care of the Python dependencies:
pipx install git+https://codeberg.org/davidjosearaujo/coconuts
There are three things it can’t install for you, because they aren’t Python packages:
- radare2, for the static key search.
adb, from the Android platform-tools. It doesn’t need to be in yourPATH:coconutsalso looks in$ANDROID_HOME,$ANDROID_SDK_ROOTand the default Android Studio SDK folder. Not needed if you give it APKs with--apk.frida-server, running as root on the device, for the dynamic track.
Grab the native library from the APK (look in lib/arm64-v8a/ for libcocos.so, libcocos2djs.so, or whatever name android.app.lib_name points to), and point coconuts at it along with the package name:
# Race static vs. Frida, then decrypt everything from the APK
coconuts ./libcocos.so com.example.game ./out
# Keep collecting live (and hot-updated) scripts for 60s after finding the key
coconuts ./libcocos.so com.example.game ./out --live-seconds 60
# No device, no Frida: static only, against a local APK
coconuts ./libcocos.so com.example.game ./out --static-only --apk ./base.apk
# EncryptManager AES, with a key and IV you already have
coconuts ./libcocos.so com.example.game ./out --apk ./base.apk --aes-key <hex> --aes-iv <hex>
If you leave out the output folder, everything goes to dumped_cocos_assets/.
Some other useful options:
| Option | What it does |
|---|---|
--key | You already know the key? Skip the whole race. |
--sign | Force a specific signature instead of auto-detecting it. |
--aes-key / --aes-iv | Decrypt EncryptManager AES assets with a known key and IV (in hex). An empty IV means the default, sixteen 0x01 bytes. |
--aes-roll | The EncryptManager roll count (default: 5). Only needed when you pass the AES key yourself; Frida captures it automatically. |
--apk | Use local APK(s) or a folder of .jsc files instead of pulling from the device (repeatable). |
--device | Pick the device by its adb serial / Frida ID, when you have more than one. |
--timeout | How long to wait for Frida to catch the key (default: 10s). |
--all-splits | Also pull the split_config.*.apk files, which are skipped by default because they never contain scripts. |
-v | Verbose mode, for when things go sideways. |
--no-color | Plain output, for logs and pipes. |
When something’s wrong with the device, coconuts says so in one line instead of dumping a traceback on you: no device connected, more than one connected, the debugging prompt not accepted yet, or an emulator that hasn’t finished booting.
Where it falls short Link to heading
It’s not magic, and there are a few things you should know before relying on it:
- arm64 only. The radare2 analysis and offsets assume an arm64 library. Also, Frida can’t hook arm64 code running through the ARM translation layer of an x86_64 emulator, so for the dynamic track you need an arm64 device or image (an arm64 emulator on an Apple-silicon Mac works great). Otherwise, use
--static-only. - AES needs the signature block.
coconutsrelies on the0xDEADBEEFsignature to know a file decrypted correctly. That’sEncryptManager’s default, but a build that turns the signature off won’t decrypt. - Bytecode stays bytecode. If the scripts were compiled to SpiderMonkey bytecode, you get the
.mozjs.jscfiles, but turning them back into JavaScript is a whole different adventure. - Some of it is empirical. When there are no symbols to help, finding the key function relies on patterns observed in the builds I tested against (like which call inside the “Can’t decrypt code for %s” function is the
xxtea_decrypt). There are fallbacks, but a different Cocos version may need some tweaking. - Anti-Frida. Games with Frida detection may crash before the key is captured. The static track doesn’t care, though, which is half the reason the race exists.
Conclusion Link to heading
The more I play with Cocos games, the more I’m convinced that client-side encryption is just a speed bump. The key has to be in the app for the app to work, so the only question is how long it takes you to find it. With two tracks racing each other, that’s usually seconds.
And once the code is out, a game stops being a black box and becomes just another pile of JavaScript, which is a much nicer thing to read than ARM assembly, trust me.
Happy hunting!