Lab 04 — CTF: the quiet sample¶
Difficulty: Advanced Time: 3–6 hours Prerequisites: Labs 01, 02, 03; README §3 and §8
SAFETY. Everything in this challenge is inert. The two artefacts in
ctf-artefacts/are base64 text files, not executables and not APKs — you can open them in a text editor and nothing will happen. Their plaintexts name only RFC 2606.invalidhosts andcom.example.invalid.*packages, none of which exist or can exist. Nothing in this lab is installed or executed on any device.
The scenario¶
You are the on-call analyst. At 16:50 on a Friday you receive this, and nothing else:
"Fraud flagged an account takeover on a customer's Android phone. The customer says they installed a 'battery optimiser' from a link in an SMS about a parcel delivery. The phone has been wiped and reset — I know, I know. All we recovered before the reset was the attached triage output and two files from the app's assets directory. Anything you can tell me by Monday. The fraud team wants to know if this is the same thing we saw in March."
— attached:
triage-excerpt.txt(below),challenge-01.b64,challenge-02.b64
You have no sample, no device, no network capture and no corpus. You have a partial triage report and two encrypted blobs.
This is a realistic situation and it is the one this whole chapter is aimed at: the file is gone, the device is gone, and somebody needs an answer anyway.
Scoring¶
| Part | Points | What it is |
|---|---|---|
| A | 20 | Recover stage 1 |
| B | 25 | Recover stage 2 and capture the flag |
| C | 25 | Answer six questions from the triage excerpt alone |
| D | 20 | Find the contradiction the excerpt contains |
| E | 10 | Write the Monday email |
| Total | 100 |
Flag format: CH69{...}
A pass is 70. Full marks require Part D, which nobody gets on the first read.
The evidence¶
triage-excerpt.txt¶
This is what your colleague managed to run before the phone was wiped. It has been trimmed; some sections are missing entirely.
==============================================================================
1. IDENTITY -- what is this file
==============================================================================
file batteryopt.apk
size 4.7 MiB (4928512 bytes)
sha256 <redacted by submitter>
zip entries 271
package com.quietsample.batteryopt
version code=17 name=2.4.1
sdk min=21 target=31
application name=com.quietsample.batteryopt.App, allowBackup=true,
extractNativeLibs=true, usesCleartextTraffic=false
dex classes.dex 118.4 KiB v035 241 classes, 1907 methods,
3844 strings
code fraction 2.5% of the file is DEX
==============================================================================
2. PROVENANCE
==============================================================================
scheme APK Signature Scheme v2 0x7109871a
scheme JAR signing (v1) v1
certificate APK Signature Scheme v2
subject CN=Android Debug, O=Android, C=US
issuer CN=Android Debug, O=Android, C=US
validity 230114091200Z .. 530106091200Z
sha256 <redacted by submitter>
==============================================================================
3. CAPABILITY -- what it could do if every request were granted
==============================================================================
weight permission capability
[***] BIND_ACCESSIBILITY_SERVICE accessibility
[***] SYSTEM_ALERT_WINDOW overlay
[***] RECEIVE_SMS receive SMS in the background
[** ] QUERY_ALL_PACKAGES enumerate every installed app
[** ] PACKAGE_USAGE_STATS app usage statistics
[** ] REQUEST_IGNORE_BATTERY_OPTIMIZATIONS battery exemption
[** ] RECEIVE_BOOT_COMPLETED start at boot
[* ] FOREGROUND_SERVICE long-running foreground service
[* ] INTERNET network
COMPONENT DECLARATIONS
[***] accessibility service com.quietsample.batteryopt.a.b.C
CAPABILITY DESCRIPTORS found in res/xml
res/xml/aq.xml <accessibility-service>
accessibilityEventTypes 0x800020
canRetrieveWindowContent true
packageNames com.quietsample.batteryopt
res/xml-v24/aq.xml <accessibility-service>
accessibilityEventTypes 0xffffffff
canPerformGestures true
canRetrieveWindowContent true
packageNames ABSENT -- every package
==============================================================================
4. PERSISTENCE
==============================================================================
[** ] ContentProvider com.quietsample.batteryopt.InitProvider
authorities=com.quietsample.batteryopt.init initOrder=1000 exported=false
[** ] boot receiver com.quietsample.batteryopt.R1
BOOT_COMPLETED, MY_PACKAGE_REPLACED
[** ] foreground service com.quietsample.batteryopt.S1
type=dataSync stopWithTask=false
[** ] multi-process :core, :watch
2 extra process name(s)
[** ] activity-alias com.quietsample.batteryopt.Alias
enabled=true
==============================================================================
5. NATIVE
==============================================================================
lib/arm64-v8a/libjiagu.so 1.9 MiB
ELF64 aarch64 entropy 7.81 stripped
DT_INIT=True DT_INIT_ARRAY=True DT_NEEDED=7
JNI_OnLoad=True Java_* symbols=0 RegisterNatives=True
lib/armeabi-v7a/libjiagu.so 1.6 MiB
ELF32 arm (32-bit) entropy 7.79 stripped
DT_INIT=True DT_INIT_ARRAY=True DT_NEEDED=7
JNI_OnLoad=True Java_* symbols=0 RegisterNatives=True
==============================================================================
6. LOADING
==============================================================================
assets/challenge-01.b64 608 B H=6.25 ratio=0.75
assets/challenge-02.b64 673 B H=6.01 ratio=0.76
assets/dat.png 2314880 B H=7.99 ratio=1.00
assets/icon_cache.dat 118272 B H=7.98 ratio=1.00
==============================================================================
7. STRING-POOL MARKERS -- 3844 strings across all DEX files
==============================================================================
LOADING
dalvik.system.DexClassLoader DEX loaded from a file
java.lang.reflect.Method reflection
NATIVE
System.loadLibrary native library load
The two blobs¶
Part A — Recover stage 1 (20 points)¶
You have no key and no source.
# host
cd 69-MalwareAnalysis
python3 -B scripts/config-decrypt.py --file labs/ctf-artefacts/challenge-01.b64 --auto
A.1 (5 pts). What layers wrap the ciphertext, and in what order? Quote the tool's own answer and explain how you would have found each by hand.
A.2 (10 pts). Recover the plaintext. State the cipher and the exact key.
A.3 (5 pts). The tool also offers a second, longer key that scores nearly as well. Explain the relationship between the two, and say which you would quote in a report.
Part A solution
**A.1** `base64 -> gzip`. By hand: - The file is printable ASCII from the base64 alphabet with no other characters, so try base64 first. - The decoded bytes begin `1f 8b`, which is the gzip magic. Decompress. - What remains is high-entropy binary. **A.2** Repeating-key XOR, key `quiet-sample` (12 bytes), recovered by frequency analysis **with no key material at all**:key : xor STATISTICALLY recovered key len=12 'quiet-sample'
score : 0.73 (printable=1.00 json_markers=1 url_markers=3)
layers : base64 -> gzip
{
"artefact": "CH69 CTF stage 1",
"campaign": "QUIET-SAMPLE",
"next_artefact": "challenge-02.b64",
"next_cipher": "AES-128-CBC, PKCS#7, IV = first 16 bytes of the decoded blob",
"next_key_rule": "lowercase hex sha256 of the exact ASCII string CH69-QUIET, first 16 characters, used directly as 16 key bytes",
"note": "INERT CTF ARTEFACT. Nothing here executes. All names are RFC 2606 .invalid.",
"poll_seconds": 600,
"sinkhole": "https://gate.quiet-sample.invalid/v1/poll"
}
Part B — Recover stage 2 and capture the flag (25 points)¶
Stage 1 told you the rule. It did not give you the key.
B.1 (10 pts). Derive the key. Show the command.
B.2 (10 pts). Decrypt stage 2. Quote the flag.
B.3 (5 pts). Stage 1 said the IV is the first 16 bytes. Prove it from the lengths, without trying it.
Part B solution
**B.1**# host
python3 -B -c "import hashlib; print(hashlib.sha256(b'CH69-QUIET').hexdigest()[:16])"
# 53c3a790755bd7ae
python3 -B scripts/config-decrypt.py --file labs/ctf-artefacts/challenge-02.b64 \
aes --key 53c3a790755bd7ae --mode cbc --iv-prefix
{
"artefact": "CH69 CTF stage 2",
"capabilities_claimed": ["accessibility", "notification_listener", "overlay"],
"flag": "CH69{n0_expl01t_ju5t_c0nsent}",
"note": "INERT CTF ARTEFACT. No payload, no C2, no capability. Every host is .invalid.",
"targets": [
"com.example.invalid.bank.delta",
"com.example.invalid.wallet.epsilon"
]
}
Part C — Six questions from the excerpt (25 points)¶
No blobs needed. Everything below is answerable from triage-excerpt.txt.
C.1 (4 pts). The code fraction is 2.5%. What is the sample, structurally,
and what does that tell you about the value of decompiling classes.dex?
C.2 (4 pts). The accessibility descriptor appears twice, with different attributes. Which one governs on the customer's phone, and what would an analyst who read only the first one have concluded?
C.3 (4 pts). Java_* symbols=0 with RegisterNatives=True. State exactly
what is missing from the file and how you would recover it.
C.4 (4 pts). The certificate is CN=Android Debug, O=Android, C=US. Your
colleague wants to know whether this is "the same thing we saw in March". What
do you tell them about pivoting on this signer?
C.5 (4 pts). assets/dat.png is 2.3 MB with entropy 7.99 and a compression
ratio of 1.00. Give three explanations, ranked, and say what would distinguish
them.
C.6 (5 pts). The excerpt has no section for SMS reading, notification access or device admin, and the fraud was an account takeover involving a one-time code. Reconcile that.
Part C solutions
**C.1** A 118 KB DEX inside a 4.7 MB file is the **packer stub** shape — chapter 40 §3.7 puts a stub at 20–150 KB against a multi-megabyte app. Combined with `libjiagu.so` (a named commercial packer) and two incompressible multi-megabyte assets, that is three of the four packer indicators, and **any two together is conclusive**. Decompiling `classes.dex` will show you the stub's loader and essentially nothing else. The value is in identifying the product and then finding the published unpacking method — chapter 40 records that the second analyst spends hours where the first spent weeks. **Full marks also for noting:** `application android:name=…App` will resolve to a class that forwards lifecycle callbacks to the *real* Application after swapping `LoadedApk.mClassLoader` by reflection. **C.2** The `-v24` variant, because the phone was running something newer than API 24 (the sample targets 31 and the fraud is recent). The base `res/xml/aq.xml` variant restricts `packageNames` to the app's **own package** and subscribes to two event types. Read alone, it is an almost innocuous declaration — a self-monitoring service. The `-v24` variant has `typeAllMask`, `canPerformGestures=true` and **no `packageNames` at all**. An analyst reading only `res/xml/` would have concluded that the accessibility service was scoped and passive, which is the opposite of the truth. **This is a deliberate evasion of exactly that reading**, and it is the same mechanism the chapter's own inert sample produced by accident. **C.3** The **Java-to-native mapping**. With zero `Java_*` exports, no method name in the DEX can be resolved to a function in the library by `dlsym`; the binding happens inside `JNI_OnLoad` via `RegisterNatives`, and the C functions can be `static` and absent from every symbol table. Recovery: hook `art::JNI::RegisterNatives` at runtime ([`52-StaticAnalysis/scripts/blindspot-recorder.js`](../../52-StaticAnalysis/scripts/blindspot-recorder.js)), or read the `JNINativeMethod` table out of `JNI_OnLoad` in a disassembler (chapter 57). **Also worth a mark:** `DT_INIT=True` **and** `DT_INIT_ARRAY=True`, on a stripped 1.9 MB library with entropy 7.81. Constructors run before `dlopen` returns, so you must spawn-gate. Attaching has already lost. **C.4** **Tell them it establishes nothing.** `CN=Android Debug, O=Android, C=US` is the default debug certificate that the Android SDK generates. It is on an enormous number of unrelated APKs — every debug build anybody has ever sideloaded. Two samples sharing it are not linked in any useful sense. Pivot on the `classes.dex` hash, on the packer version, on the capability vector, or on infrastructure — not on this signer. **Bonus mark for noticing:** a debug certificate also means the sample was **never distributed through Play**, which corroborates the SMS-link sideload story. **C.5** Ranked: 1. **The packed payload.** 2.3 MB is the right size for the real DEX of a 4.7 MB app, and `libjiagu` needs somewhere to keep it. `.png` with no PNG magic is the classic disguise, and chapter 40's rule is **check entropy, not extension**. 2. **Genuine media.** A large PNG or JPEG is also incompressible. 3. **A nested archive.** Distinguishing them costs one command — read the first eight bytes:python3 -B -c "
import zipfile,binascii
z=zipfile.ZipFile('batteryopt.apk')
print(binascii.hexlify(z.read('assets/dat.png')[:8]))"
Part D — The contradiction (20 points)¶
The excerpt contains an internal inconsistency. Something in it cannot be true alongside something else in it.
D.1 (12 pts). Find it. D.2 (8 pts). Say what the most likely explanation is, and what one command would settle it.
Part D solution
**D.1 The inconsistency is between section 3 and section 7.** Section 3 reports `BIND_ACCESSIBILITY_SERVICE` in the **permission** list, and declares an accessibility service at `com.quietsample.batteryopt.a.b.C`. Section 7 — the string-pool markers — reports only three markers across 3,844 strings: `DexClassLoader`, `java.lang.reflect.Method` and `System.loadLibrary`. **Not one capability marker.** No `AccessibilityNodeInfo`, no `performGlobalAction`, no `dispatchGesture`, no `TYPE_APPLICATION_OVERLAY`, no `UsageStatsManager` — despite the manifest declaring an accessibility service and requesting `SYSTEM_ALERT_WINDOW` and `PACKAGE_USAGE_STATS`. A class that extends `AccessibilityService` and does anything at all must reference `AccessibilityEvent` and `AccessibilityNodeInfo`. Those references would be in the string pool as type descriptors. **A second, subtler one, worth partial credit:** the manifest requests `BIND_ACCESSIBILITY_SERVICE` as a `python3 -B -c "
import zipfile, binascii
print(binascii.hexlify(zipfile.ZipFile('batteryopt.apk').read('assets/dat.png')[:8]))"
Part E — The Monday email (10 points)¶
Write the reply. Maximum 200 words. It must:
- answer the question that was actually asked ("is this the same thing we saw in March?")
- state what you established, with sources
- state what you could not establish
- give exactly one recommendation
Model answer
> **Re: batteryopt.apk** > > **Short answer: I cannot tell you whether it is the March sample, and the > signer will not help.** The certificate is `CN=Android Debug` — the SDK's > default debug key, shared by an enormous number of unrelated APKs. It also > confirms the app never came through Play, which fits the SMS-link story. > > **What the artefacts establish.** The app is packed with a commercial > protector (`libjiagu.so`); the 118 KB `classes.dex` is a stub and the real > code is in `assets/dat.png` (2.3 MB, incompressible). Its accessibility > descriptor has **two variants**: the base one is scoped to the app's own > package, and the API 24+ one requests every event type from every app with > gesture dispatch and window-content retrieval. The API 24+ one is what ran. > That capability reads one-time codes off the screen with no SMS permission > required. > > The two recovered config blobs name two target packages and one endpoint > (`hxxps://gate[.]quiet-sample[.]invalid/v1/poll`), and a campaign tag, > `QUIET-SAMPLE` — **that tag is the thing to check against March**, not the > certificate. > > **What I could not establish.** Whether any capability was exercised; whether > the endpoint was ever live; the sample's hash (redacted in what I received). > > **Recommendation:** retrieve `batteryopt.apk` itself and unpack it in an > isolated environment. Everything above is from a trimmed report and two > assets. Note what the model does **not** do: it does not name a family, it does not call anything a "banking trojan", and it does not say "sophisticated". It answers the question, sources every claim, and asks for the one thing that would actually move the analysis forward.Scoring your run¶
| Score | Reading |
|---|---|
| 90–100 | You found the contradiction unprompted and your email would survive a review |
| 70–89 | Solid analyst work; re-read Part D, it is the difference |
| 50–69 | You can drive the tools; the judgement needs lab 03 again |
| below 50 | Work through labs 01–03 before retrying |
Instructor notes¶
How the artefacts were made, and how to make more
Both blobs were generated with this chapter's own tooling, so a reader can reproduce and extend the challenge:# host — python3 -B
import base64, gzip, hashlib, json
ns = {"__name__": "x", "__file__": "scripts/config-decrypt.py"}
exec(compile(open("scripts/config-decrypt.py", encoding="utf-8").read(), "s", "exec"), ns)
# stage 1: json -> repeating XOR -> gzip -> base64
p1 = json.dumps({...}, indent=2, sort_keys=True).encode()
c1 = base64.b64encode(gzip.compress(ns["xor_bytes"](p1, b"quiet-sample"), mtime=0))
# stage 2: json -> AES-128-CBC with a derived key -> IV prefix -> base64
key = hashlib.sha256(b"CH69-QUIET").hexdigest()[:16].encode()
iv = bytes(range(16, 32))
p2 = json.dumps({...}, indent=2, sort_keys=True).encode()
c2 = base64.b64encode(iv + ns["aes_encrypt"](p2, key, "cbc", iv))
Next¶
- README §13 — the summary and quick-revision set
../examples/triage-writeup-inert-sample.md— the model write-up- 40-Obfuscation lab 04 — build a packer, then defeat it by dumping the DEX from memory. The natural next step after Part D
- 15-Native-Code lab 05
— when the answer is in the
.so