repositories

daemon-sec-cheatsheet

The cheatsheet vault for operators: AD, enumeration, exploitation, priv-esc, web, DFIR

clonegit clone https://git.daemon-sec.xyz/daemon-sec-cheatsheet.git
manual-deobfuscation.mdMarkdown258 lines17.9 KiBsource raw download

title: "Manual De-obfuscation Techniques" section: "Mobile" sectionSlug: "mobile-pentesting" sourcePath: "src/mobile-pentesting/android-app-pentesting/manual-deobfuscation.md" sourceUrl: "https://github.com/HackTricks-wiki/hacktricks/blob/188de82beb54e70956b2952367a0af91d26758b8/src/mobile-pentesting/android-app-pentesting/manual-deobfuscation.md" sha: "188de82beb54e70956b2952367a0af91d26758b8" isIndex: false modified: true license: "CC-BY-NC-4.0"#

Manual De-obfuscation Techniques#

Manual De-obfuscation Techniques#

In the realm of software security, the process of making obscured code understandable, known as de-obfuscation, is crucial. This guide delves into various strategies for de-obfuscation, focusing on static analysis techniques and recognizing obfuscation patterns. Additionally, it introduces an exercise for practical application and suggests further resources for those interested in exploring more advanced topics.

Strategies for Static De-obfuscation#

When dealing with obfuscated code, several strategies can be employed depending on the nature of the obfuscation:[2]

Identifying Obfuscation#

Recognizing obfuscated code is the first step in the de-obfuscation process. Key indicators include:[2]

Dynamic Analysis in De-obfuscation#

By executing the code in a controlled environment, dynamic analysis allows for the observation of how the obfuscated code behaves in real time. This method is particularly effective in uncovering the inner workings of complex obfuscation patterns that are designed to hide the true intent of the code.[3][4]

Applications of Dynamic Analysis#

Automated De-obfuscation with LLMs (Androidmeda)#

While the previous sections focus on fully manual strategies, in 2025 a new class of Large-Language-Model (LLM) powered tooling emerged that can automate most of the tedious renaming and control-flow recovery work.
One representative project is Androidmeda – a Python utility that takes decompiled Java sources (e.g. produced by jadx) and returns a greatly cleaned-up, commented and security-annotated version of the code.[5][6]

Key capabilities#

Installation#

git clone https://github.com/In3tinct/Androidmeda
cd Androidmeda
pip3 install -r requirements.txt

Preparing the inputs#

  1. Decompile the target APK with jadx (or any other decompiler) and keep only the source directory that contains the .java files:
    jadx -d input_dir/ target.apk
    
  2. (Optional) Trim input_dir/ so that it only contains the application packages you want to analyse – this massively speeds-up processing and LLM costs.

Usage examples#

Remote provider (Gemini-1.5-flash):

export OPENAI_API_KEY=<your_key>
python3 androidmeda.py \
  --llm_provider google \
  --llm_model gemini-1.5-flash \
  --source_dir input_dir/ \
  --output_dir out/ \
  --save_code true

Offline (local ollama backend with llama3.2):

python3 androidmeda.py \
  --llm_provider ollama \
  --llm_model llama3.2 \
  --source_dir input_dir/ \
  --output_dir out/ \
  --save_code true

Output#

Tips & troubleshooting#

Practical value – Crocodilus malware case study#

Feeding a heavily obfuscated sample from the 2025 Crocodilus banking trojan through Androidmeda reduced analysis time from hours to minutes: the tool recovered call-graph semantics, revealed calls to accessibility APIs and hard-coded C2 URLs, and produced a concise report that could be imported into analysts’ dashboards.[5]


Targeted Dalvik string decryption with DaliVM#

DaliVM is a Python Dalvik bytecode emulator aimed at statically recovering runtime-only values (especially decrypted strings) without spinning up Android. It executes a specific method inside an APK by emulating Dalvik opcodes and mocking Android/Java APIs.[1]

Workflow

  1. Select target method by Dalvik signature (Lpkg/Class;->method(Args)Ret). Examples: Lutil/Crypto;->decrypt(Ljava/lang/String;)Ljava/lang/String;, LMyClass;->compute(II)I.
  2. Enumerate call sites across multi-DEX (classes*.dex) and reconstruct arguments via backward data-flow tracing, forward lookup, and partial execution when needed.
  3. Emulate the method inside the Dalvik VM (covers 120+ opcodes across const/array/control/field/invoke, handles class init via <clinit>) and collect return values (e.g., decrypted strings).
  4. Bypass runtime dependencies using built-in mocks for common Android APIs (Context, PackageManager, Signature, reflection, system services) and hooks for Java stdlib (String/StringBuilder/Integer/Math/Arrays/List/Iterator).
  5. If execution stalls, enable opcode-level tracing to see PC/register changes and extend opcode handlers.

CLI usage

# Emulate a decryptor and dump all returns
python emulate.py app.apk "Lcom/example/Decryptor;->decrypt"

# Verbose, debug trace, and limit outputs
python emulate.py app.apk "Lcom/example/Decryptor;->decrypt" -v --debug --limit 10

Outputs are the collected return values per invocation; useful for bulk string/config extraction during malware triage or heavily obfuscated apps.

Offline recovery of staged Android malware payloads#

A recurring Android malware pattern is a small Java stub + stripped JNI loader + high-entropy asset. If the APK contains a native library with one abnormally large JNI export, encrypted strings, and an assets/ blob that doesn't match its file extension, you can usually recover the next stage without executing the sample.[7]

Repair hostile APK and DEX metadata before decompiling#

Treat an APK as an adversarial ZIP, not as a trustworthy filesystem tree. List members before extraction and reject absolute paths, normalized paths that escape the output directory, and file/directory collisions. A sample can remain installable while crafted names make extractors omit entries, crash, or write outside the analysis directory.[8][11]

A DEX parser error also does not prove that the bytecode is encrypted. Compare the header and map_list against the actual layout: section sizes must fit inside file_size, fixed-width tables must be aligned, indexes must stay within their target tables, and string_data, class_data, and code_item references must decode consistently. A packer can swap map type labels or point table entries at valid-but-wrong data so a disassembler follows the attacker's metadata instead of the real structures.[9][11]

Useful repairs on a disposable copy are:[9][11]

Recover indexed native string oracles and encrypted assets#

When most Java strings are calls such as nativeGetStr(int), enumerate the integer call sites and reverse the single JNI routine as a string oracle.[8][11] In a stripped native library, the fixed AES S-box and Rcon tables identify AES; a nonce/counter block plus an incrementing counter distinguishes CTR-like use from ECB/CBC.[11] Preserve the exact counter layout and endianness when reimplementing it, then iterate all valid indexes to recover configuration, asset names, permission strings, and payload parameters in bulk.[11]

Apply recovered cipher parameters to high-entropy, extensionless assets offline and validate the plaintext independently rather than trusting a successful decrypt. For an embedded APK, check ZIP integrity and its signing metadata:[8][11]

file stage2.bin
unzip -t stage2.bin
apksigner verify --verbose --print-certs stage2.bin

Reconstruct DPT-Shell method bodies#

DPT-Shell hollows DEX method implementations and reconstructs them at runtime.[10] Strong fingerprints are a small ProxyApplication/JniBridge stub, assets/OoooooOooo, and a native loader below assets/vwwwwwvwww/ for each ABI.[10][11] Repair deceptive DEX table offsets before resolving method indexes; otherwise valid code-store records will be mapped to the wrong methods.[11]

The upstream writer and runtime parser define the code store as little-endian records:[10]

u16 version
u16 dex_count
u32 dex_section_offset[dex_count]
for each DEX section:
    u16 method_count
    repeat method_count times:
        u32 method_idx
        u32 instruction_size_bytes
        u8  instructions[instruction_size_bytes]

For each DEX section, use method_idx as an index into that file's method_ids, locate the method's code_item, and restore its insns[] bytes.[10][11] Keep DEX instruction units in mind: code_item.insns_size counts 16-bit code units whereas the external store records a byte length. Validate every offset/length against the store boundary, then regenerate the DEX signature/checksum after patching.[9][10]

Also inspect nominal image resources instead of assuming they are decoration. For PNGs, concatenate IDAT chunks in file order, decompress the zlib stream, and compare its expected scanline length with the actual output; unexplained trailing data or additional streams can be another code/payload carrier.[11]

OLLVM-style native XOR string recovery#

A common native pattern is a one-time init block that decrypts strings in place byte-by-byte:

if (init_done == 0) {
    DAT_00142f50 ^= 0xd7;
    DAT_00142f51 ^= 0xb4;
    DAT_00142f52 ^= 0xa6;
    init_done = 1;
}

Practical workflow:

This is especially useful when the native loader decrypts its strings only on the first invocation, leaving plaintext only in process memory but never on disk.

Rebuilding filename-derived AES asset decryptors#

Once native strings reveal constants such as an asset name, SHA-1, SHA-256, and AES/CBC/PKCS5Padding, recreate the decryptor offline and validate the result with file magic:

from Crypto.Cipher import AES
import hashlib
ct = open('asset.bin','rb').read()
seed = b'asset_name2'
key = hashlib.sha1(seed).digest()[:16]
iv = hashlib.sha256(seed).digest()[:16]
pt = AES.new(key, AES.MODE_CBC, iv).decrypt(ct)
pt = pt[:-pt[-1]]
open('stage2.bin','wb').write(pt)

Triage hints:

StringFog and similar DEX string obfuscators#

If JADX shows many Base64-looking constants and a helper like StringFogImpl.decrypt(String), extract the key and replay the transform over all candidate strings. One common variant is Base64 decode + repeating-key XOR:

import base64
def sf(s):
    key = b'UTF-8'
    ct = base64.b64decode(s)
    return bytes(c ^ key[i % len(key)] for i, c in enumerate(ct)).decode()

Recovered plaintext commonly reveals Firebase paths, Telegram bot logic, phishing URLs, WebView resources, and operator config that do not appear anywhere else in the APK.

Treat split APKs, loaders, and web assets as one payload chain#

After decrypting a staged container:

References#