Goal: a system that cannot be permanently tampered with
A read-only rootfs is the simplest effective hardening against persistent tampering: what cannot be written cannot be permanently changed by an attacker or a power cut. This article is a build-it-yourself manual - from the squashfs image through controlled write paths to A/B updates and factory reset.
The mechanisms come from a real, anonymized field-device project; all names, paths and recipes are generic. The target release is Yocto 6.0 "Wrynose" (LTS until April 2030); the override syntax works from Honister (3.4) onwards.
- A provisioned system keeps its provisioning across system updates.
- A failed system update can be rolled back - to the last working state.
- Applications update separately, but always as a set matching the system image.
- Factory reset restores shipping state without losing provisioning or lifetime data.
- Updates survive power loss and resume at the last completed step.
- The writable surface is minimal and fully inventoried.
Architecture: two controlled write paths
The rootfs becomes a compressed squashfs - read-only by design. Only two classes of paths are writable: directories with their own overlayfs (lower = rootfs, upper = persistent storage), and symlinks pointing into a writable area.
Each directory gets its own overlay. This is the central design decision: it determines which part of the system can be reset individually - a factory reset later becomes a pure delete operation on upper layers.

- Overlay rule: the upper tree may only be modified while the overlay is not mounted - otherwise behavior is undefined (kernel documentation).
- Defaults live in the image (lower); modifications shadow them only when actually changed. Deleting the upper entry restores the default.
- One shared persistent partition serves both A/B system slots - saves space, but demands migration after every slot switch.
Partition layout: A/B slots plus one persistent partition
The layout has four partitions: bootloader, two system slots and one persistent data partition. A new image is always flashed into the inactive slot; the bootloader decides which slot starts.

| Partition | Filesystem | Role |
|---|---|---|
| boot | VFAT or ext4 | U-Boot plus environment (bootcount, slot selection) |
| rootfs_a | squashfs (read-only) | System slot A: kernel, rootfs, system packages |
| rootfs_b | squashfs (read-only) | System slot B: identical structure, update target |
| persist | ext4 (rw), optional LUKS | Overlay uppers, device-root, update state, backups |
Base image: squashfs and read-only-rootfs
Two settings make the image read-only: IMAGE_FSTYPES produces a squashfs, IMAGE_FEATURES += "read-only-rootfs" hardens the system. Compression is chosen via the image type (squashfs-xz) - a separate compression variable does not exist.
- The kernel command line gains ro, the root line in /etc/fstab is set to ro.
- Post-install scripts must succeed at image build time - otherwise the build fails. No "will run on first boot".
- systemd: /etc/machine-id stays an empty file in the image - the system boots stateless.
- sysvinit: ROOTFS_READ_ONLY=yes, populate-volatile.sh already runs at build time.
- Every write attempt into the rootfs fails at runtime - processes must use writable paths.
# conf/local.conf
IMAGE_FSTYPES += "squashfs-xz"
IMAGE_FEATURES += "read-only-rootfs"
INIT_MANAGER = "systemd"
# meta-device/recipes-kernel/linux/linux-%.bbappend
FILESEXTRAPATHS:prepend := "${THISDIR}/files:"
SRC_URI += "file://readonly.cfg"
# meta-device/recipes-kernel/linux/files/readonly.cfg
CONFIG_SQUASHFS=y
CONFIG_SQUASHFS_XZ=y
CONFIG_OVERLAY_FS=yPersistent storage and defaults
The persistent partition mounts at /media/data. Two trees live below it: overlay/ for the upper layers and device-root/ as the symlink target area - mirroring the rootfs structure with etc/, opt/ and usr/lib/sysimage/.
The image ships defaults read-only under /usr/share/device-defaults/. A oneshot service copies them into device-root at boot, but only where files are missing (cp -rn). Deleting a file plus a reboot restores the default - the same principle as with overlays.
Encryption is optional but recommended: a LUKS container below the ext4 partition protects data at rest. Never keep the key in plaintext on the device - hardware keyblob or secure element, otherwise the encryption is pointless.
# /etc/fstab (im Image; der Bootloader setzt root= auf den aktiven Slot)
/dev/disk/by-partlabel/persist /media/data ext4 defaults,noatime 0 2
# Verzeichnisgerüst (Rezept device-base-files, siehe unten)
/media/data/overlay/<dir>/upper
/media/data/overlay/<dir>/work
/media/data/device-root/{etc,opt,usr/lib/sysimage}
# /usr/lib/systemd/system/provision-defaults.service
[Unit]
Description=Seed writable device-root from read-only defaults
After=media-data.mount
Before=nginx.service sshd.service
[Service]
Type=oneshot
ExecStart=/bin/sh -c 'cp -rn /usr/share/device-defaults/. /media/data/device-root/'
RemainAfterExit=yes
[Install]
WantedBy=multi-user.targetOverlayfs in 60 seconds
Overlayfs combines a read-only base (lowerdir) with a writable layer (upperdir) into a writable view (merged). workdir is internal working space of the kernel driver. The rules are in the kernel documentation (filesystems/overlayfs):
- lowerdir may be read-only - exactly our squashfs.
- upperdir and workdir must live on the same filesystem.
- The upper filesystem needs trusted.* xattrs and valid d_type values - NFS is unsuitable.
- Changes to lower or upper while the overlay is mounted are forbidden (undefined behavior). Offline changes to the upper are allowed.
- Deleted lower files appear as whiteouts (character device 0/0 or trusted.overlay.whiteout xattr); opaque directories carry trusted.overlay.opaque=y.
mount -t overlay overlay \
-o lowerdir=/var/lib,upperdir=/media/data/overlay/var-lib/upper,workdir=/media/data/overlay/var-lib/work \
/var/libOverlays at boot: mount units
systemd dynamically generates mount units from /etc/fstab; for overlays a dedicated unit is the cleaner solution. Type=overlay creates upperdir and workdir automatically if missing. Where must not be a symlink - the mount point must be a real directory.
Watch out: the OE recipe volatile-binds (systemd images) binds /var/lib, /var/cache, /var/spool and /srv to /var/volatile by default - into volatile storage. If you want persistent overlays, adjust VOLATILE_BINDS in a bbappend or remove the affected entries.
# /etc/systemd/system/var-lib.mount
[Unit]
Description=Persistent overlay for /var/lib
Requires=media-data.mount
After=media-data.mount
[Mount]
What=overlay
Where=/var/lib
Type=overlay
Options=lowerdir=/var/lib,upperdir=/media/data/overlay/var-lib/upper,workdir=/media/data/overlay/var-lib/work
[Install]
WantedBy=local-fs.target
# Alternative: fstab-Zeile mit Ordering-Option
# overlay /var/lib overlay lowerdir=/var/lib,upperdir=/media/data/overlay/var-lib/upper,workdir=/media/data/overlay/var-lib/work,x-systemd.requires=media-data.mount 0 0Which directories get an overlay
The list is deliberately short. Every overlay is attack surface and migration effort - only what truly needs persistence gets one. /var/log, /var/run and /tmp stay volatile (tmpfs via /var/volatile); they should be empty after a reboot.
/etc itself gets no overlay: systemd depends on it. Yocto does have the IMAGE_FEATURE overlayfs-etc, but its default mode restricts package management. Instead, individual files and subdirectories become writable via symlinks (next section).
| Path | Mechanism | Reason |
|---|---|---|
| /var/lib | overlayfs | RPM database and service state must persist |
| /var/cache | overlayfs | Package and application caches survive reboots |
| /home | overlayfs | User and service data |
| /etc/yum.repos.d | overlayfs | Temporary repositories for testing and provisioning |
Which files become writable via symlink
Symlinks replace the original file in the rootfs with a reference into /media/data/device-root/. The image installs defaults there (via provision-defaults); modifications edit the target file directly. The advantage over an /etc overlay: every file is individually classifiable and resettable.
resolv.conf shows the cascade: the runtime manager (DHCP) writes /run/resolv.conf; the middle file can be replaced with a real file to pin static configuration - without opening the rootfs.
| Path in rootfs | Target under device-root/ | Purpose |
|---|---|---|
| /opt/apps | opt/ | Applications and libraries (bin, lib) |
| /usr/lib/sysimage | usr/lib/sysimage/ | dnf5 system state |
| /etc/passwd, shadow, group, gshadow | etc/passwd, shadow, group, gshadow | Runtime user management (optional maintenance user) |
| /etc/ssh | etc/ssh/ | Host keys (first boot), known_hosts |
| /etc/network | etc/network/ | Network configuration from commissioning |
| /etc/logrotate, /etc/logrotate.d | etc/logrotate, etc/logrotate.d | Log rotation stays adjustable |
| /etc/adjtime | etc/adjtime | Hardware clock drift file |
# Kaskade: /etc/resolv.conf (Symlink, im Image)
# -> /media/data/device-root/etc/resolv.conf (Symlink, provisioniert)
# -> /run/resolv.conf (tmpfs, vom DHCP-Client beschrieben)
ln -s /media/data/device-root/etc/resolv.conf /etc/resolv.conf
ln -s /run/resolv.conf /media/data/device-root/etc/resolv.conf
# Statische Konfiguration pinnen: mittleren Symlink durch echte Datei ersetzen
rm /media/data/device-root/etc/resolv.conf
printf 'nameserver 192.0.2.53\n' > /media/data/device-root/etc/resolv.confRecipe pattern 1: bbappend for standalone components
Components with their own configuration (nginx here) move their /etc directory into the writable area and symlink back. The maintainability rule: every recipe that extends write access requires the shared include - a grep-able audit finds all exceptions.
Changes apply only to class-target: native and SDK builds do not need the write paths. QA_EMPTY_DIRS:remove allows packages below /media, which the QA check would otherwise flag as "expected empty".
# meta-device/recipes-core/device-base-files/device-base-files.inc
deviceRootPath = "/media/data/device-root"
# meta-device/recipes-core/device-base-files/device-base-files.bb
SUMMARY = "Writable-path skeleton for the read-only rootfs"
LICENSE = "MIT"
LIC_FILES_CHKSUM = "file://${COMMON_LICENSE_DIR}/MIT;md5=0835ade698e0bcf8506ecda2f7b4f302"
do_install() {
install -d ${D}${deviceRootPath}${sysconfdir}
install -d ${D}${deviceRootPath}/opt
install -d ${D}${deviceRootPath}/usr/lib/sysimage
install -d ${D}/media/data/overlay
}
FILES:${PN} = "${deviceRootPath} /media/data"
# meta-device/recipes-support/nginx/nginx_%.bbappend
require recipes-core/device-base-files/device-base-files.inc
DEPENDS:append:class-target = " device-base-files"
do_install:append:class-target() {
install -d ${D}${deviceRootPath}${sysconfdir}
mv ${D}${sysconfdir}/nginx ${D}${deviceRootPath}${sysconfdir}/nginx
ln -s ${deviceRootPath}${sysconfdir}/nginx ${D}${sysconfdir}/nginx
}
FILES:${PN}:append:class-target = " ${sysconfdir}/nginx ${deviceRootPath}${sysconfdir}/nginx ${deviceRootPath}${sysconfdir}/nginx/*"
QA_EMPTY_DIRS:remove:class-target = "/media"Recipe pattern 2: ROOTFS_POSTPROCESS_COMMAND for shared resources
Files like passwd/shadow/group/gshadow only come into existence when the image is assembled - several recipes write into them. A bbappend per component runs too early; the right place is a postprocess function that runs after rootfs creation.
${IMAGE_ROOTFS} points at the rootfs under construction. The function moves the file into device-root and replaces it with a symlink - the writable path is done, with zero runtime cost. The function list is extended with += (the doc-canonical form).
# In device-base-files.inc
device_base_files_provision_readonly_etc() {
for f in passwd shadow group gshadow; do
mv ${IMAGE_ROOTFS}${sysconfdir}/$f \
${IMAGE_ROOTFS}${deviceRootPath}${sysconfdir}/$f
ln -s ${deviceRootPath}${sysconfdir}/$f \
${IMAGE_ROOTFS}${sysconfdir}/$f
done
}
# Im Image-Rezept (oder per bbappend auf das Image)
ROOTFS_POSTPROCESS_COMMAND += "device_base_files_provision_readonly_etc"Volatile state and runtime reality
Not everything should persist. /var/volatile is a tmpfs; populate-volatile (sysvinit) or systemd-tmpfiles create the volatile directories and symlinks. Logs, sockets and PID files belong there - not into an overlay.
- /etc/machine-id stays empty in the image; systemd boots stateless and assigns a transient ID.
- An optional maintenance user is created at runtime - hence passwd/shadow/group/gshadow must be writable.
- Timekeeping: /etc/adjtime (hwclock drift) via symlink; systemd-timesyncd state lives under /var/lib and is persistent anyway.
- Log rotation: configuration writable via symlink, the cron entry lives in the read-only image.
- SSH host keys are generated on first boot in writable /etc/ssh - never ship them in the image.
Development image: debugging without write access
The development image is a separate recipe on the same base - not "just make everything writable". Debuginfo packages install sources into /opt/apps/src; PATH and library path are set through files the image installs.
The trap: /etc/ld.so.conf.d is read-only, and ldconfig cannot update /etc/ld.so.cache. If you need extra library paths, set LD_LIBRARY_PATH or bake the path into the image - not at runtime.
# /etc/profile.d/apps.sh (vom Entwicklungs-Image installiert)
export PATH=$PATH:/opt/apps/bin
# /etc/ld.so.conf.d/apps-extend-libpath.conf (read-only, im Image)
/opt/apps/lib
# Konsequenz: ldconfig scheitert am read-only /etc/ld.so.cache.
# Entweder LD_LIBRARY_PATH nutzen oder den Pfad ins Image bauen.The RPM database trap after a slot switch
/var/lib is an overlay - so part of the RPM database lives in the upper. After flashing a new system image, the old upper database shadows the new image database: system packages are out of sync, applications exist only in the old database.
Three options were evaluated: a full rebuild in place (fails - system libraries cannot be synchronized), delete plus partial rebuild, delete plus reinstall of all applications (costs bandwidth). The middle variant was chosen - as a field-tested pattern, not a Yocto-documented procedure:
- Back up and delete the upper database - the image database becomes visible again.
- System packages are now in sync; application RPMs are re-recorded without filesystem writes.
- Save the file list at every application install - the basis for later rebuilds.
- dnf5 keeps its system state under /usr/lib/sysimage - hence the symlink from the matrix.
- Check on the target where the database really lives: rpm -E %_dbpath (Yocto may relocate the path).
# Migrations-Modus: /var/lib-Overlay NICHT gemountet (Offline-Regel!)
mv /media/data/overlay/var-lib/upper/rpm /media/data/backup/rpm-old
# Overlay frisch mounten, dann Anwendungspakete nur in der DB erfassen:
rpm --justdb --noscripts --notriggers -ivh /media/data/packages/app-*.rpm
# Bei jeder Installation: Dateiliste für spätere Rebuilds sichern
rpm -ql app-core > /media/data/packages/app-core.files
# dnf5: Transaktion ohne Dateisystem-Änderung (tsflags)
dnf5 --setopt=tsflags=justdb install app-coreA/B system updates: the interruption-safe flow
Applications depend on system libraries - a kernel or library update can break them. So applications always update together with the system image, as a matching set. The first boot after the update runs in migration mode: applications start only after data migration and a functional test.
The state (last step, retry counter) lives on the persistent partition. Power loss is thus not a disaster - the flow resumes. Repeated failures indicate a faulty update and trigger rollback.

- Receive the update job (system image plus application RPMs).
- Flash the new system image into the inactive slot.
- Reboot into the new slot.
- Disable application autostart.
- Create backups (overlay state, RPM database) - the basis for rollback.
- Migrate the RPM database and system configuration.
- Install the new application RPMs.
- Start applications in migration mode (data migration).
- Functional test, then start normal operation.
- Report completion to the backend.
# U-Boot: nach bootlimit fehlgeschlagenen Boots altbootcmd statt bootcmd
setenv bootlimit 3
setenv altbootcmd 'setenv rootfs_slot a; setenv upgrade_available 0; saveenv; run bootcmd'
saveenv
# Linux, nach erfolgreichem Boot (Userspace verantwortet den Reset):
fw_setenv bootcount 0
fw_setenv upgrade_available 0Watchdog, failure classes and rollback levels
A kernel panic while booting into the new image cannot be fixed remotely - the device must recover on its own. Two mechanisms: the watchdog is armed in U-Boot and no longer serviced on the way into the kernel; a stall causes a reset. bootcount counts failed boots, and from bootlimit onwards altbootcmd runs into the old slot.
Important detail: CONFIG_WATCHDOG means U-Boot services the watchdog itself. For the stall behavior the watchdog must start but be handed to the kernel unserviced (Kconfig documentation).
- Recoverable: power loss/reboot - as long as the last step is known and the retry counter runs along.
- Recoverable: unexpected system binaries in the upper (a developer installed system packages standalone) - clean up before migration.
- Non-recoverable: kernel panic/stall at boot - watchdog reset plus bootcount fallback.
- Non-recoverable: failed data migration - rollback to the previous state.
- Non-recoverable: incompatible application RPM (wrong library dependency) - roll back the set.
Rollback: three levels, one principle
Rollback means: restore backups and boot into the previous state - not repair. The levels differ in how much gets reverted. Multiple applications with IPC dependencies must be reverted together.
- System level: system update including application migration failed - switch slot back, restore backups.
- Application set: data migration or functional test failed - revert all affected RPMs including their data.
- Single application: only if no dependencies are dragged along; otherwise set rollback.
- Manual: non-recoverable errors in normal operation - update or rollback as a deliberate decision.
Factory reset: data classes instead of wipe mode
A factory reset must not delete everything. Data is divided into three classes; the class determines what happens at which reset type. Classified correctly, the reset is a targeted delete operation - not a re-flash.
The offline rule applies here too: upper directories are deleted before the overlays are mounted. A oneshot service ahead of the mount units checks a reset request and deletes the affected trees; afterwards the overlays mount with empty uppers, and provision-defaults restores the defaults.

| Class | Examples | Normal reset | Aggressive reset |
|---|---|---|---|
| parameters | Runtime settings, user configuration | reset | reset |
| provisioning | Keys, certificates, network and backend configuration | kept | reset |
| lifetime | Counters, calibration, irreplaceable records | kept | kept |
# /usr/lib/systemd/system/factory-reset.service
[Unit]
Description=Apply pending factory reset before overlays mount
After=media-data.mount
Before=var-lib.mount home.mount
ConditionPathExists=/media/data/reset-request
[Service]
Type=oneshot
ExecStart=/usr/libexec/factory-reset.sh
ExecStartPost=/bin/rm -f /media/data/reset-request
[Install]
WantedBy=local-fs.target
# /usr/libexec/factory-reset.sh - uppers are NOT mounted yet
#!/bin/sh
set -eu
rm -rf /media/data/overlay/var-lib/upper/*
rm -rf /media/data/overlay/home/upper/*
rm -rf /media/data/device-root/etc/params
# provisioning und lifetime bleiben unangetastetMigration: coming from a writable image
Existing devices with a largely writable rootfs cannot be migrated gently - the cut is a factory reset with re-provisioning. What is lost and what no longer works afterwards belongs into the migration guide:
- /etc overlays are gone: individual configuration is lost and must be re-applied.
- Network configuration is gone - without DHCP, serial console access is required.
- Overlays in /usr, /sbin, /bin, /lib are gone: additionally installed system binaries are lost.
- System packages can no longer be installed individually - only via a system image update.
- ldconfig can no longer update /etc/ld.so.cache: LD_LIBRARY_PATH or an image update.
- Applications move from /usr/{bin,lib} to /opt/apps; init scripts become part of the image.
Verification: what to check before release
Every property of the system is testable - most checks run directly on the target. The list doubles as the acceptance checklist for the update procedure:
- Write attempts into read-only paths fail with EROFS - no exception in the inventory list.
- After a slot switch: rpm database consistent, applications start in migration mode.
- Factory reset keeps provisioning and lifetime; parameters are back to defaults.
- The retry counter limits repetitions; afterwards rollback instead of an endless loop.
findmnt -t overlay # alle geplanten Overlays sichtbar?
cat /proc/cmdline # 'ro' vorhanden?
touch /usr/bin/should-fail # erwartet: Read-only file system
rpm -qa | wc -l # nach Update: System + Anwendungen konsistent?
fw_printenv bootcount upgrade_available
# Factory-Reset-Test: Datei im Upper löschen, Reboot, Default wieder da?
# Unterbrechungs-Test: Strom während Schritt 6 ziehen, Ablauf setzt wieder auf?
# Watchdog-Test: Kernel-Stall provozieren, Gerät bootet in den alten Slot?Pitfalls and references
References: Yocto Security Manual (read-only-rootfs, 6.0), kernel documentation filesystems/overlayfs, rpm.org rpm(8) (--justdb, --noscripts, --notriggers), dnf5 documentation (system_state_dir, tsflags), systemd.mount(5), U-Boot bootcount documentation. The RPM migration and update flow patterns are field experience from an anonymized project - verify them on your own target.
If you want your own setup reviewed externally - before a tender or a customer audit - the Yocto Risk Scan offer has a fixed scope with a written risk report.
- Editing the upper while the overlay is mounted - undefined behavior, silent data loss.
- volatile-binds overlays /var/lib into /var/volatile - persistence is then gone.
- An old RPM database in the upper shadows the new image - migration is mandatory, not optional.
- ldconfig fails on read-only /etc - bake library paths into the image or use LD_LIBRARY_PATH.
- A mount unit with Where=symlink fails - mount points must be real directories.
- Post-install scripts that need first boot - read-only-rootfs fails the build.
- One overlay for everything - reset granularity and auditability are lost.
