Skip to content

MicroSD tools: detect the card at the point of use - #449

Open
kkdao wants to merge 12 commits into
3rdIteration:devfrom
kkdao:fix/microsd-tools-guard
Open

kkdao wants to merge 12 commits into
3rdIteration:devfrom
kkdao:fix/microsd-tools-guard

Conversation

@kkdao

@kkdao kkdao commented Sep 20, 2026 •

Copy link
Copy Markdown

Description

Problem or Issue being addressed

The MicroSD tools (Flash, Wipe, Verify) could write the wrong device, write under a mounted filesystem, or report success for a write that did not happen:

  1. With an empty slot, None reached dd (of=None), and Wipe said "MicroSD Wiped". Flash looked up the card before its "Insert MicroSD" prompt; a blank card looked like an empty slot; Verify hashed a stale file after a failed read.
  2. The card lookup took the first partitioned mmcblk device, which on a board with eMMC can be the board's own storage.
  3. Only two hard-coded paths were unmounted, and only when the hostname said SeedSigner OS: a Luckfox mounts at /mnt/sdcard, the DIY-tools squashfs is loop-mounted at /mnt/diy from the card, and Wipe (Random) unmounted nothing.
  4. dd exit statuses were ignored, and a card pulled after the checks left a RAM file at /dev/mmcblkN that later "flashes" and "wipes" went to.

Solution

  • Detect the card at the point of use, never across a prompt; refuse through one helper.
  • Only a device the kernel reports as SD is ever a candidate.
  • Before any raw write, unmount everything that depends on the card (loop mounts, overlays, nested mounts, then the card's own), refuse if the card is the running root or swap, and refuse if anything cannot be read.
  • Each write job runs in one child that claims the card exclusively (O_EXCL) and writes through that claimed file, and only while the card still has the CID it had when chosen. Every dd step is checked; a changed or vanished card is a failure.
  • Flash lists and copies from one images folder, and asks the SeedSigner OS marker instead of the hostname.

Additional Information

Known behaviour, unchanged: dd writes are buffered, so a card pulled in the middle of a long wipe is noticed only as the kernel gives up on it, which can take a long time. Also not changed: Bitbox02/Passport/Tapsigner backup views cache the MicroSD dir.

Screenshots

Error screens reuse the existing "Error" WarningScreen with new text (e.g. "No MicroSD card detected. Nothing was wiped.").


This pull request is categorized as a:

  • New feature
  • Bug fix
  • Code refactor
  • Documentation
  • Other

Checklist

I ran pytest locally

  • All tests passed before submitting the PR
  • I couldn't run the tests
  • N/A

CI on the fork (Linux 3.10/3.12 and the Linux/macOS desktop matrix, screenshots included) is green on this exact code. The Windows desktop lanes were left out: they fail on dev itself ("runner lost communication").

I included screenshots of any new or modified screens

  • Yes
  • No
  • N/A

I added or updated tests

  • Yes
  • No, I'm a fool
  • N/A

I tested this PR hands-on on the following platform(s):

  • Raspberry Pi OS
  • SeedSigner OS on a Pi0/Pi0W board
  • Emulator

Pi Zero, SeedSigner OS built from this branch merged with #448, #450 and #451: Wipe (Zero) 64MB on the card in the slot finished with "MicroSD Wiped" and left the card blank. Earlier build of this branch: an empty slot is refused, and a just-wiped, partition-less card wipes again.

I have reviewed these notes:

  • I understand

@kkdao

kkdao commented Sep 20, 2026

Copy link
Copy Markdown
Author

Tested on hardware: Pi Zero running SeedSigner OS built from this branch (pi0, smartcard enabled), boot card removed after boot, wipes performed on a spare 8GB card.

Flow Result
Wipe (Zero) 64MB, empty slot Refused: "No MicroSD card detected. Nothing was wiped." — no success screen
Wipe (Zero) 64MB, card inserted at the prompt Wiped, "MicroSD Wiped"
Wipe (Zero) 64MB again on that just-wiped (partition-less) card Wiped again

The third one is what the "treat a blank MicroSD card as present" commit fixes: before it, a card with no partition table read as an empty slot, so a second wipe (or flashing a brand-new card) was refused.

Flash and Verify were not exercised on the device; they share the detection and refusal path with the wipe views, which the unit tests cover.

Marking ready for review.

@kkdao
kkdao marked this pull request as ready for review September 20, 2026 08:45
@kkdao kkdao changed the title MicroSD tools: never act on a card that isn't there MicroSD tools: detect the card at the point of use Sep 20, 2026
@kkdao
kkdao marked this pull request as draft September 21, 2026 17:29
@kkdao
kkdao marked this pull request as ready for review September 22, 2026 09:20
Three diagnostics in the MicroSD flash view reported nothing
useful. The "Selected:" log passed the filename as an argument to a
message with no placeholder, which raises TypeError inside logging
as soon as the level is enabled; the copy step printed its result
to stdout instead of the log; and the failure screen showed the
literal text "data.stderr" instead of what dd reported.
Every MicroSD tool resolved the device node once and then used that
path across a prompt asking the user to insert the card to work on.
The flash view resolved it before staging the image and before that
prompt, so it refused outright whenever the slot was empty at that
moment, and the path it kept described whichever card was present
before the swap. The verify view never checked the lookup at all
and ran dd with if=None, reading a file named "None".

Look the device up immediately before each dd instead, and refuse
with a screen stating that nothing was written, read or wiped when
no card is present. The refusal is a single helper, so the next
tool added here cannot quietly leave it out.
find_sd_card_device() reported a card only when its disk node had a
partition child in sysfs, which the kernel creates only after parsing
a partition table. A brand-new card has none, and neither does one
the wipe tool just zeroed, so the tools were blind to the very cards
they exist to write: wiping the same card twice, or flashing a blank
one, looked like an empty slot.

Report the disk node itself, still preferring a partitioned card so
that a host with several MMC devices resolves as it did before.
The verify view ran dd with check=False and then hashed /tmp/img.img
regardless. That file still holds whatever the last read or flash put
there, so a card that could not be read was reported with the
previous image's checksum, up to a confident "Matched Checksum".

Inspect dd's exit status and report that the card could not be read.
The MicroSD and GPG before_run helpers start mock.patch objects and
store them on the View, which nothing ever stops, so the rest of the
pytest session ran with find_sd_card_device() patched to return
"/dev/test" and resolve_microsd_images_dir() pointing at a temp dir.
Any later test of the real detector passed or failed on the mock, and
every temp dir the file created stayed on disk after the run.

Register both in the module and undo them in teardown_method, so a
helper that is handed a View rather than the test still gets cleaned
up.
Flash Image listed a hard-coded folder and copied from another spelling
of it. On a board whose images live anywhere else -- a Luckfox with no
card, writing to /userdata; a card on an alternate mount -- it listed
images it then could not find, or listed nothing it could flash.

It also ran an unguarded os.listdir. A stock card has no images folder,
so three taps from the main menu ended on the generic error screen with
a FileNotFoundError, and a folder that exists but is empty crashed too,
on an IndexError from a button list with no buttons.

Resolve the folder once, in flash_images_dir(): the data directory every
other file tool uses on SeedSigner OS, the boot partition on a manual
Raspberry Pi OS build. List from it and copy from it, and say so on a
warning screen when there is nothing there.
find_sd_card_device() took the first mmcblk device with a partition
table, and the raw-write tools dd straight onto whatever it returns.
eMMC is an mmcblk device too, and on a board that has it, it is the
board's own storage -- partitioned, so it won over the card in the slot.
Accepting a blank card as present, as this branch does, only widened
that.

The kernel says which is which in device/type: "SD" for a card, "MMC"
for eMMC, "SDIO" for anything else on the bus. Only an SD card is a
candidate now, and a device that will not say what it is is not one:
refusing to write is the answer that cannot brick a board.
Flash and Wipe (Zero) unmounted two hard-coded paths, /mnt/diy and
/mnt/microsd, and only when the hostname read "seedsigner-os". A Luckfox
mounts its card at /mnt/sdcard and does not carry that hostname, so a
flash went straight under a live filesystem. Wipe (Random) unmounted
nothing at all.

Ask the kernel instead, right before the write, and refuse -- nothing
written -- if anything will not go. A mount is on the card when its
device number in /proc/self/mountinfo is the card's or a partition's.
The name it was mounted by does not say: a root the kernel mounted
itself is listed as /dev/root, which is how Raspberry Pi OS without an
initramfs shows the card it booted from.

A card is held by more than the filesystems mounted from it:
SeedSigner OS loop-mounts diy-tools.squashfs from the card at /mnt/diy,
an overlay with a layer on the card keeps a copy of that mount of its
own, and a mount can sit inside or on top of a card mountpoint. Those
come off first, then the card's own mounts, deepest first. Nothing is
unmounted and the write is refused if mountinfo or the card's sysfs
entries cannot be read, a loop device will not say which file it
reads, device-mapper or md is built on the card, or the card holds the
root filesystem.

The mount table does not show everything that uses the card: swap, an
overlay root whose lower layer was mounted before the root was
switched, a btrfs root under a device number of its own. So the kernel
is also asked outright, by opening for exclusive use, which it refuses
while anything has the device: each partition no mount shows, before
anything is unmounted, and the whole card, once everything is.

The open is a short Python script, run with -c in a child interpreter
under the same su prefix as umount, because a dev host runs the app as
a user who cannot open the device itself. Each device goes to it with
the major:minor sysfs gives it. The kernel honours O_EXCL without
O_CREAT only for a block device, so a regular file at the card's path
would open without complaint: the script fstat()s what it opened and
fails unless it is a block device with that number.

Loop mounts come off with umount -d, which frees the loop device in
the same command, so its file on the card is closed before the card's
own filesystem goes. busybox and util-linux both take -d, and
util-linux skips it for an autoclear loop, which is what either mount
sets up. losetup -d as a second step would need its own answer for a
device autoclear has already freed.

On a Raspberry Pi OS host the image is copied before the card is
unmounted: it comes from /boot, which can be on the card.

The same hostname check decided whether dd needed sudo, so SeedSigner
OS is now recognised in this file the way the rest of the codebase
recognises it, by Settings.is_seedsigner_os().
A flash or a wipe could report success after a step in it had failed.

Flash on a Raspberry Pi OS host ran cp and then dd without looking at
either result, and said nothing once dd was done. A copy that failed
left /tmp/img.img holding whatever an earlier flash or Verify had put
there, and dd wrote that to the card. A dd that failed and one that
worked looked the same: straight back to the main menu.

Flash on SeedSigner OS zeroes the first 26 MB before it writes the
image, and wrote the image whatever the zeroing had done. It and both
wipes then went by dd's record counts alone, which do not say: GNU dd
reports every record written, and exits 1, when it is closing the card
that fails.

Every dd that writes to the card now goes through one check: it must
exit cleanly and write every record it read. A wipe still counts a
full card as done, since it writes until it has written what was asked
or the card is full, and dd then fails with "No space left on device".
A failed zeroing ends the flash and is what gets reported. The copy is
judged by its exit status on both branches, and on a dev host a copy
that fails is refused before the card is touched.

A dev-host flash reports as the SeedSigner OS branch does: dd's error
output on failure, "MicroSD Flashed" on success. Verify is not offered
there: the SeedSigner OS branch zeroes the first 26 MB, the span Verify
hashes, before it writes, and this one does not.
Settings learns that the card has gone from mdev, which reports a card
pulled out of the slot. Flash and the wipes unmount the card
themselves, and nothing reported that, so Persistent Settings stayed on
offer with nowhere left to save to: on a board without /userdata, a
change made after a wipe was skipped without a word. A save still
waiting on its timer could also land after the card was unmounted.

Write any waiting save before the first umount, and afterwards tell
Settings the card was removed, as mdev would have. That happens even
when the unmount is refused part-way, since a card mountpoint may
already be gone by then.

One thing a card pulled out by hand runs into is left as it was: on a
Luckfox the next save still goes to /mnt/sdcard, by then a bare
directory on the root filesystem, because SETTINGS_FILENAME is resolved
once at start-up. Following the store as it changes is a separate
change.
dd opens of= with O_CREAT, busybox's as well as GNU's. A card pulled
after it was unmounted takes its node with it, and dd then creates a
regular file of that name instead, in RAM on devtmpfs, writes it and
exits 0: Flash said "MicroSD Flashed" and the wipes "MicroSD Wiped"
for a card nothing had reached. devtmpfs never replaces a file it did
not make, so the file then stood in for the card, even once the card
was back, and every later Flash, Wipe and Verify found it instead.

After each dd that writes the card, and after Verify reads it, the
path must still be the block device with the number sysfs gives the
card. Otherwise the step failed, and a regular file at the path is
removed so that the card's node can come back. The card is asked
about first, whatever dd said, since a dd that failed can have left a
file behind as well, having filled RAM with it.

conv=nocreat would stop dd making the file, but busybox dd, as
SeedSigner OS builds it, has no such flag and rejects the whole
command over it. GNU dd on a dev host does have it; one check that
holds for both is kept rather than a second path for one of them.
The exclusive-open check proved the card free, then let go of it
before dd opened the card, and Flash let go of it again between its
zero pass and its image. Anything that took the card in those gaps
was written under: a remount, or a card swapped into the slot. A card
pulled and another put in even takes the same node and device number,
so unmounted it passed every check.

Each job now runs in one child that claims the card for exclusive use
and runs every dd of the job with of=/proc/self/fd/N, the file it
claimed, until the last has finished, so nothing can mount the card
meanwhile. The card's CID is read when it is chosen, and the child
writes only while the card in the slot still has it: before the first
dd, and after each one before its exit status is looked at, since a
wipe that fills the card ends in an error that counts as success. A
changed card is a failure whatever dd said, and a card that will not
give its CID is not written. The child runs under the su prefix, so
its dds carry none.
@kkdao
kkdao force-pushed the fix/microsd-tools-guard branch from 73ce605 to 345f517 Compare September 25, 2026 21:08

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant