← Back to logbook

Engineering & AI · · 12 min read

My grandfather's phone and the vanishing APN: reverse engineering Xiaomi firmware with AI

For two months, my grandfather's phone deleted its own mobile internet settings on every network drop. A logcat, ~1 million lines of Dalvik bytecode and an empty 8 KB APK showed the culprit was a 'self-repair' rule inside HyperOS itself.

Open laptop on a wooden table, connected by USB cable to a Xiaomi phone.
AI-generated illustration.

For two months, my grandfather's phone kept deleting its own mobile internet.

He doesn't ask much of a phone: WhatsApp, his banking app, government services, maps and family photos. But turning on Wi-Fi, going through Airplane Mode or rebooting his Redmi A3 was enough to make the settings for his regional carrier disappear, leaving him without mobile data until someone entered everything again. If all you want is to talk to your family, there's no such thing as a telephony bug. There's just the phone that stopped working again.

We swapped the SIM for a brand-new one, and nothing changed. I removed Xiaomi's telemetry and the provisioning packages, and nothing changed. So I treated the phone the way I treat a production system failing for no clear reason: I plugged it into my Mac, wrote a diagnostic prompt targeting Android's telephony and RIL layers, and let Claude investigate over adb.

The full path to the cause is below, with real logs and bytecode. The success criterion was never technical, though: it was my grandfather using his phone in peace again.

TL;DR

  • Symptom: on my grandfather's Redmi A3 running HyperOS (Android 16), the APN manually configured for a regional MVNO vanished whenever the radio reconnected: turning on Wi-Fi, toggling Airplane Mode or rebooting. This went on for two months.
  • Cause: a rule Xiaomi added to the DataProfileManager in telephony-common.jar. When an internet request finds no APN, it calls content://telephony/carriers/restore and reloads the factory table. Satellite internet requests from Google apps never find an APN, so the rule fired and wiped the user's APN. Since the carrier isn't in apns-conf.xml, nothing replaced it.
  • Fix: the rule is skipped when isInstalledCtsApps() returns true. An empty 8,538-byte APK, with no code and no permissions, whose package name contains android.telephony.cts, triggers that exception.
  • Validation: 92 satellite requests without an APN during the test, 0 restores, and the APN still present after every cycle and after a reboot.

A new phone would have solved it. I wanted to know why.


1. The symptom

ItemValue
DeviceXiaomi Redmi A3 (2024), codename blue, model 2312CRNCCL
SoC / RILMediaTek Helio G36, mtkfusionrild
SystemHyperOS V816.0.10.0.WGRMIXM, Android 16, user build (no root)
SIMRegional MVNO, MCC/MNC 724-18, registered on TIM's network (724-04)
APNsolucao.br

The pattern never changed. The APN was added in Settings and mobile data came back. Turning on Wi-Fi, toggling Airplane Mode or rebooting was enough for the APN to disappear from the list as the radio reconnected. With the same SIM, a Samsung phone worked with no configuration at all.

Before the investigation, these had already been tried without success:

  • a brand-new SIM from the same carrier;
  • every parameter combination: MVNO type (SPN/IMSI), APN type default,supl and forced roaming;
  • debloating with UAD-NG, including disabling the OMA provisioning service (com.wdstechnology.android.kryten), the most obvious suspect.

2. Method: AI in the terminal, no shortcuts

The whole investigation ran in a Claude Code session with the phone connected over USB. No reverse-engineering plugin or skill was used, only what was already installed on the Mac:

ToolUse
adblogcat, content query/insert, dumpsys, pm, cmd, pull, install
dexdump (build-tools 36.1)Disassemble the framework's classes.dex
aapt2, zipalign, apksignerBuild, align and sign the guard APK
grep, awk, strings, unzipFilter ~34k log lines and ~1M lines of bytecode

jadx, baksmali and apktool weren't installed, so the analysis was done directly on Dalvik bytecode (invoke-virtual, if-nez, const-string), with no decompiled Java. That's one of the places where AI speeds things up the most: reading bytecode register by register is slow for a human and trivial for a model, as long as every conclusion is checked against the dump.

What worked was a clear split of roles. The model proposes the hypothesis and the next command, I decide whether it makes sense, and the log or the dump confirms or kills it.


3. The evidence: the log at the moment of deletion

The logcat buffer is only 256 KB, so the log has to be saved right after the problem:

bash
adb logcat -b all -d -v threadtime,uid > logs/pre_existing.log   # 33,984 lines

The search started from the user side: the ApnEditor activity led to the URI carriers/5142, the newly created APN. With the PID of com.android.phone (1969) in hand, the DPM-0, DNC-0 and MtkDPM tags told the story:

TimeEvent
09:35:38The APN is saved (_id 5142)
09:36:03HyperOS's edit APN screen crashes (NullPointerException at ApnEditor.java:459). That's a different bug, and it deletes nothing
09:36:49CARRIER_CONFIG_CHANGED: the DPM loads solucao.br … USER_EDITED as the attach profile. The APN still exists
09:37:41Airplane Mode on; internet CONNECTED → DISCONNECTED
09:37:43.680restore apns since apn list is empty
09:37:47Update data profiles due to APN db updated. The preferred profile becomes null

The real lines:

log
11-05 09:37:42.293 radio  1969  1969 D DNC-0   : onDataNetworkDisconnected: [DataNetwork: DN-103-C, solucao.br, state=null], cause=LOST_CONNECTION(0x10004)(65540), tearDownReason=AIRPLANE_MODE_ON
11-05 09:37:43.667 radio  1969  1969 D DPM-0   : canHandleDefault(apnSetting) isCanHandleDefault=false
11-05 09:37:43.680 radio  1969  9316 D DPM-0   : restore apns since apn list is empty
11-05 09:37:47.268 radio  1969  1969 D DPM-0   : Update data profiles due to APN db updated.
11-05 09:37:47.293 radio  1969  1969 D DPM-0   : Changed preferred data profile to null

Look at the fourth column of the restore line. Every other line runs on the main thread (1969), but the restore runs on thread 9316, created on demand just for that. Someone wrote code to wipe the table on purpose, on a separate thread.

The trigger: satellite internet

Right before each restore, the log filled up with network requests no APN could satisfy:

log
D DPM-0 : Can't find any data profile that can satisfy [NetworkRequest [ REQUEST id=16, [ Transports: SATELLITE Capabilities: INTERNET&NOT_RESTRICTED&TRUSTED&NOT_VPN&NOT_VCN_MANAGED ...

Google apps (Messages, GMS, Maps) keep internet requests with a SATELLITE transport. The APN created in Settings gets infrastructure_bitmask=1, meaning cellular only, so it never satisfies those requests. What was left to find out was why "no APN for satellite" ended up as "delete every APN".

Ruled out at this point: the OMA service (kryten), com.miui.daemon, CarrierConfigLoader, carrierdefaultapp and any third-party app. The culprit lived inside com.android.phone (UID 1001, radio), in com.android.internal.telephony.data.DataProfileManager.


4. Down to the bytecode

bash
adb pull /system/framework/telephony-common.jar fw/
adb pull /system/framework/mediatek-telephony-common.jar fw/
unzip -o fw/telephony-common.jar classes.dex -d fw/x_telephony-common.jar/
dexdump -d fw/x_telephony-common.jar/classes.dex > fw/tc_dexdump.txt   # 1,033,486 lines

One attempt was dropped along the way: the boot-*.vdex files (vdex027 format) don't contain dex, so they had no useful code. The .jar files do. With strings, the anchors restore apns since apn list is empty, restoreDefaultApnsIfNeeded and canHandleDefault showed up in telephony-common, which Xiaomi modified relative to AOSP.

From those, using grep -n on the dump, seven methods were read. This is the reconstructed logic:

getDataProfileForNetworkRequest(...)

java
if (request.hasAttribute(1 /* APN-based */)) {
    apn = getApnSettingForNetworkRequest(request, networkType, ...);
    if (!"es_vodafone".equals(CUSTOMIZED_REGION)
            && !isInstalledCtsApps(context)          // ← the loophole
            && mDataNetworkController.getConfigReady()
            && apn == null
            && !mHasApnListRestored
            && request.hasCapability(12 /* NET_CAPABILITY_INTERNET */)) {
        restoreDefaultApnsIfNeeded(apn, request);
        mHasApnListRestored = true;
    }
}

restoreDefaultApnsIfNeeded(...) and the thread

java
if (!request.hasCapability(INTERNET)) return;
boolean ok = canHandleDefault(apn);   // apn != null && apn.canHandleType(TYPE_DEFAULT)
log("canHandleDefault(apnSetting) isCanHandleDefault=" + ok);
if (!ok) new DataProfileManager$4(this).start();

// DataProfileManager$4.run()
if (SubscriptionManager.isValidSubscriptionId(mPhone.getSubId())) {
    log("restore apns since apn list is empty");
    // DEFAULTAPN_URI + "subId/" + subId → TelephonyProvider deletes and reloads apns-conf.xml
}

What re-arms the latch

DataNetworkController.updateOverallInternetDataState() calls setHasApnListRestored(false) every time the set of connected internet networks changes. That's why all three reported triggers (Wi-Fi, Airplane Mode and reboot) lead to the same result: the mobile connection changes state, the latch is re-armed and the next satellite request without an APN fires the restore.

The full chain:

text
radio reconnects
  → updateOverallInternetDataState() → mHasApnListRestored = false
  → a Google app requests INTERNET over SATELLITE
  → no APN satisfies it (infrastructure_bitmask=1)  → apn == null
  → !isInstalledCtsApps() && ... → restoreDefaultApnsIfNeeded()
  → DataProfileManager$4 thread → carriers/restore/subId/4
  → apns-conf.xml has no 72418 → user APN lost

5. The loophole: isInstalledCtsApps()

The guard exists so the rule doesn't interfere with CTS (Compatibility Test Suite), Google's certification tests, which manipulate APNs on purpose. This is the actual bytecode:

text
isInstalledCtsApps:(Landroid/content/Context;)Z
0004: invoke-virtual {v3}, Landroid/content/Context;.getPackageManager:()...
0008: invoke-virtual {v3, v2}, Landroid/content/pm/PackageManager;.getInstalledPackages:(I)...
...
0026: iget-object v0, v0, Landroid/content/pm/PackageInfo;.packageName:Ljava/lang/String;
002a: const-string v1, "android.telephony.cts"
002c: invoke-virtual {v0, v1}, Ljava/lang/String;.contains:(Ljava/lang/CharSequence;)Z
0030: if-eqz v0, 0018
0032: const/4 v2, #int 1
0033: return v2

In Java:

java
for (PackageInfo p : pm.getInstalledPackages(0))
    if (p.packageName != null && p.packageName.contains("android.telephony.cts"))
        return true;
return false;

The check looks only at the package name, using contains. It doesn't verify signature, origin or permissions.

Before using the loophole: what's the blast radius?

Disabling a guard without knowing what else it protects would just trade one bug for another. So I checked:

  • the string "android.telephony.cts" appears exactly once in telephony-common;
  • isInstalledCtsApps has exactly one caller, getDataProfileForNetworkRequest;
  • mediatek-telephony-common doesn't use that string.

In other words, satisfying the check disables only this auto-restore and affects no other behavior.


6. The guard APK

xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="br.local.android.telephony.cts.apnguard"
    android:versionCode="1" android:versionName="1.0">
    <uses-sdk android:minSdkVersion="29" android:targetSdkVersion="36"/>
    <application android:hasCode="false" android:label="APN Guard"/>
</manifest>
  • No code (hasCode="false"), no permissions, no activity and no icon. It doesn't run anything: its only effect is existing.
  • The name contains android.telephony.cts, so the check now returns true.
  • The final size is 8,538 bytes, and removing it takes a single command.
bash
SDK=~/Library/Android/sdk; BT=$SDK/build-tools/36.1.0
$BT/aapt2 link -o unsigned.apk --manifest AndroidManifest.xml -I $SDK/platforms/android-36/android.jar
$BT/zipalign -f 4 unsigned.apk aligned.apk
$BT/apksigner sign --ks ~/.android/debug.keystore --ks-pass pass:android --key-pass pass:android \
  --out apnguard.apk aligned.apk
$BT/apksigner verify apnguard.apk
adb install -r apnguard.apk        # Success

Recreating the APN through the provider

With the guard installed, the APN was inserted directly into TelephonyProvider, bypassing HyperOS's buggy screen:

bash
adb shell content insert --uri content://telephony/carriers \
 --bind name:s:Solucao --bind numeric:s:72418 --bind mcc:s:724 --bind mnc:s:18 \
 --bind apn:s:solucao.br --bind type:s:default,supl \
 --bind protocol:s:IPV4V6 --bind roaming_protocol:s:IPV4V6 \
 --bind carrier_enabled:i:1 --bind edited:i:1 --bind user_visible:i:1 --bind user_editable:i:1

adb shell content insert --uri content://telephony/carriers/preferapn/subId/4 --bind apn_id:l:5142

A shell detail that cost time: the quoted query must be --where "numeric='72418'" with the whole command in quotes. Escaping with \' inside adb shell makes the query come back empty, which looks like "APN deleted" when it isn't.


7. Validation: 92 triggers, 0 restores

The test reproduces the radio cycle without touching the phone:

bash
#!/bin/zsh
# test_cycle.sh: Airplane Mode ON/OFF and a check on APN 72418
adb logcat -c -b all
adb logcat -b all -v threadtime,uid > "$LOG" &
for i in $(seq 1 $CYCLES); do
  adb shell cmd connectivity airplane-mode enable;  sleep 12
  adb shell cmd connectivity airplane-mode disable; sleep 35
  q   # content query for APN 72418
done
grep -E "restore apns since|canHandleDefault|APN db|Internet data state changed" "$LOG"
ItemBeforeAfter
SATELLITE requests without an APN (the trigger)yes92
restore apns since apn list is empty1 (APN wiped)0
canHandleDefault (restore entry point)10
APN 5142 after each cyclewipedpresent and CONNECTED
log
11-05 09:48:07.698 D DNC-0 : Internet data state changed from CONNECTED to DISCONNECTED.
11-05 09:48:21.367 D DNC-0 : Internet data state changed from DISCONNECTED to CONNECTED.
11-05 09:48:56.898 D DNC-0 : Internet data state changed from CONNECTED to DISCONNECTED.
11-05 09:49:10.377 D DNC-0 : Internet data state changed from DISCONNECTED to CONNECTED.

The trigger kept firing, with 92 satellite requests, but the rule that wiped the table never ran once. After a manual reboot, the APN was still present, preferred and connected, with 0 restore apns since lines since boot.


8. Alternatives ruled out

OptionWhy not
Managed APN (owned_by=0, DPC)Requires a Device Owner; DPC APNs are invisible unless enforced
Adding 72418 to apns-conf.xmlRequires root or a writable system partition
Changing infrastructure_bitmask to satisfy satelliteUncertain behavior: it might try satellite data when it shouldn't
A script on a computer that recreates the APNA stopgap that depends on a computer being on
Blocking the apps' satellite requestsNo ADB control without root

The guard APK was the only option that is local, minimal, reversible and rootless.


9. Risks and limits

  • It's a workaround. The real bug is the firmware treating "no APN satisfies a satellite request" as "the table is empty". Xiaomi is the one who has to fix it.
  • A HyperOS update can break the fix. If the guard changes, test_cycle.sh becomes a regression test: after each OTA, it shows within a minute whether the protection still holds.
  • Don't uninstall the guard. Without it, the APN is wiped again on the first network drop.
  • No new attack surface. The app has no code and no permissions. In the worst case, it gets ignored.

10. Back in his hands

With the APN stable, what remained was the part he actually notices. I removed the ad-ridden apps, gave the power button back its classic Power Off / Restart menu and left on the phone what he uses: WhatsApp, banking and government apps, maps and family photos.

None of those changes show up in a dump. But they're the reason the investigation existed.


11. Takeaways

  1. Save the log right away. With a 256 KB buffer, the evidence lasts minutes.
  2. The thread tells the story. A single line outside the main thread pointed to the code acting on purpose.
  3. AI to read bytecode, a human to decide. The model read raw Dalvik with no decompiler and proposed the causal chain; every link was confirmed in the dump or the log before becoming a conclusion.
  4. Measure the blast radius before using a loophole. One occurrence of the string and one caller: that alone is what makes the fix safe.
  5. The smallest fix that works. 8,538 bytes, no permissions, one command to undo.

AI fluency isn't about generating boilerplate. It's knowing how to frame a systems-level problem so an agent can disassemble Dalvik bytecode with you, checking every conclusion, and shipping an 8 KB patch so your grandfather can use his phone in peace.


Tools: Claude Code, adb, dexdump, aapt2, zipalign, apksigner. Device: Redmi A3, HyperOS / Android 16.