project · android · nfc
NFC Explorer — what is actually on a hotel key card
A developer-grade NFC inspection tool for Android — closer to adb than to a consumer tag app. It started as one question about a card I brought home from a hotel, and the answer turned out to be a single byte of OR-ed silicon.
I kept a key card after a stay, the way you do, and pressed it against my phone. Every app I tried said some version of nothing here. NFC Tools found no tag data. Android's own formatter refused. The card plainly worked on a door two days earlier, so the absence was clearly in the reader and not in the card.
Two questions, then. What is actually on it, and why does everything refuse to read it? Both turned out to need a tool that reports bytes rather than interpreting them, so that is what this became — a memory explorer, a lock-bit decoder, a guarded writer, and an exporter, generalised from the one card that prompted it.
The dump, and the byte that explains everything
The card is a MIFARE Ultralight: 16 pages of 4 bytes, 64 bytes in total, of which pages 04–0F are user data. Reading it needs reader mode with FLAG_READER_SKIP_NDEF_CHECK, because the platform's NDEF probe is precisely the thing that finds nothing here and gets in the way.
PAGE HEX ASCII ACCESS
00 04 0E 66 E4 ··f· hardware read only SN0 SN1 SN2 BCC0
01 A2 F0 7B 81 ··{· hardware read only SN3..SN6
02 A8 48 00 00 ·H·· lock control BCC1, LOCK0=00, LOCK1=00
03 46 0D AE 11 F··· otp one way <-- NOT an NDEF capability container
04 E2 42 1B 5E ·B·^ writable
05 36 56 3A 96 6V:· writable
06 CA C7 C4 88 ···· writable
07 C2 BD D7 19 ···· writable
08 67 03 03 FC g··· writable
09 4D D4 BF 32 M··2 writable
0A–0F 00 00 00 00 ···· writable
Three findings, in ascending order of interest.
The card is not locked. At all. LOCK0 and LOCK1 are both 0x00: no lock bit set, no block-locking bit set, every user page still writable, and the lock bits themselves still free to change. The obvious hypothesis — the hotel locked the tag — is simply false.
There is no NDEF capability container. An NDEF-formatted Type 2 tag carries its CC in page 03: E1 10 06 00 — magic E1, version 1.0, 48 bytes, read/write. This card holds 46 0D AE 11 there. No CC, so no NDEF, so nothing whatsoever for an NDEF-oriented reader to show you. Every app that reported an empty card was telling the truth about the only thing it knew how to look for.
And then the part I actually enjoyed, which is why formatting fails too. The capability container has to live in page 03, and page 03 is OTP — one-time programmable. Its bits are OR-ed on write: they can be set, never cleared. So writing a valid CC over what is already there does not replace it. It merges with it:
46 0D AE 11 what the issuer wrote
| E1 10 06 00 the NDEF capability container
= E7 1D AE 11 magic byte E7, not E1 — invalid, and irreversible
The result is not a formatted tag. It is a permanently corrupted OTP page with a magic byte that means nothing, and there is no command, key or factory reset that walks it back. Android will not do that, and is right not to. This card can never be NDEF-formatted by any app on any phone — that is a property of the silicon combined with what the issuer wrote, not a limitation of the tool you happened to try.
The remaining 24 bytes in pages 04–09 are high-entropy with no ASCII, no TLV structure and no repetition — consistent with an encrypted or MAC'd credential validated against a door controller, rather than a plaintext room number. Which answers the practical question: the card cannot be reused as a room key, because the UID is fixed in silicon and the credential is checked elsewhere. It can be reused as a raw data tag, since pages 04–0F are wide open — as long as you accept that it will never speak NDEF, and that overwriting pages 04–09 destroys the room credential for good.
Both check bytes validate — BCC0 stored E4 computed E4, BCC1 stored A8 computed A8 — which is what makes the dump evidence rather than an anecdote. The UID from anticollision agrees with the UID stored in the pages, so this is a clean read, not a partial or corrupted one.
Absence is never rendered as a zero
That dump is only worth anything if every line in it is true, which turns out to be a design constraint rather than a coding one. Four invariants, each with tests attached:
- An unread page is not a page of zeros. Unread bytes are
null, so they cannot be printed as00 00 00 00— indistinguishable from a page that genuinely holds zeros. The JSON export emits"hex": null; the text export emits??. On this card, pages0A–0Freally are zeros, and that claim only means something because the tool is incapable of saying it by accident. - Partial results are first class. A tag pulled away mid-dump produces a report, not an error. The stride that was in flight is
TAG_LOST— it was attempted; everything after it isNOT_ATTEMPTED— it never was. Those are different facts and they are stored as different facts. - Unconfirmed is stated, not rounded off. Android reports
TYPE_ULTRALIGHTfor MF0ICU1, Ultralight EV1 and every NTAG21x alike, so chip geometry reports a safe floor withgeometryConfirmed = falserather than naming a chip that ATQA and SAK cannot distinguish. NXP's own TagInfo said MF0ICU1 and is almost certainly right; this tool still will not assert it without aGET_VERSIONprobe. - Colour never carries a verdict alone. Every access verdict is also stated in words, because a red cell is not a diagnosis.
There is no NFC in the Android emulator
This one fact shapes the entire architecture, so it is worth stating plainly: no emulator can present a tag. There is no shadow, no mock, no host-side substitute. Worse, the framework classes are terminal — android.nfc.Tag and MifareUltralight are final, constructed by the platform from a binder parcel, and offer no seam at all.
So the naive design, where decoders call MifareUltralight directly, makes every correctness claim in the app depend on a physical card being physically present. Bit-level logic would be "verified" by holding a tag against a phone and reading the screen. That is a demonstration, not a test: it cannot run in CI, cannot cover a fully-locked tag without permanently locking a real one, and cannot reproduce a mid-read tag loss on demand.
All tag I/O therefore sits behind domain/transport/TagTransport, and the suite drives a FakeUltralightTransport. The load-bearing decision is not that the fake exists — it is that the fake enforces the chip's real semantics rather than permitting everything: READ wraps past the last page, UID pages reject writes, lock and OTP bytes are OR-ed so bits set but never clear, and a locked page NAKs. A permissive stub would let every test pass while real hardware failed, which is exactly the failure mode the seam exists to prevent.
Two details make it hold. The transport defines its own exception types, because the read pipeline must distinguish "the tag left the field" from "the tag refused" to assign per-page status, and it cannot import android.nfc.TagLostException to do it. And the fake and the decoder derive lock state independently, so the lock tests cross-check two separate implementations against each other rather than one implementation against its own assumptions.
The rule is enforced by the build, not by discipline:
fails the build on any android.* or androidx.* import under domain/
— and tests its own detector, so it cannot pass vacuously
That last clause matters more than it looks. A purity checker that silently stops checking is worse than no checker, because it reads as a guarantee. Injecting an android import is part of the suite, and the detector has to notice.
I did consider Robolectric. It ships no meaningful NFC shadow, so using it would mean writing the same fake anyway, plus a heavyweight test runtime, plus the pretence of testing the framework. Strictly worse. Instrumented tests were kept as a complement for the I/O path, never as a substitute — they need a physical tag per run and cannot cover destructive states without destroying tags.
Writes that cannot be undone
00–01 hold the UID and are never writable. Page 02 holds lock bytes whose bits are OR-ed, and a block-locking bit permanently freezes whether a page is lockable at all. Page 03 is OTP, also OR-ed, and writing it is what makes a tag permanently un-NDEF-formattable — as the arithmetic above shows.
An app that can do that needs its safety to be the most boring, most exhaustively tested thing in the codebase. So WriteGuard is a pure function of page index, lock state and expert mode — no I/O, no clock, no configuration — and the payload is checked for width only, so no caller can smuggle a different outcome through the bytes. That makes every branch exhaustively testable, and the tests sweep all pages × lock states × expert mode rather than sampling them.
Two rules hold unconditionally, and they are the interesting ones:
- Expert mode can only turn
RequiresExpertModeintoAllowed. It never touches aBlocked. There is no flag anywhere that unlocks the UID pages, because there is no state of the world in which writing them is possible. - An unknown lock state is never writable. If page
02could not be read, everything is refused — user pages included. Guessing would either invite a write that silently fails or one that unexpectedly succeeds, and setting lock bits from an unknown starting state could permanently close pages the app never even managed to read.
Around that pure core, four procedural rules that exist because the guard being correct is not the same as the write being safe:
- Lock state is re-read from the tag inside the write session, never carried over from an earlier scan, which could be stale.
- Every write is followed by a read-back. Success is demonstrated, not assumed — and on OTP or lock pages a write can legitimately succeed while storing something different, which the result reports rather than hides. That is the OR-ing again, and it is the one case where "the write succeeded" and "the bytes you asked for are on the card" are not the same sentence.
- Writing requires arm-then-tap. Arming is the confirmation step, because a tag is only in range for a moment and a dialog cannot be answered with a card held to the back of a phone. The exact bytes are shown before arming, and any edit to the payload or range disarms.
- Expert mode resets to off on every launch and is never persisted. A dangerous mode you enabled last Tuesday should not still be on.
One more thing the risk model gets right: the acknowledged risk travels with the approval, so enabling expert mode does not make the danger invisible — the UI keeps warning even once the write is permitted.
The device proof was deliberately taken on a second card from the same provider, so that a mistake could not destroy the read evidence. It wrote the text shivam to pages 04–05, read it back byte-for-byte, and left pages 00–03 untouched: no lock bit set, no OTP bit set, expert mode never enabled. The zero padding in page 05 is correct rather than a bug — a page is the smallest writable unit, so a six-byte payload necessarily occupies eight.
A card that can never hold NDEF, doing useful work
Here is the pleasing consequence of everything above. Two unlocked cards that can never be NDEF-formatted are, from any normal app's point of view, junk. But an action does not need to be stored on the tag — it only needs the tag's UID, which every card broadcasts to every reader for free.
So: assign an action to a UID, tap the card with the app closed, and the phone does the thing. Launch an app, open a URI or deep link, send an explicit intent, a media command, a WhatsApp message, a Toggl timer. No NDEF, no writing to the card at all, and — worth noting — no new runtime permission. Listing installed apps for the picker uses a <queries> manifest declaration, which is a visibility declaration rather than the restricted QUERY_ALL_PACKAGES.
Android has no background NFC listener, so the only way to run code on a tap is an exported activity with an NFC intent filter, which then finishes without drawing anything. That sentence contains the whole security problem, and it took three passes to get right.
The guard that was a tautology
An exported activity that executes stored intents is an attack surface, and I knew that when I wrote it. TagActionDispatch.shouldAct took three conditions described as "necessary, none sufficient", and the suite swept all eight combinations. It looked thorough. At the only call site, the activity did this:
val uid = tag?.id?.let(ByteBlock::copyOf)
if (uid == null) { finish(); return }
...
shouldAct(intentAction = intent?.action, hasTagExtra = true, assignment = assignment)
hasTagExtra = true restates the null check three lines above it. It can never be false. So of three conditions only two could ever vary in production, and the exhaustive sweep gave me full confidence over a parameter carrying no information whatsoever. The KDoc called it "the part a hostile caller cannot fake". The KDoc was wrong.
Not theoretically wrong, either. From an ordinary third-party uid:
$ adb shell am start -n dev.shivam.nfcexplorer/.TagActionActivity \
-a android.nfc.action.TECH_DISCOVERED
ActivityTaskManager: START u0 {act=android.nfc.action.TECH_DISCOVERED
cmp=dev.shivam.nfcexplorer/.TagActionActivity} with LAUNCH_MULTIPLE
from uid 2000 (com.android.shell) result code=0
W/NfcExplorer: [4] trigger: trigger invoked without a tag; ignoring
The activity started, from a caller that is not the NFC stack, with a copied action string. The only thing that stopped it was the absence of a Tag — and android.nfc.Tag is a Parcelable with a public CREATOR, so a caller can construct one carrying any UID it likes. The guard reduced to does the caller know a UID the user configured?, and a UID is shouted in the clear by every tag to every reader.
The fix is to find the one signal in that intent which cannot be forged in software. TagPresence.check opens a connection and reports whether the tag answered. The handle inside a Tag is issued by the NFC service for a live discovery session; a handle that was never issued is not in that table, so a forged parcel cannot be connected to. You can fake the description of a tag. You cannot fake a tag that replies.
Fixing the instance is not the same as removing the class, so two supporting changes. shouldAct now takes a TagPresence.Answer rather than a Boolean — true no longer compiles there, and a hand-written Answer.Live is a visible claim rather than a plausible-looking flag. That matters specifically because the activity has no unit test, so nothing else would catch the regression. And the answer carries the cause of a refusal, because the trigger has no UI: a tap that silently does nothing must be explainable from the log afterwards, and "left the field" points somewhere completely different from "speaks no technology this app can open".
What is still open, deliberately: a cloned UID passes. A clone is a genuinely live tag and presence cannot tell it from the original. That is inherent to identifying tags by UID — the same property MacroDroid and Tasker rely on — and is not fixable at this layer. The bound on the damage is the honest part: an attacker can only replay an action the user configured themselves. They cannot introduce a new one.
The cost is a connection attempt on every tap, including taps that do nothing, and a card whipped away in the same instant it was discovered will fail it. Accepted, because the failure mode is "nothing happened", it is logged with a cause, and a second tap fixes it — whereas the alternative is a guard that cannot tell a tap from a hostile intent. Device evidence later settled the open question: no refusals on ordinary taps, so the check is affordable and the trade stands.
The crash that had been waiting since the file was written
The presence check immediately exposed something else. First real tap of an assigned tag in the field: a buzz, then "NFC Explorer keeps stopping".
java.lang.IllegalStateException: Activity {…TagActionActivity}
did not call finish() prior to onResume() completing
at android.app.Activity.performResume(Activity.java:9516)
Theme.NoDisplay is not merely "draw nothing". It is a contract that finish() happens before onResume() returns, and the platform enforces it by throwing. The trigger has to read the assignment store before it knows whether to act, which suspends, so finish() always landed after onResume.
That was latent from the moment the activity was written. The presence check did not cause it — it widened the pre-suspension window enough to make it fire every single time. The reason it went unseen is the interesting bit: every test of this activity had used a launch with no tag, which returns and finishes synchronously. The one path that satisfies the contract was the only path anyone had exercised. The fix is a translucent theme instead: same invisibility, no such contract. Verified by launching the trigger over the app drawer and watching the drawer stay fully visible — Displayed … +243ms, no frame, empty crash buffer.
The tag exchange also moved to Dispatchers.IO, which it should have been regardless of the crash. A blocking NFC exchange on the main thread is wrong even when it works.
Driving an app that has no automation API
The action I actually wanted was tap the card on the nightstand, start sleep tracking. Sleep Cycle publishes no automation API: no documented intent, no URL scheme, no Tasker plugin, no Assistant action. So this became an exercise in reading an APK and writing down what is genuinely reachable — including, importantly, the routes that look promising and are not.
Starting is easy once you find it: an exported activity, no permission, action com.northcube.sleepcycle.STARTUP_ALARM. Any app may launch it, and it starts a real session — foreground service up, ongoing notification showing — and it works with the phone locked.
Knowing whether a session is running has exactly one trustworthy source, the ongoing notification, and one trap. Match on the channel id, never the notification text: channel ids are chosen by developers and never translated, while "Analysis in progress" only matches on an English phone. And it must be read live rather than remembered, because Sleep Cycle ends the session itself each morning when the alarm fires — after which any flag the automation stored still says "running" and the toggle is inverted from then on. A remembered boolean drifts within a day.
Stopping has no intent at all, and the four routes that ought to work do not:
| Route | Result |
|---|---|
ACTION_STOP_ALARM to the sleep service | Silences a ringing alarm only. Session keeps running. |
Firing STARTUP_ALARM again | No toggle. Opens the live sleep screen. |
| Notification action buttons | There are none — only a content intent. |
| Forging the wear "session end" message | Rejected silently. |
The wear route is worth spelling out because it looks like the answer. ConnectedWearService is exported with no permission, and the app clearly has a clean session-stop path behind it. Sending that message locally produces no app-side log at all: WearableListenerService verifies the caller is Google Play Services and drops everything else before the app's own code runs. There is no way through it from an ordinary uid.
Which leaves the slider on the sleep screen, and a gesture. Two things were established the hard way. A smooth swipe does not work — an interpolated input swipe was tried repeatedly and the session kept running; what works is a press that dwells and then moves in discrete increments, the shape of a real finger. And the travel must be long: a stepped drag ending a third of the way up did nothing, and the same drag continued to roughly a third of the display height ended the session. Hence a preset storing screen ratios rather than pixels.
Also: a drag is blind. It lands on whatever is frontmost. During this investigation an unrelated app took the foreground and silently absorbed several drags aimed at Sleep Cycle, which looks exactly like the gesture not working. DragGesture.requireForegroundPackage exists because of that hour.
The part I would defend is that none of this is a Sleep Cycle code path. It is expressed in a general action vocabulary, and Sleep Cycle is a preset composed from it:
WhileNotificationShowing(com.northcube.sleepcycle, CHANNEL_SLEEP_NOTIFICATION)
├─ absent -> SendIntent(STARTUP_ALARM)
└─ showing -> Steps
├─ SendIntent(STARTUP_ALARM) raise the sleep screen
└─ DragGesture(0.5, 0.805 -> 0.5, 0.454, guarded on the package)
Any other app with a start intent and a slide-to-stop control is describable the same way without new code. The notification-reading and gesture-dispatch services both require grants the user makes by hand in system settings, and both are inert until then — the notification probe reports Unavailable rather than guessing "not running", which is the difference between a wrong answer and no answer.
Everything above was read out of one APK version and confirmed on one device. The gesture in particular can break on any update, and the doc says so.
Two integrations, and where a secret lives
A tag that starts a Toggl timer needs an API token, which is the first genuine credential in the app. It goes in EncryptedSharedPreferences under a key held in the Android Keystore — a key that never leaves secure hardware, cannot be read by this app or any other, and is destroyed on uninstall.
The comparison that makes the point is the one this app is otherwise all about: a MIFARE Ultralight page has no read authentication at all. Anything written to a tag is readable by any phone that touches the card, silently and without trace. A tag is the worst possible place for a secret, and knowing precisely why is a side effect of having built the memory explorer.
The cost is stated rather than discovered: because the key stays on the device, an encrypted token cannot be restored onto a new phone from any backup. The token is entered once per device. That is what safe costs here.
The wire protocol lives in a pure object, separate from the HTTP call, specifically so the parts that fail with an unreadable 403 get unit tests. Toggl's Basic auth is the classic trap: the token is the username and the literal string api_token is the password, not the other way round, and swapping them produces an indistinguishable authentication failure. The workspace is fetched from /me rather than typed, because the token already implies it — asking was the last thing the feature made the user look up by hand.
The WhatsApp action has the same shape of problem: wa.me links fail silently and specifically. A number carrying +, spaces or dashes opens an error page rather than a chat, and an unencoded message loses everything from the first & onward. Both are bugs that surface only on the one tag someone actually uses, so the rules are pure functions with tests rather than string handling at the call site. Auto-send also has to accept WhatsApp Business, which is a separate package with its own copy of every view id — matching only com.whatsapp meant the chat opened, the message sat there, and nothing was pressed. Send is found by view id first because ids are never translated, with the accessibility label as fallback, because that label is English and matches nothing on a translated install.
Sync, and the deletion that kept coming back
Assignments sync through the user's own Google Drive app-data folder, and the merge is the part where a sync quietly eats someone's work. The failure that matters is not a crash — it is a tag silently reverting to what it pointed at last week, on a device you were not looking at.
So the rule is per assignment, not per document. Whole-document last-write-wins means editing one tag on a phone and a different tag on a tablet loses one of the two edits outright, even though they never touched the same thing.
And deletions have to participate like any other edit, which is what tombstones are for. A deleted assignment is kept as a marker with a timestamp and competes on the same newest-wins rule, because an absent row is indistinguishable from a row the other device has never seen — so union-by-newest restores whatever you just deleted. This is not hypothetical: it happened within an hour of switching sync on. Nothing special-cases tombstones; a tombstone beats an older edit and loses to a newer one, which is simply what "the most recent thing the user did wins" means when one of the things is a deletion.
Ties go to local, on the grounds that identical timestamps almost certainly mean the same edit round-tripping, and preferring the copy already here avoids a pointless write-back.
Retention answers a different question from storage, and getting them to agree took a bug first. What is kept on disk is what is shown to the user — taps and scans; diagnostics explain a failure while it is happening and are noise by morning. What is uploaded is narrower still: taps only. On the phone, scan detail explains why the card in your hand behaved oddly this morning; in the cloud the question is what a new phone should be handed, and the answer is what your tags did — not page-level forensics of a card you were holding on a device you no longer own.
Two separate bounds rather than one, for a reason I like: a single scan writes a line per page while a tap writes two, so under one shared limit, dumping a card's memory once would evict weeks of tap history. The history worth keeping, evicted by the history worth glancing at.
Tech, and where it stands
domain/ pure Kotlin — zero android.* imports, enforced by DomainPurityTest
model/ ByteBlock, TagIdentity, ChipProfile, MemoryDump, LockAnalysis
transport/ TagTransport / UltralightTransport — the seam
decoder/ UID/BCC, static lock bits, chip profile, memory rendering
writer/ WriteGuard, PageEncoder
action/ TagAction vocabulary, TagPresence, dispatch
usecase/ ReadTag, WritePage, WritePages
data/ Android adapters, DataStore, Keystore, Drive, Toggl
ui/ Compose Material 3
di/ Hilt
ui -> domain <- data
Single Gradle module, Clean Architecture enforced by package boundary rather than by module count — domain depends on nothing but the Kotlin and JVM standard libraries, which is exactly what keeps it testable without a device. Kotlin on JDK 17, minSdk 26, compileSdk 36, Compose with Material 3, Hilt with KSP, currently v0.18.1 at version code 43.
570 test functions across 42 test files — roughly 8,600 lines of tests against 13,600 lines of source — all running on the JVM with no hardware. They cover UID and BCC arithmetic, every documented lock and block-lock bit, page-access classification, READ wrap-around, memory rendering, the write guard swept across all pages × lock states × expert mode, page encoding, batch writes, the session logger under concurrent writers, JSON escaping, the null-versus-zeros export rule, the sync merge, the Toggl auth header, version comparison, and both view models.
Linting is Detekt, chosen after ktlint was tried and reverted. ktlint's default ruleset produced 628 findings, of which 5 were real: 479 were pure wrapping and signature preference, and 29 flagged every @Composable for being PascalCase — which is the correct Compose convention. Detekt targets code smells rather than formatting, so it does not fight the framework's naming.
What the tests do not cover is Compose screens and Hilt wiring, verified on-device instead. That exemption is not free, and the number is the honest part: a single visual inspection pass found eleven presentation defects a green suite could not see. A test suite tells you the bytes are right. It does not tell you the screen is legible.
Version comparison earned its own pure module for a small, characteristic reason — release tags in this repo are not bare semver (sleep-cycle-toggle-v0.1.0 is a real one), so the numeric run is extracted rather than assumed, and anything yielding no digits is treated as uncomparable rather than guessed at. Guessing means either nagging about an update that does not exist or hiding one that does.
The app requests three permissions and no more: NFC; INTERNET, for one unauthenticated GET against the GitHub releases API and the Toggl and Drive calls; and REQUEST_INSTALL_PACKAGES, which hands a downloaded APK to the system installer — Android still shows its own confirmation screen and the user must separately have allowed installs from this app. The notification-reading and accessibility services are user-granted by hand and inert until then.
Currently it models MIFARE Ultralight MF0ICU1 in full. MIFARE Classic, DESFire, NTAG21x and IsoDep are not started, and neither are NDEF decoding, a raw transceive console or a hex editor. The type system is built so other chips slot in behind ChipProfileResolver and the transport interface without reshaping the domain — which is the actual return on ADR 0001, beyond the tests.
It needs a physical Android device with NFC. That is not a preference, and it is the one requirement no amount of architecture removes — the seam means the logic is testable without hardware, not that the app is usable without it.
Licensed MIT, with one thing worth saying plainly given what this app does: it writes to NFC tags, and some of those writes are physically irreversible. OTP and lock bits can be set but never cleared, so a mistake here is not undone by reinstalling. The write path guards against that and explains itself before acting — but the licence's "as is, without warranty" applies to your tags as much as to the code.