Lab 02 — Configuration recovery and capability adjudication¶
Difficulty: Intermediate Time: 2–3 hours Prerequisites: Lab 01, README §3.1–§3.5, README §3.10, 34-Cryptography
SAFETY. The target is the inert sample you built in lab 01. It has no payload, no C2 client and no working capability. Every hostname it carries is under
.invalid, which RFC 2606 reserves permanently so that it can never resolve. Nothing in this lab is installed or executed on any device.
Objective¶
Two halves, and the second is the harder one.
Half A — recovery. Get the plaintext of both config blobs. You will do it three different ways for the XOR blob, including one that uses no key material at all, and two ways for the AES blob.
Half B — adjudication. Given a decrypted config and a capability profile, decide what you can honestly say, and write it. This is where most people either under-claim (a page of hedging nobody can act on) or over-claim (a family name and a confident verdict).
Part A — Know the answer first¶
# host
cd 69-MalwareAnalysis/examples/inert-sample
python3 -B make-config-assets.py --show
Read both plaintexts. Note in particular:
- the XOR key is
ch69-inert-xor— 14 bytes - the AES key is
6b39ff0e2c7a41d5— 16 ASCII characters, used directly as 16 key bytes - the AES blob is CBC with the IV as the first 16 bytes
- both plaintexts are
json.dumps(..., indent=2, sort_keys=True), so they begin{\n "and are heavily indented
That last detail matters more than it looks and Part B.2 depends on it.
Part B — The XOR blob, three ways¶
Extract the blobs so you can work on them directly:
# host
mkdir -p /tmp/ch69/blobs && cd /tmp/ch69/blobs
python3 -B -c "
import zipfile
z = zipfile.ZipFile('/tmp/ch69/inert-sample.apk')
for n in ('assets/cfg-xor.bin', 'assets/cfg-aes.bin'):
open(n.split('/')[-1], 'wb').write(z.read(n))
"
ls -l
B.1 — With the key (the easy case)¶
# host
cd /path/to/69-MalwareAnalysis
python3 -B scripts/config-decrypt.py --file /tmp/ch69/blobs/cfg-xor.bin \
xor --key 'ch69-inert-xor'
Expected:
key : supplied 'ch69-inert-xor'
score : 0.81 (printable=1.00 json_markers=2 url_markers=3)
entropy : 4.90 bits/byte
plaintext:
{
"campaign": "CH69-INERT-DEMO",
"kill_switch": "NO-OP: this build contains no execution path",
...
"next_stage_url": "https://stage2.c2-example.invalid/p/loader.bin",
...
}
indicators (defanged):
url hxxps://stage2[.]c2-example[.]invalid/p/loader[.]bin
host stage2[.]c2-example[.]invalid
Question B.1.a. The indicators are printed as hxxps:// with [.] for
dots. Why?
Answer
Defanging. Reports get pasted into chat clients and ticketing systems that auto-fetch links, and a reader clicking an indicator out of curiosity has just contacted the operator from their corporate IP address — telling them they are being analysed, from where, and when. `--raw-iocs` turns it off, for when you are piping into another tool that needs them literal. Think about where that output ends up.Question B.1.b. Where did the key come from, in a real engagement? Find it in this sample without being told.
Answer
python3 -B scripts/config-decrypt.py --apk /tmp/ch69/inert-sample.apk --scan-dex
B.2 — With a crib, no key¶
Now pretend ConfigVault.java was obfuscated and the key was built from a char
array, so no literal exists. You still know something: the plaintext is JSON.
# host — two known bytes
python3 -B scripts/config-decrypt.py --results 3 \
--file /tmp/ch69/blobs/cfg-xor.bin xor --crib '{"'
That will fail to produce readable output. Work out why before reading on.
Why the two-byte crib fails
Repeating-key XOR gives you `key[i % k] = plain[i] ^ cipher[i]`. Two known plaintext bytes give you **two key bytes**. The key is fourteen bytes long, so you have recovered 2/14 of it and the other twelve positions decrypt to garbage. A crib recovers a key only up to its own length. To recover a 14-byte key by cribbing you need 14 known plaintext bytes. And here the first two bytes are not even `{"` — `json.dumps(indent=2)` emits `{\n "campaign"`, so the crib is wrong as well as short.Now use a crib long enough, and correct:
# host — a 14-byte crib for a 14-byte key
python3 -B scripts/config-decrypt.py --results 1 \
--file /tmp/ch69/blobs/cfg-xor.bin xor --crib '{
"campaign"'
key : recovered len=14 'ch69-inert-xor'
score : 0.81 (printable=1.00 json_markers=2 url_markers=3)
The whole key, exactly, with no key material supplied.
Question B.2. How did you know the first field would be campaign?
Answer
You did not, and in a real engagement you would not. Two things make it tractable anyway: 1. **`sort_keys=True` is very common.** Many config generators sort. If the plaintext is sorted JSON, the first key is alphabetically first, and you can guess from a small set: `api`, `c2`, `campaign`, `config`, `domains`, `id`, `key`, `url`, `version`. 2. **You do not need the *first* field.** Crib-dragging generalises to any offset: slide the crib along the ciphertext and check for a self-consistent key. `"http` and `"https://` are excellent cribs because a config nearly always contains a URL somewhere. But the honest answer is that cribbing is a guessing game, and the next method is not.B.3 — With nothing at all¶
# host — no key, no crib, no knowledge of the plaintext
python3 -B scripts/config-decrypt.py --results 1 \
--file /tmp/ch69/blobs/cfg-xor.bin xor --recover
Measured output:
key : statistically recovered len=14 'ch69/inert-xop'
score : 0.61 (printable=1.00 json_markers=2)
entropy : 5.09 bits/byte
plaintext:
{
campaign : "CJ69-INERT/DEMO ,
"kiln_swivch": "NO/OP: vhis builf convains no gxecuvion path ,
min_battgry_pat": 15,
"next]stagg_url": "jttps8//stage2,c2-ezample.intalid-p/loader,bin",
poll]seconds"8 900.
"requkre_skm": falsg,
schema":"1,
""stage":""one
}
Twelve of the fourteen key bytes are correct. Read what you can already
see: the campaign tag, the next-stage URL, the poll interval, the require_sim
flag.
How it works¶
The method is the textbook break of a Vigenère cipher, which is what repeating-key XOR is:
- Guess a key length k.
- Split the ciphertext into k columns — bytes 0, k, 2k, … are column 0. Every byte in a column was XORed with the same key byte, so each column is a single-byte XOR problem.
- Solve each column by trying all 256 candidate bytes and keeping the one that produces the most plausible characters.
- Reassemble, decrypt the whole message, score it.
- Repeat for every k, preferring the shortest length that scores near the top — because every multiple of the true length also decrypts correctly and would otherwise tie.
Question B.3.a. Step 3 says "most plausible characters". The first version of this code scored by membership — "does this produce a printable character". Against this 441-byte blob it recovered a 15-byte key of garbage. Why?
Answer
Because most **wrong** keys still produce *some* printable text, so a binary test ties for dozens of candidates and the tie is broken arbitrarily. The fix is a frequency weighting, because real config plaintext is not uniformly distributed. The weights the tool uses: | Character class | Weight | |---|---| | space | 9 | | `"` | 7 | | lowercase a–z | 5 | | newline | 4 | | digits, tab | 3 | | uppercase A–Z | 2 | | other printable ASCII | 1 | | non-printable | −20 | Indented JSON is space-dense and quote-dense, so those two weights do most of the work. With frequency weighting the same input yields the true 14-byte key. **The general lesson: breaking a classical cipher is a statistics problem, and a binary test is not statistics.**Question B.3.b. Finish the job. Two key bytes are wrong. Fix them by hand.
Answer
Look at `"CJ69-INERT/DEMO`. The campaign tag is plainly meant to be `CH69`. `J` is `0x4A`, `H` is `0x48` — one bit apart. So the key byte at that column is off by `0x02`. Do the same for the `/` that should be `-` (`0x2F` vs `0x2D`, again `0x02` — it is the same key byte, appearing twice). The recovered key was `ch69/inert-xop`; the truth is `ch69-inert-xor`. Position 4 (`/` → `-`) and position 13 (`p` → `r`) are both off by `0x02`. Re-run and confirm:python3 -B scripts/config-decrypt.py --file /tmp/ch69/blobs/cfg-xor.bin \
xor --key 'ch69-inert-xor'
Part C — The AES blob¶
C.1 — With the key¶
# host
python3 -B scripts/config-decrypt.py --file /tmp/ch69/blobs/cfg-aes.bin \
aes --key 6b39ff0e2c7a41d5 --mode cbc --iv-prefix
You should get the full stage-two config: the gate URL, two fallbacks, three
target packages, an overlay-asset map, and a pin_sha256 of all As.
Question C.1. How did you know the IV was the first 16 bytes rather than all-zero or a separate constant?
Answer
Three converging arguments, and in a real engagement you use all three: 1. **Arithmetic.** The blob is 928 bytes. If it were pure CBC ciphertext, the plaintext would be at most 928 bytes. The plaintext is 902. 902 padded to a 16-byte boundary is 912, and 912 + 16 = 928. **The extra 16 bytes are an IV.** 2. **Convention.** Prefixing the IV is what nearly every implementation does, because the IV must be transmitted and there is nowhere else to put it. 3. **Try it.** `--auto` tries prefix, zero and supplied. It is free. Argument 1 is the one worth internalising, because it generalises: *ciphertext length minus plaintext length tells you the mode*.C.2 — The two answers that tie¶
# host
python3 -B scripts/config-decrypt.py --apk /tmp/ch69/inert-sample.apk \
--auto --quiet
assets/cfg-aes.bin 0.82 aes-cbc utf8 '6b39ff0e2c7a41d5' iv=prefix
assets/cfg-aes.bin 0.82 aes-cbc utf8 '6b39ff0e2c7a41d5' iv=zero
assets/cfg-xor.bin 0.61 xor STATISTICALLY recovered key len=14 'ch69/inert-xop'
assets/cfg-xor.bin 0.61 xor STATISTICALLY recovered key len=28 'sh69/inert!xop5h49/i~ept-x…'
assets/cfg-xor.bin 0.51 xor single 0x60
Two AES answers at the identical score of 0.82. One of them is wrong.
Question C.2.a. Which, and how do you tell?
Answer
`iv=zero` is wrong, and you tell by looking at the **first sixteen bytes**. This is CBC behaving exactly as specified. Decryption isP[i] = D(C[i]) XOR C[i-1] with C[-1] = IV
python3 -B scripts/config-decrypt.py --file /tmp/ch69/blobs/cfg-aes.bin \
aes --key 6b39ff0e2c7a41d5 --mode cbc
# no --iv-prefix, so the IV is all zeroes: watch the first line mangle
Question C.2.b. Look at the two XOR rows. len=14 and len=28 both score
0.61. Why, and which does the tool return first?
Answer
28 is a multiple of 14. A key of `KKKKKKKKKKKKKK` repeated twice decrypts identically to the same key once, so every multiple of the true key length scores the same. The tool returns the **shortest** length within 2% of the best score first, which is why `len=14` is on top. Without that rule the ordering would be arbitrary and a reader would see a 28-byte key that is really two copies of a 14-byte one. **In a report, always quote the shortest key length that works.** It is the real one.C.3 — Find the key without being told¶
# host
python3 -B scripts/config-decrypt.py --apk /tmp/ch69/inert-sample.apk --scan-dex
DEX string pool: 185 strings across all classes*.dex
key-shaped candidates: 129 (showing top 40)
rank string why
80 NativeProbe.java ascii-len-16,xor-candidate,named
68 6b39ff0e2c7a41d5 ascii-len-16,xor-candidate
68 ConfigVault.java ascii-len-16,xor-candidate
68 getSystemService ascii-len-16,xor-candidate
...
Question C.3. NativeProbe.java ranks above the real key. Is that a
bug?
Answer
No. It is the tool being honest about what it is doing. The scanner ranks **shapes**, not keys. `NativeProbe.java` is exactly 16 ASCII characters, and it additionally matches the "named" heuristic because it contains a word the regex looks for. There is no way to tell from the string alone that it is a filename rather than a key. The design consequence is `--auto`: rather than picking the top candidate, it **tries all of them under every cipher and mode** and ranks by whether the result is plausible plaintext. That is the right architecture — let the plaintext decide, not the key heuristic. The false-positive rate here is instructive: 129 candidates from a 185-string pool. On a real app with a hundred thousand strings you would raise `--top` and accept that most of what you try is noise. It costs milliseconds. **The failure mode to be alert for:** if `--auto` finds nothing, the key is not a literal. It is derived — from the package name, the signing certificate hash, `ANDROID_ID` or a build property — and no amount of string harvesting will help. Read the derivation. The tool's own "next steps" block says exactly this.Part D — Adjudication¶
You now have both plaintexts and the capability profile from lab 01. This is the half that is actually hard.
D.1 — Build the evidence table¶
Fill this in from your own output. Every row must cite where the evidence came from.
| Claim | Evidence | Source | Confidence |
|---|---|---|---|
| Can read every app's screen | canRetrieveWindowContent=true, no packageNames |
res/xml-v22/accessibility_config.xml |
Declared, not observed |
| Can synthesise input | canPerformGestures=true |
res/xml-v22/… |
Declared, not observed |
| Can read and cancel notifications | BIND_NOTIFICATION_LISTENER_SERVICE service |
manifest | Declared, not observed |
| Intends to contact three hosts | gate + two fallback URLs |
assets/cfg-aes.bin |
Config, not observed |
| Targets three specific apps | targets array |
assets/cfg-aes.bin |
Config, not observed |
| Pins a certificate | pin_sha256 |
assets/cfg-aes.bin |
Config, not observed |
| Fetches a second stage | next_stage_url |
assets/cfg-xor.bin |
Config, not observed |
| Persists across reboot | boot receiver | manifest | Declared, not observed |
| … |
Note the fourth column. Every single row says "not observed", because this was a static pass. That column is what stops a triage note becoming a fiction.
D.2 — The three sentences¶
Write these three, precisely.
- One sentence stating what the sample is capable of, if every request were granted.
- One sentence stating what you observed it do.
- One sentence stating what you cannot say.
Model answers
1. "If every request it makes were granted, the application could read the content of and synthesise input into every window on the device, read and cancel every notification, receive and read SMS, install further packages, enumerate installed applications, and restart itself after reboot, task removal and its own update." 2. "Nothing. This was a static analysis; the sample was not executed." 3. "This analysis cannot say whether any of the declared capability is exercised, whether the configured hosts were ever reachable, whether the signing key appears on other samples, or whether the sample would behave differently in an instrumented environment." Sentence 2 is the one people cannot bring themselves to write, and it is the most important of the three. "Nothing was observed because nothing was run" is a complete and defensible statement.D.3 — The over-claim exercise¶
Here are five sentences somebody wrote about this sample. Each one is wrong. Say why, and rewrite it.
- "The sample is a banking trojan."
- "C2 servers: gate.c2-example.invalid, alt1.c2-example.invalid, alt2.c2-example.invalid."
- "The sample uses a second process to escalate privileges."
- "The device-admin declaration requests no policies and is therefore harmless."
- "The configuration is encrypted, so the indicators could not be recovered."
Answers
**1.** No evidence supports "trojan" or "banking". The capability set is consistent with device-takeover fraud, and the config names three packages, but nothing observed establishes what the sample *does*. Rewrite: *"The declared capability set and the configured target list are consistent with device-takeover fraud against the three named applications. No behaviour was observed."* **2.** Three errors. The indicators are undefanged, they are stated as fact when they are a *claim about build time*, and "C2 server" asserts a role that was not observed. Rewrite: *"The configuration names three HTTPS endpoints (defanged: `hxxps://gate[.]c2-example[.]invalid/v1/beacon`, …). Whether these were ever reachable is outside the scope of this analysis."* **3.** A second process has the same UID, SELinux label, data directory and grants. Rewrite: *"One service runs in a second process, so a single process kill does not stop the application. This confers survivability, not privilege."* **4.** Uninstall resistance comes from being an **active admin at all**, not from any policy. Rewrite: *"The device-admin declaration requests no policies. an active admin resists uninstall regardless of its policy list; the empty list bounds what else the admin could do, not whether it persists."* **5.** Both blobs were recovered — one with a key harvested from the DEX, one with no key material at all. Rewrite: *"Both configuration blobs were recovered offline. `cfg-aes.bin` decrypted with a 16-byte key present as a string literal in the DEX; `cfg-xor.bin` was recovered by frequency analysis of the ciphertext alone."*D.4 — The under-claim exercise¶
Now the opposite failure. Here is a paragraph that says nothing:
The application declares several permissions and components. Some of these could potentially be used for malicious purposes, although they also have legitimate uses. The configuration files appear to be encrypted. Further analysis may be warranted.
Question. Rewrite it in under 100 words so that a reader can act on it.
Model answer
> The application declares an accessibility service requesting every event type > from every package, with window-content retrieval and gesture dispatch and no > package filter; a notification listener; SMS read and receive; and > `REQUEST_INSTALL_PACKAGES`. Two encrypted configuration assets were recovered > offline and name three target packages and four HTTPS endpoints. Persistence > is declared at four independent points. **Recommend full dynamic analysis in > an isolated environment.** No capability was observed in use; this was a > static pass. Under 100 words, every claim sourced, one clear recommendation, and one explicit limit.Part E — Adversarial thinking¶
E.1 — Make the tool fail¶
Modify the sample so that config-decrypt.py --auto finds nothing, without
using a stronger cipher.
Three ways, in increasing order of effectiveness
1. **Derive the key.** Change `ConfigVault.AES_KEY` from a literal to something computed — for example the first 16 hex characters of the SHA-256 of the package name. `--scan-dex` finds no literal, `--auto` tries 40 wrong keys, and nothing decrypts. The analyst must now *read the derivation*, which is minutes rather than seconds. 2. **Add a layer the peeler does not know.** Reverse the byte order, or interleave two blobs. The peeler handles base64, gzip and zlib; anything bespoke defeats it until somebody looks. 3. **Split the config.** Put half the key in `strings.xml` and half in the native library. Nothing about this is cryptographically stronger; it just costs a human twenty minutes. **What all three have in common:** none of them is *encryption*. They are obfuscation, and they buy time. Section 3.10's structural argument still holds — the device must decrypt with what it shipped, so the material is in the file somewhere. Rebuild after each change and re-run the tool to confirm.E.2 — Make the tool lie¶
Craft a change that makes apk-triage.py report a capability the sample does
not have, or miss one it does.
Two answers, and both are real classes of tooling bug
**Make it miss one:** add an accessibility descriptor variant under an API qualifier the tool does not enumerate — except that it enumerates all of `res/xml*`, so instead put the capability declaration in a **split APK**. The tool reads one file. Chapter 38 hit exactly this on a large real app that showed *zero* controls in `base.apk` because its code shipped in splits. The tool's own header names this limitation. **Make it over-report:** declare a service with `BIND_ACCESSIBILITY_SERVICE` and no implementation class at all, or with `android:enabled="false"`. The tool reports the declaration, which is correct as a *signal* and wrong as a *conclusion* — and this is precisely why it prints signals rather than findings. **The general lesson:** every static tool has a boundary, and the useful ones state theirs in their own output. Read the "WHAT THIS WILL NOT TELL YOU" section of any tool before you quote its results.Success criteria¶
- Recover the XOR config three ways: with the key, with a crib, and with nothing.
- Explain why a two-byte crib cannot recover a fourteen-byte key.
- Explain why frequency weighting beats a printable-character test.
- Correct the two wrong bytes in the statistically recovered key, by hand.
- Recover the AES config, and explain from the lengths why the IV is prefixed.
- Explain why
iv=prefixandiv=zerotie on score, and which sixteen bytes distinguish them. - Explain why
NativeProbe.javaoutranks the real key in--scan-dex, and why that is not a bug. - Produce the evidence table with a populated confidence column.
- Write the three sentences in D.2.
- Correct all five over-claims in D.3.
- Rewrite the under-claiming paragraph in D.4.
- Break the tool at least once, and explain what class of blindness you exploited.
Hints¶
The multi-line crib is awkward in my shell
On Windows `cmd` or PowerShell, put the crib in a file and read it, or use the statistical mode instead — `xor --recover` needs no crib at all. In Git Bash and any POSIX shell, a single-quoted string spanning lines works:python3 -B scripts/config-decrypt.py --results 1 \
--file cfg-xor.bin xor --crib '{
"campaign"'
`--results` is rejected after the subcommand
`--results`, `--threshold`, `--top` and `--max-bytes` are top-level options. Put them **before** `xor` or `aes`:python3 -B scripts/config-decrypt.py --results 1 --file x.bin xor --recover
`--recover` finds nothing on my own test blob
Frequency analysis needs enough ciphertext per column. With a *k*-byte key and *n* bytes of ciphertext, each column has *n/k* samples; below about 20 the statistics stop working. Either supply a crib, or accept a partial key and fix it by eye — which is what Part B.3.b is about.Next¶
- Lab 03 — Full triage, ending in a written analysis
- README §3.10 — the four config shapes
- 34-Cryptography — the primitives, done properly
- 40-Obfuscation — when the key is derived and you are willing to execute