diff --git a/mac-manual/content/04-security.md b/mac-manual/content/04-security.md index f294a04a..5108bd8d 100644 --- a/mac-manual/content/04-security.md +++ b/mac-manual/content/04-security.md @@ -18,6 +18,14 @@ Owner provisioning then asks for your name and password, as on x86. On an encryp The next boot unlocks the disk with your password. At the prompt the built-in keyboard and trackpad work, because their drivers are loaded early in the initramfs. A Bluetooth keyboard does not, just as on x86: use the built-in keyboard or a wired one. +## Touch ID login + +After you explicitly enable Touch ID, its driver starts at each boot and restores the fingerprints already enrolled for Linux. The first interactive SDDM login after each boot uses your password, which also unlocks your login keyring if you have one. SDDM then records that login for the rest of the boot; a lingering user service alone does not count. After that, a stock SDDM login screen accepts Touch ID: submit your username with an empty password and touch the sensor when prompted. This works while your user services from that login are still running, as they are while another session of yours is open and sometimes after you log out. It is not offered while a login keyring of yours is locked. Automatic login after the disk password does not create this record: the first later SDDM screen still needs your password, and subsequent screens can accept Touch ID. Enabling or upgrading the policy during a session likewise needs one password login before fingerprints are offered. Typing your password always works and skips the fingerprint wait. An account that has no password cannot use the SDDM login screen while Touch ID is on. A customized SDDM authentication stack is left for its administrator rather than rewritten, and fingerprint setup carries on without the login screen change. + +Fingerprint login does not unlock an encrypted root disk, so keep using the disk password at the early boot prompt. Three rejected fingers count toward the account lockout like wrong passwords, and an accepted finger clears the count. If you change the lockout limits, set up the fingerprint again so the login screen uses the new ones. Turning Touch ID off removes its SDDM authentication include but does not delete the Linux key store. If an administrator has customized the PAM configuration and the include cannot be removed safely, turning Touch ID off still stops the driver loading at the next boot and reports that the PAM configuration needs review. + +On the 15-inch M4 Air (J715), Touch ID also requires a compatible kernel and this Mac's own FDR root key and FSC2 calibration. They are private, are not shipped in a package and are not interchangeable with another Mac's files. Setup currently accepts only the 130427-byte calibration size observed working on one reference Mac. Size does not authenticate the file, and other sizes have not been qualified. The earlier J715 port has restored an existing enrollment and completed fingerprint login after a cold boot, but the current upstream kernel still needs its own qualification. + ## Changing passwords Change passwords under _Update > Password_ in the Omarchy menu, as on x86. On a Mac your disk password and your login password start out the same, but each changes on its own: _Drive Encryption_ changes only the disk password, and _User_ only the login password. A disk password change is recorded step by step, so an interruption resumes rather than leaving the disk half changed. If you no longer know your password, see the next section. diff --git a/omarchy-mac/README.md b/omarchy-mac/README.md index 93939a4a..eb5c55d7 100644 --- a/omarchy-mac/README.md +++ b/omarchy-mac/README.md @@ -26,7 +26,7 @@ The Mac's hardware data lives in the platform root, `/usr/share/omarchy-platform - `display-cutouts.json`: the notch of each MacBook panel (the 14" Pro measured at 64 physical rows, the 16" Pro inferred at 64 and the Airs at 56), which the bar keeps clear of. A notched panel not listed gets no floor until the file lists it; `[bar] notch-height` in `shell.toml` only adjusts the floor of a listed panel. An entry may also name `cutoutWidth`, a centered notch's measured width in physical columns. Support for placing center status content beside that notch remains proposed for the canonical desktop in [omacom/omarchy#17744](https://github.com/omacom/omarchy/pull/17744); this schema alone does not change placement. A runtime without that support, or a panel without the key, keeps its current layout. - `displays.conf`: `omarchy-hw-display` never picks the Touch Bar's `display-pipe` or `228600000.dsi.0` backlight and prefers the Retina panel's `apple-panel-bl` (no GPU backlight exists), and `omarchy-brightness-display` probes an external monitor over DDC only when its connector has a `ddc` node, since Apple's display driver registers no DDC channel and a probe would walk the SoC's SMBus for about 3 s. - `audio.json`: the audio panel and microphone widget leave out asahi-audio's DSP internals: the speaker graph's output stream into the raw speakers (`effect_output.jNNN-convolver`, and the desktops' `mini`/`studio`), the microphone graph's always-running capture of the raw array (`audio_effect.jNNN-mic`), the raw devices asahi-audio marks do-not-use (`RawSpeakers`, `RawMics`), the mapper's own capture of the DSP microphone (`input.omarchy_asahi_mic`), which would otherwise count as an app recording, and the mono DSP microphone while the mapper's stereo `omarchy_asahi_mic` exists. A runtime older than the platform root reads no audio hints and keeps its own Apple checks. -- `fingerprint-readers`: Touch ID. `omarchy-hw-fingerprint` finds the sensor once `/run/omarchy-mac/touchid` reads `ready`, or `available` before the owner has turned it on. Nothing loads the Secure Enclave driver until the owner agrees. At boot, `omarchy-mac-touchid-status.service` (`lib/touchid-status`, pulled in by the package's `multi-user.target.wants` link, before the greeter and `fprintd`) asks `lib/touchid-eligibility`, which reads only the device tree and installed files: `available` needs a sensor node, a board the aurora driver has a profile for (M2, M2 Pro and Max, the M3 Air J613 and J615, and the MacBook Neo; M1-family Macs wait for their xART guard path), `/chosen/apfs-preboot-uuid`, a way to the calibration (under the name the sensor's `firmware-name` gives, `apple/mesacal-.bin`, or `apple/mesa_calibration.bin` on M2 Pro and Max) and, on the Neo, a way to the sensor root key, an installed one or the factory records on the ESP with `python` to rebuild it from (the extractors need `python`, which linux-aurora only suggests), and an Omarchy whose `omarchy-lifecycle-dispatch` resolves `enable-fingerprint`, since the invitation comes once and an older setup would enrol a reader nothing turned on; anything else records `unsupported:`, which no detector line names. Omarchy's fingerprint setup then runs `omarchy-lifecycle-dispatch enable-fingerprint` (`entrypoints/enable-fingerprint`, as root) before enrolling. With no status file (a Mac without a sensor records nothing, and a status service can fail) it works eligibility out again. Where Touch ID can't be set up it lets the setup go on, so a USB reader enrols on a Mac mini, a Studio or an M1 Mac as it would without Touch ID. A Mac whose owner already agreed is never asked again: it gets any missing options and, unless Touch ID reads `ready`, is told to restart, and the setup goes on. It stops the setup only when the owner says no, or turning Touch ID on or writing its options fails. It says in three lines that Touch ID is experimental and can be unstable, that it shares the Secure Enclave with macOS so macOS should be backed up first, and that the Mac manual has the details, then asks. The manual's Encryption and passwords page carries the rest: the key store Linux creates stays, the enclave's anti-replay state moves forward and is one file in the iBoot System Container that macOS updates too, and a bug that writes it wrongly can cost macOS data (with FileVault on, macOS won't start and the Mac needs a DFU restore; with FileVault off, macOS resets its keychain and fingerprints). FileVault's state isn't checked: the owner can change it after installing, so the manual names both cases. On yes, `lib/touchid-enable` carves what is missing from this Mac's own iBoot System Container into `/usr/lib/firmware/updates` (the calibration with linux-aurora's `extract-mesa-calibration`, except on the Neo, whose installer writes the sealed form; the Neo's `apple/msrk-j700.bin`, root-only `0600`, rebuilt with `lib/touchid-root-key`), records the agreement in `/etc/omarchy-mac/touchid-on` and in the driver's options (`/etc/modprobe.d/omarchy-mac-touchid.conf`: `xart_writes=1 provision_keybag=1`, today's defaults, which a kernel that loads `apple_sep` read-only by default, omacom/linux-aurora#180, writes only with; the name sorts after `apple-sep.conf`, so the owner's agreement wins over any `apple-sep.conf`, while `apple_sep.xart_writes=0` on the kernel command line still wins over both, and no initramfs hook includes `apple_sep`, so only the root's copy of the options is read), loads `apple-sep` now (a driver already running keeps the options it loaded with, so on a kernel that loads it read-only, and a Mac with no key store yet, the agreement stands and Touch ID turns on after a restart), and succeeds only once the activation records `ready`, restarting an `fprintd` that started without the reader; a failure after the record is written removes it again, so the next boot offers Touch ID again instead of loading a driver that never came up. A driver that loaded but never came up stays that way until a restart, so the status then reads `failed` and setup doesn't offer Touch ID again that boot; when `/dev/sep-bio` or the keybag never appeared, the activation never ran, and the error points to `journalctl -k`, the driver's own log. While the record exists, `omarchy-mac-touchid-load.service` (pulled in by a `multi-user.target.wants` link) loads `apple-sep` at every boot once `udevadm wait` sees `/dev/disk/by-partlabel/iBootSystemContainer`, since the driver opens that link as it probes and does not retry, and before the greeter and `fprintd`. The wait is part of the service rather than a device dependency, because systemd waits for a unit's devices before it checks its condition: a dependency would hold up every boot, agreed or not, and the greeter on a machine without the partition until the device timed out. A key store from an earlier load (`/var/lib/aurora-sep-keybag.bin`) is not agreement: that owner never saw this text, so they are asked too, told that the existing key store is used. `omarchy-lifecycle-dispatch disable-fingerprint`, after the fingerprints are deleted, removes the record and the options, so the driver stops loading from the next boot and the status offers Touch ID again; the key store stays. A record or options that can't be written, or removed, fails the operation rather than reporting success, and a carved calibration, like the sensor key, takes its name only once it is whole. On a kernel with omacom/linux-aurora#180, udev loads `apple_sep` on every Mac, read-only unless the options file exists, and a read-only driver always reports `matching` as `blocked`. The activation runs only on the owner's record, so a Mac whose owner hasn't agreed, or turned Touch ID off, keeps the boot's `available` and is offered Touch ID; and `enable-fingerprint` writes the options for a Mac agreed before they existed whatever its status, so one that reads `blocked` reaches `ready` after a restart. The Neo's sensor key (`apple/msrk-j700.bin`) is device-private, so nothing reads it before the owner agrees. asahi-installer copies this Mac's factory records (`com.apple.factorydata`) into the ESP's fallback firmware archive, `asahi/all_firmware.tar.gz`, on every install; an image install mounts the ESP at `/boot/efi` with `umask=0077`, so only root can read it there, and that mount is where the archive is read; on yes, `lib/touchid-root-key` (Python's standard library only) reads the `MSRk`, `seal` and trust bundle records from it in memory, rebuilds the key as omarchy-mac-installer's `factory_root_key()` does on macOS (the `MSRk` record's `IM4P` under the FDR sealing manifest, with the trust bundle as `secb`), checks its envelope, and refuses records that aren't all found byte for byte in this Mac's own iBoot System Container, so an archive from another Mac, or one swapped on the ESP, gives no key. It writes the key root-only (`0600`) under a temporary name, synced, then renames it. Nothing is kept when the owner says no, and a yes that then fails to turn Touch ID on takes back the key it rebuilt along with the agreement; `disable-fingerprint` deletes the installed key, and the next yes rebuilds it. A factory reset gives the factory root no key, since the ESP survives it and the next owner's yes rebuilds it. Every Neo install has the archive, since upstream asahi-installer writes it on every install, so none needs the installer to collect the key. A Neo without the archive (removed by hand) or without `python` reads `unsupported:no-root-key`; the boot status looks for the archive, so `omarchy-mac-touchid-status.service` runs after `boot-efi.mount`. Carved files under `/usr/lib/firmware/updates` belong to no package, so a root rollback can remove them. An agreed Mac isn't asked again, so its setup doesn't carve them back: turning Touch ID off (Omarchy's fingerprint removal) and on again does. The two operations, and `available`, need the matching Omarchy change before this file ships. `omarchy-mac-touchid-activate.service` (`lib/touchid-activate`) runs only on the owner's record, so it never opens a driver something else loaded without agreement (fprintd still opens `/dev/sep-bio` when it probes its readers, so on a kernel with omacom/linux-aurora#180, which loads the driver on every Mac, fprintd's allowance for the node needs the same gate first), and writes `/run/omarchy-mac/touchid`, `0644` so the session user can read it, and only when all four of the Secure Enclave driver's `diag` attributes say Touch ID can enrol and match, as the driver's ABI document asks: `touchid` reads `ready`, `sensor_attach` reads `attached`, `restore` reads `restored` or `empty`, and `matching` reads `usable` or `unverified`. `diag/touchid` alone can read `ready` while the sensor is uncalibrated, the enrolled fingerprints are unproven, or the xART guard blocks a match, as on a cold-booting M1-family Mac, and the invitation that follows comes only once. Anything else writes the reason instead (`failed`, `not-ready`, `unproven` or `blocked`) and says why in the unit's journal. Touch ID activates only on the first open of `/dev/sep-bio`, so `94-omarchy-mac-touchid.rules` starts the unit, which opens it once, read-only, as soon as the kernel publishes it; nothing needs enabling. The kernel activates Touch ID inside that open, and activation lasts the rest of the boot after the close. So does a failed activation, so the unit opens the node only once the kernel has made this Mac's keybag, `/var/lib/aurora-sep-keybag.bin`. The node takes one opener at a time, so a node `fprintd` holds is already activated. The attach retries once about 10 s after a short fall, so the script waits until 45 s after it starts for a settled answer, and `TimeoutStartSec=60s` bounds an open that blocks. A missing attribute ends it at once. An update runs it again, and a `ready` from earlier in the boot stands while `sensor_attach` reads `attached`, unless a final failure (`failed`, `unproven` or `blocked`) appears, since `diag/touchid` follows every later bring-up and one can fall short and recover. On the install or update that brings the rule, `/dev/sep-bio` already exists and no add event comes, and the boot-time status unit hasn't run on the update that first installs it, so `90-omarchy-mac-touchid.hook` starts the status unit and then the activation after the transaction, and the same session's post-update check sees the result. On a Mac with no agreement, that status run records `available` and the activation is skipped, whatever loaded the driver, unless Touch ID failed to come up earlier that boot: a reason that failure recorded (`failed`, `not-ready`, `unproven` or `blocked`) stands until a restart, and setup says to restart. The hook is skipped in a chroot, which includes `pacman --root`, or an unbooted root, and never fails the transaction: a unit that fails says why in its journal. The post-update fingerprint invitation then reaches the owner, and the fingerprint setup installs `libfprint-git`, whose aarch64 build carries the Touch ID driver (omacom/omarchy-pkgs#806) and owns `fprintd`'s allowance for `/dev/sep-bio`. systemd resolves that allowance when `fprintd` starts, so the drop-in `fprintd.service.d/50-omarchy-mac-touchid.conf` orders `fprintd` after `omarchy-mac-touchid-wait.service`, which follows the boot-time load, waits up to 15 s for the node where the Secure Enclave driver has a device and returns at once on a Mac without one, and after the activation, so `fprintd` never takes the node while the activation holds it: when both start together, at boot or from the pacman hook, `fprintd` waits for the activation, up to 60 s on a Mac whose attach is still settling. It adds no allowance of its own, and it's inert until Omarchy's setup installs `fprintd`. No sleep hook: the kernel ends a capture before suspend, and on a MacBook Neo the lock screen took the finger on the first touch after resume. Ship this file only once a boot without `aurora-touchid` shows enrolment, verification and suspend working, which still needs: Omarchy's `enable-fingerprint` and `disable-fingerprint` operations and their calls from the fingerprint setup and removal, since `apple-sep` is a module (`APPLE_SEP=m`: built in, it probes before udev has made the iBoot System Container's partition link and fails without retrying) with no modalias, which loads only on the owner's record; and m1n1 that forwards `/chosen/apfs-preboot-uuid`, which selects this install's own lane in the Secure Enclave. Keep that source stable: changing it (boot entries with and without `apple_sep.os_uuid_hi`/`os_uuid_lo`, or a stub reinstall) orphans the Linux enrolments. Without all of that the invitation, which comes once, leads to a setup that cannot finish. The script follows the aurora kernel's naming (the `apple_sep` driver and its `diag` attributes): a kernel that renames them stops the invitation without an error, so move the script together with the kernel pin. +- `fingerprint-readers`: Touch ID. `omarchy-hw-fingerprint` finds the sensor once `/run/omarchy-mac/touchid` reads `ready`, or `available` before the owner has turned it on. Nothing loads the Secure Enclave driver until the owner agrees. At boot, `omarchy-mac-touchid-status.service` (`lib/touchid-status`, pulled in by the package's `multi-user.target.wants` link, before the greeter and `fprintd`) asks `lib/touchid-eligibility`, which reads only the device tree and installed files: `available` needs a sensor node, a board the aurora driver has a profile for (M2, M2 Pro and Max, the M3 Air J613 and J615, and the MacBook Neo; M1-family Macs wait for their xART guard path), `/chosen/apfs-preboot-uuid`, a way to the calibration (under the name the sensor's `firmware-name` gives, `apple/mesacal-.bin`, or `apple/mesa_calibration.bin` on M2 Pro and Max) and, on the Neo, a way to the sensor root key, an installed one or the factory records on the ESP with `python` to rebuild it from (the extractors need `python`, which linux-aurora only suggests), and an Omarchy whose `omarchy-lifecycle-dispatch` resolves `enable-fingerprint`, since the invitation comes once and an older setup would enrol a reader nothing turned on; anything else records `unsupported:`, which no detector line names. Omarchy's fingerprint setup then runs `omarchy-lifecycle-dispatch enable-fingerprint` (`entrypoints/enable-fingerprint`, as root) before enrolling. With no status file (a Mac without a sensor records nothing, and a status service can fail) it works eligibility out again. Where Touch ID can't be set up it lets the setup go on, so a USB reader enrols on a Mac mini, a Studio or an M1 Mac as it would without Touch ID. A Mac whose owner already agreed is never asked again: it gets any missing options and, unless Touch ID reads `ready`, is told to restart, and the setup goes on. It stops the setup only when the owner says no, or turning Touch ID on or writing its options fails. It says in three lines that Touch ID is experimental and can be unstable, that it shares the Secure Enclave with macOS so macOS should be backed up first, and that the Mac manual has the details, then adds four lines about SDDM re-login, empty passwords, accounts without a password and custom PAM policy before asking. The manual's Encryption and passwords page carries the rest: the key store Linux creates stays, the enclave's anti-replay state moves forward and is one file in the iBoot System Container that macOS updates too, and a bug that writes it wrongly can cost macOS data (with FileVault on, macOS won't start and the Mac needs a DFU restore; with FileVault off, macOS resets its keychain and fingerprints). FileVault's state isn't checked: the owner can change it after installing, so the manual names both cases. On yes, `lib/touchid-enable` carves what is missing from this Mac's own iBoot System Container into `/usr/lib/firmware/updates` (the calibration with linux-aurora's `extract-mesa-calibration`, except on the Neo, whose installer writes the sealed form; the Neo's `apple/msrk-j700.bin`, root-only `0600`, rebuilt with `lib/touchid-root-key`), records the agreement in `/etc/omarchy-mac/touchid-on` and in the driver's options (`/etc/modprobe.d/omarchy-mac-touchid.conf`: `xart_writes=1 provision_keybag=1`, today's defaults, which a kernel that loads `apple_sep` read-only by default, omacom/linux-aurora#180, writes only with; the name sorts after `apple-sep.conf`, so the owner's agreement wins over any `apple-sep.conf`, while `apple_sep.xart_writes=0` on the kernel command line still wins over both, and no initramfs hook includes `apple_sep`, so only the root's copy of the options is read), loads `apple-sep` now (a driver already running keeps the options it loaded with, so on a kernel that loads it read-only, and a Mac with no key store yet, the agreement stands and Touch ID turns on after a restart), and succeeds only once the activation records `ready`, restarting an `fprintd` that started without the reader; a failure after the record is written removes it again, so the next boot offers Touch ID again instead of loading a driver that never came up. A driver that loaded but never came up stays that way until a restart, so the status then reads `failed` and setup doesn't offer Touch ID again that boot; when `/dev/sep-bio` or the keybag never appeared, the activation never ran, and the error points to `journalctl -k`, the driver's own log. While the record exists, `omarchy-mac-touchid-load.service` (pulled in by a `multi-user.target.wants` link) loads `apple-sep` at every boot once `udevadm wait` sees `/dev/disk/by-partlabel/iBootSystemContainer`, since the driver opens that link as it probes and does not retry, and before the greeter and `fprintd`. The wait is part of the service rather than a device dependency, because systemd waits for a unit's devices before it checks its condition: a dependency would hold up every boot, agreed or not, and the greeter on a machine without the partition until the device timed out. A key store from an earlier load (`/var/lib/aurora-sep-keybag.bin`) is not agreement: that owner never saw this text, so they are asked too, told that the existing key store is used. `omarchy-lifecycle-dispatch disable-fingerprint`, after the fingerprints are deleted, removes the record and the options, so the driver stops loading from the next boot and the status offers Touch ID again; the key store stays. A record or options that can't be written, or removed, fails the operation rather than reporting success, and a carved calibration, like the sensor key, takes its name only once it is whole. On a kernel with omacom/linux-aurora#180, udev loads `apple_sep` on every Mac, read-only unless the options file exists, and a read-only driver always reports `matching` as `blocked`. The activation runs only on the owner's record, so a Mac whose owner hasn't agreed, or turned Touch ID off, keeps the boot's `available` and is offered Touch ID; and `enable-fingerprint` writes the options for a Mac agreed before they existed whatever its status, so one that reads `blocked` reaches `ready` after a restart. The Neo's sensor key (`apple/msrk-j700.bin`) is device-private, so nothing reads it before the owner agrees. asahi-installer copies this Mac's factory records (`com.apple.factorydata`) into the ESP's fallback firmware archive, `asahi/all_firmware.tar.gz`, on every install; an image install mounts the ESP at `/boot/efi` with `umask=0077`, so only root can read it there, and that mount is where the archive is read; on yes, `lib/touchid-root-key` (Python's standard library only) reads the `MSRk`, `seal` and trust bundle records from it in memory, rebuilds the key as omarchy-mac-installer's `factory_root_key()` does on macOS (the `MSRk` record's `IM4P` under the FDR sealing manifest, with the trust bundle as `secb`), checks its envelope, and refuses records that aren't all found byte for byte in this Mac's own iBoot System Container, so an archive from another Mac, or one swapped on the ESP, gives no key. It writes the key root-only (`0600`) under a temporary name, synced, then renames it. Nothing is kept when the owner says no, and a yes that then fails to turn Touch ID on takes back the key it rebuilt along with the agreement; `disable-fingerprint` deletes the installed key, and the next yes rebuilds it. A factory reset gives the factory root no key, since the ESP survives it and the next owner's yes rebuilds it. Every Neo install has the archive, since upstream asahi-installer writes it on every install, so none needs the installer to collect the key. A Neo without the archive (removed by hand) or without `python` reads `unsupported:no-root-key`; the boot status looks for the archive, so `omarchy-mac-touchid-status.service` runs after `boot-efi.mount`. Carved files under `/usr/lib/firmware/updates` belong to no package, so a root rollback can remove them. An agreed Mac isn't asked again, so its setup doesn't carve them back: turning Touch ID off (Omarchy's fingerprint removal) and on again does. The two operations, and `available`, need the matching Omarchy change before this file ships. `omarchy-mac-touchid-activate.service` (`lib/touchid-activate`) runs only on the owner's record, so it never opens a driver something else loaded without agreement (fprintd still opens `/dev/sep-bio` when it probes its readers, so on a kernel with omacom/linux-aurora#180, which loads the driver on every Mac, fprintd's allowance for the node needs the same gate first), and writes `/run/omarchy-mac/touchid`, `0644` so the session user can read it, and only when all four of the Secure Enclave driver's `diag` attributes say Touch ID can enrol and match, as the driver's ABI document asks: `touchid` reads `ready`, `sensor_attach` reads `attached`, `restore` reads `restored` or `empty`, and `matching` reads `usable` or `unverified`. `diag/touchid` alone can read `ready` while the sensor is uncalibrated, the enrolled fingerprints are unproven, or the xART guard blocks a match, as on a cold-booting M1-family Mac, and the invitation that follows comes only once. Anything else writes the reason instead (`failed`, `not-ready`, `unproven` or `blocked`) and says why in the unit's journal. Touch ID activates only on the first open of `/dev/sep-bio`, so `94-omarchy-mac-touchid.rules` starts the unit, which opens it once, read-only, as soon as the kernel publishes it; nothing needs enabling. The kernel activates Touch ID inside that open, and activation lasts the rest of the boot after the close. So does a failed activation, so the unit opens the node only once the kernel has made this Mac's keybag, `/var/lib/aurora-sep-keybag.bin`. The node takes one opener at a time, so a node `fprintd` holds is already activated. The attach retries once about 10 s after a short fall, so the script waits until 45 s after it starts for a settled answer, and `TimeoutStartSec=60s` bounds an open that blocks. A missing attribute ends it at once. An update runs it again, and a `ready` from earlier in the boot stands while `sensor_attach` reads `attached`, unless a final failure (`failed`, `unproven` or `blocked`) appears, since `diag/touchid` follows every later bring-up and one can fall short and recover. On the install or update that brings the rule, `/dev/sep-bio` already exists and no add event comes, and the boot-time status unit hasn't run on the update that first installs it, so `90-omarchy-mac-touchid.hook` starts the status unit and then the activation after the transaction, and the same session's post-update check sees the result. On a Mac with no agreement, that status run records `available` and the activation is skipped, whatever loaded the driver, unless Touch ID failed to come up earlier that boot: a reason that failure recorded (`failed`, `not-ready`, `unproven` or `blocked`) stands until a restart, and setup says to restart. The hook is skipped in a chroot, which includes `pacman --root`, or an unbooted root, and never fails the transaction: a unit that fails says why in its journal. The post-update fingerprint invitation then reaches the owner, and the fingerprint setup installs `libfprint-git`, whose aarch64 build carries the Touch ID driver (omacom/omarchy-pkgs#806) and owns `fprintd`'s allowance for `/dev/sep-bio`. systemd resolves that allowance when `fprintd` starts, so the drop-in `fprintd.service.d/50-omarchy-mac-touchid.conf` orders `fprintd` after `omarchy-mac-touchid-wait.service`, which follows the boot-time load, waits up to 15 s for the node where the Secure Enclave driver has a device and returns at once on a Mac without one, and after the activation, so `fprintd` never takes the node while the activation holds it: when both start together, at boot or from the pacman hook, `fprintd` waits for the activation, up to 60 s on a Mac whose attach is still settling. It adds no allowance of its own, and it's inert until Omarchy's setup installs `fprintd`. No sleep hook: the kernel ends a capture before suspend, and on a MacBook Neo the lock screen took the finger on the first touch after resume. Ship this file only once a boot without `aurora-touchid` shows enrolment, verification and suspend working, which still needs: Omarchy's `enable-fingerprint` and `disable-fingerprint` operations and their calls from the fingerprint setup and removal, since `apple-sep` is a module (`APPLE_SEP=m`: built in, it probes before udev has made the iBoot System Container's partition link and fails without retrying) with no modalias, which loads only on the owner's record; and m1n1 that forwards `/chosen/apfs-preboot-uuid`, which selects this install's own lane in the Secure Enclave. Keep that source stable: changing it (boot entries with and without `apple_sep.os_uuid_hi`/`os_uuid_lo`, or a stub reinstall) orphans the Linux enrolments. Without all of that the invitation, which comes once, leads to a setup that cannot finish. The script follows the aurora kernel's naming (the `apple_sep` driver and its `diag` attributes): a kernel that renames them stops the invitation without an error, so move the script together with the kernel pin. - `keyrings`: `asahi-alarm-keyring`, the signing keyring of the `[asahi-alarm]` repository. `omarchy update` reinstalls every installed keyring this file names, with Arch Linux ARM's, before the system upgrade, so an Asahi key rotation never fails that upgrade's signature checks. omarchy-mac is the platform package on Apple Silicon: the recipe declares `provides=('omarchy-platform')` and `conflicts=('omarchy-platform')`, so only one platform package owns the root. Nothing may depend on `omarchy-platform`: the provide exists for the conflict, and a dependency on it could pull this package onto another machine. @@ -39,6 +39,32 @@ The logind drop-in `/usr/lib/systemd/logind.conf.d/20-omarchy-mac-sleep-key.conf Vendor defaults use NetworkManager's `/usr/lib/NetworkManager/conf.d`, systemd's `/usr/lib/systemd` and `/usr/lib/tmpfiles.d`, modprobe's `/usr/lib/modprobe.d`, and WirePlumber's `/usr/share/wireplumber/wireplumber.conf.d`. Same-name `/etc` or user fragments retain precedence. iwd has no vendor directory, so an `iwd.service` drop-in lists `/usr/lib/omarchy-mac/iwd` after `/etc/iwd`; iwd loads the first `main.conf` it can read, so an `/etc/iwd/main.conf` replaces the Apple one whole. The Apple default keeps iwd off 6 GHz: on the BCM4388 a join the firmware makes to a 6 GHz access point reports connected and authorized, yet the access point drops everything the Mac sends and DHCP never completes, so a network that also offers 5 GHz joins there instead. The firmware's own roaming can still move a weak connection onto 6 GHz, and `omarchy network band 6` cannot reach 6 GHz. On the MT7932, NetworkManager's own autoconnect replaces iwd's (`wifi.iwd.autoconnect=false`, matched by driver): after the firmware rejects a connect, iwd stops autoconnecting and nothing else would retry. Like the backend, the iwd default applies when iwd next starts: setup restarts nothing, so an upgraded Mac keeps 6 GHz until it reboots. Setup reports effective live NetworkManager/module configuration and systemd fragments. Review those reports and any drop-ins when diagnosing overrides; custom policy is never normalized to the package default. +## J715 Touch ID + +J715 (the 15-inch M4 Air, `apple,j715` and `apple,t8132`) additionally needs a kernel with the J715 nonce-session support and this Mac's own installed 10848-byte FDR MSRk body at `apple/msrk-j715.bin`. Its FSC2 calibration must already be installed under the sensor node's `firmware-name`, or `apple/mesa_calibration.bin` when the node omits it. There is no automatic extraction path for this board: the older calibration carve and the Neo's root-key envelope are not substitutes. Eligibility checks that every present J715 key candidate is regular, readable and 10848 bytes using file metadata, without reading or copying the key. A malformed shadow in any firmware lookup directory refuses eligibility. Enablement checks the existing body's observed size again before it records consent or loads the driver. A length check does not authenticate the body: it must already have been acquired and verified for this Mac, and the enclave decides whether to accept it. Keep the key root-only. This package neither distributes private factory data nor recreates or resets existing enrollments. + +For J715, eligibility requires every present calibration candidate to be readable and 130427 bytes, the size observed working on one reference Mac. The comparison with an earlier failure was not a controlled A/B test. This deliberately rejects other sizes until they are tested. Size alone does not prove that a body is complete, authentic or this Mac's own. + +The existing consent-gated boot service loads the driver before the display manager and fprintd. Its failure does not prevent password login. An already enrolled fingerprint still needs the driver's successful restore and matching diagnostics on the new boot. Same-boot enrollment alone does not prove that. + +## Touch ID at the SDDM login screen + +Where SDDM is installed, enabling Touch ID also adds an authentication include to its stock `system-login` PAM stack. This applies on every supported board. The include preserves shell, nologin and account-lock checks. It copies the lockout options (`silent`, `deny=`, `unlock_time=`, `fail_interval=`) from the system's `system-auth`, so Omarchy's limits apply, and refuses any other option or rule there as administrator-owned. Account, password and session management remain the original SDDM configuration. + +An empty password asks for a fingerprint. Any other password skips the fingerprint and goes straight to the original password stack, so a greeter can start fingerprint requests on its own and still accept a typed password. An account with no password cannot log in at SDDM while Touch ID is on, since its empty password is read as a fingerprint request. + +The fingerprint requires both a live user session bus and a privileged login marker from this boot. An SDDM PAM session hook creates `/run/omarchy-mac/touchid-logins/` after authentication and account checks; the marker survives logout but not reboot. A lingering user manager alone is not login proof, so the first interactive SDDM login each boot uses the password. It is also never offered while a login keyring may be locked. If the running keyring lists a `login` collection, as on omarchy-mx-mac, that collection must be unlocked. Otherwise, whether the keyring is stopped or running without a `login` collection, the user must have no `login.keyring` file in `~/.local/share/keyrings` or the legacy `~/.gnome2/keyrings`, since a keyring from that file may be locked. File lookups run with the user's credentials, including supplementary groups; only confirmed absence passes, and permission errors or other checks that cannot finish refuse. + +On omacom/omarchy, which removes `pam_gnome_keyring` from SDDM and uses a passwordless `Default_keyring`, there is no login keyring, so the fingerprint is offered. There Touch ID is a re-login feature. Automatic login does not run this SDDM session hook: after an automatic login, the first interactive SDDM screen still needs the password to establish login proof. Later screens accept a fingerprint while the user's bus survives. Enabling or upgrading the policy during an existing session also requires a password login before fingerprints are offered. + +A fingerprint request ends after five seconds or three rejected fingers without trying the empty password. Rejections count toward the account lock and an accepted finger clears the count, as a password login does. The lockout options are copied when Touch ID setup runs, so after a change to the `pam_faillock` options in `system-auth`, run fingerprint setup again to carry them into the SDDM policy. + +The helper refuses custom authentication rules, symlinks and edited owned policy rather than overwriting them. The SDDM step is best effort: when the helper refuses, setup says so and fingerprint enrollment goes on with the login screen unchanged. Only a Mac whose owner agreed through the prompt that names the SDDM login screen gets the change. That agreement is recorded in `/etc/omarchy-mac/touchid-sddm`, so a Mac that agreed earlier is not changed unasked. Disabling Touch ID removes that record, removes only its own include and restores the original bytes. An `sddm` file that does not include the policy, a symlink included, never blocks removal. No SDDM restart is needed. Fingerprint login does not unlock a password-encrypted keyring or the LUKS root volume. + +If administrator-owned PAM configuration prevents removal of the include, disabling still removes the boot consent and driver options, but reports failure so the remaining PAM policy can be reviewed. It does not unload a driver that is already running. + +The earlier J715 port has restored an existing Linux enrollment after a complete shutdown and power-on and completed an SDDM fingerprint login. That login predates the keyring check and still needed a separate keyring unlock. This does not qualify the current upstream kernel or concurrent camera operation. The offline PAM tests exercise libpam itself, including password fallback and denied accounts, but they do not replace hardware checks on the matching kernel. Release this support only after that kernel and the userspace driver are available and qualified together. + ## Video decode in mpv mpv has no vendor configuration directory and decodes in software unless told otherwise. The package ships its Apple default as `/usr/share/omarchy-mac/mpv/mpv.conf` and a systemd-tmpfiles rule that copies it to `/etc/mpv/mpv.conf` only when that file is missing. pacman's systemd hook applies the rule when the package is installed or upgraded, and boot applies it again. An existing `/etc/mpv/mpv.conf` is never overwritten, with one exception: `omarchy-mac-setup-system` replaces a regular file byte-identical to the earlier default, which lacks `gpu-sw=yes`, with the current default, and leaves an edited copy or a link alone. An upgrade alone does not apply this, because neither `omarchy update` nor a pacman upgrade runs setup: run `sudo omarchy-mac-setup-system`, or rerun hardware setup, to apply it. So edit it rather than delete it to change the system default; each user's `~/.config/mpv/mpv.conf` is read after it and wins, and `hwdec=no` there decodes in software. diff --git a/omarchy-mac/entrypoints/disable-fingerprint b/omarchy-mac/entrypoints/disable-fingerprint index ee308528..7b2e5bef 100755 --- a/omarchy-mac/entrypoints/disable-fingerprint +++ b/omarchy-mac/entrypoints/disable-fingerprint @@ -16,13 +16,18 @@ elif ! flock -w 300 "$lock_fd"; then exit 1 fi +pam_status=0 +if ! /usr/lib/omarchy-mac/touchid-sddm disable; then + pam_status=1 + echo "Touch ID's SDDM policy could not be removed; an administrator must review it." >&2 +fi key=/usr/lib/firmware/updates/apple/msrk-j700.bin -if [[ -e /etc/omarchy-mac/touchid-on || -e /etc/modprobe.d/omarchy-mac-touchid.conf || -e $key || -e $key.new ]]; then +if [[ -e /etc/omarchy-mac/touchid-on || -e /etc/omarchy-mac/touchid-sddm || -e /etc/modprobe.d/omarchy-mac-touchid.conf || -e $key || -e $key.new ]]; then # A record left behind, on a read-only root say, loads the driver again. - if ! rm -f /etc/omarchy-mac/touchid-on /etc/modprobe.d/omarchy-mac-touchid.conf "$key" "$key.new"; then - echo "Touch ID could not be turned off: remove /etc/omarchy-mac/touchid-on, /etc/modprobe.d/omarchy-mac-touchid.conf and $key" >&2 + if ! rm -f /etc/omarchy-mac/touchid-on /etc/omarchy-mac/touchid-sddm /etc/modprobe.d/omarchy-mac-touchid.conf "$key" "$key.new"; then + echo "Touch ID could not be turned off: remove /etc/omarchy-mac/touchid-on, /etc/omarchy-mac/touchid-sddm, /etc/modprobe.d/omarchy-mac-touchid.conf and $key" >&2 exit 1 fi echo "Touch ID stops loading at the next boot. The key store for Linux stays on this Mac." fi -exit 0 +exit "$pam_status" diff --git a/omarchy-mac/entrypoints/enable-fingerprint b/omarchy-mac/entrypoints/enable-fingerprint index 4134c470..8f82b41d 100755 --- a/omarchy-mac/entrypoints/enable-fingerprint +++ b/omarchy-mac/entrypoints/enable-fingerprint @@ -16,27 +16,25 @@ if [[ -e /etc/omarchy-mac/touchid-on ]]; then # whatever its status: on a kernel that loads the driver read-only, the # options are what lets it reach ready after a restart. options=/etc/modprobe.d/omarchy-mac-touchid.conf - if [[ ! -e $options ]]; then - # Under the Touch ID lock, so a removal running now can't be undone here. - lock=/run/omarchy-mac/touchid.lock - if ! { mkdir -p -m 0755 "${lock%/*}" && exec {lock_fd}>>"$lock"; } 2>/dev/null; then - echo "Touch ID's driver options could not be written: its lock, $lock, could not be opened." >&2 - exit 1 - elif ! flock -w 300 "$lock_fd"; then - echo "Touch ID's driver options could not be written: another Touch ID setup or removal is still running." >&2 - exit 1 - fi - if [[ ! -e /etc/omarchy-mac/touchid-on ]]; then - echo "Touch ID was turned off while this ran, so setup goes on without it." - exit 0 - elif [[ ! -e $options ]]; then - { mkdir -p -m 0755 "${options%/*}" && - printf '%s\n' "# The owner turned on Touch ID; omarchy-mac's disable-fingerprint removes this." \ - "options apple_sep xart_writes=1 provision_keybag=1" >"$options.new" && - chmod 0644 "$options.new" && mv -fT "$options.new" "$options"; } || - { rm -f "$options.new" 2>/dev/null; echo "Touch ID's driver options could not be written to $options" >&2; exit 1; } - fi - exec {lock_fd}>&- + # Options and login policy share the setup/removal lock, so a removal + # running now can't be undone here. + lock=/run/omarchy-mac/touchid.lock + if ! { mkdir -p -m 0755 "${lock%/*}" && exec {lock_fd}>>"$lock"; } 2>/dev/null; then + echo "Touch ID's driver options could not be written: its lock, $lock, could not be opened." >&2 + exit 1 + elif ! flock -w 300 "$lock_fd"; then + echo "Touch ID's driver options could not be written: another Touch ID setup or removal is still running." >&2 + exit 1 + fi + if [[ ! -e /etc/omarchy-mac/touchid-on ]]; then + echo "Touch ID was turned off while this ran, so setup goes on without it." + exit 0 + elif [[ ! -e $options ]]; then + { mkdir -p -m 0755 "${options%/*}" && + printf '%s\n' "# The owner turned on Touch ID; omarchy-mac's disable-fingerprint removes this." \ + "options apple_sep xart_writes=1 provision_keybag=1" >"$options.new" && + chmod 0644 "$options.new" && mv -fT "$options.new" "$options"; } || + { rm -f "$options.new" 2>/dev/null; echo "Touch ID's driver options could not be written to $options" >&2; exit 1; } fi # The owner agreed already, so they are never asked again: a Touch ID that # isn't ready yet needs a restart, and setup goes on with any other reader. @@ -44,7 +42,11 @@ if [[ -e /etc/omarchy-mac/touchid-on ]]; then echo "Touch ID is turned on but isn't ready yet ($recorded_status)." echo "Restart this Mac, then set up the fingerprint again. If it still isn't" echo "ready, see journalctl -u omarchy-mac-touchid-activate." + elif [[ -e /etc/omarchy-mac/touchid-sddm ]] && ! /usr/lib/omarchy-mac/touchid-sddm enable; then + # Only an owner who was told about the login screen gets it, and it never stops setup. + echo "Touch ID's SDDM login was left as it is: its PAM configuration is not one this package manages." >&2 fi + exec {lock_fd}>&- exit 0 fi # Only a Touch ID that can be set up stops the setup: anywhere else it goes on, @@ -69,6 +71,11 @@ echo "Touch ID on Linux is experimental and can be unstable. It shares this Mac' echo "Secure Enclave with macOS, so back up any data on your macOS partition first." echo "The Mac manual's Encryption and passwords page has the details." echo +echo "On a stock SDDM login screen, fingerprints also work when you log in" +echo "again later in a boot: submit an empty password, then touch the sensor." +echo "A typed password always works, but an account with no password can no" +echo "longer log in there. A custom SDDM PAM configuration is kept." +echo read -r -p "Turn on Touch ID? [y/N] " answer || answer="" if [[ $answer == [yY] || $answer == [yY][eE][sS] ]]; then exec /usr/lib/omarchy-mac/touchid-enable diff --git a/omarchy-mac/lib/touchid-eligibility b/omarchy-mac/lib/touchid-eligibility index f778ce0c..e273a754 100755 --- a/omarchy-mac/lib/touchid-eligibility +++ b/omarchy-mac/lib/touchid-eligibility @@ -51,7 +51,8 @@ if compatible apple,t8103 || compatible apple,t6000 || compatible apple,t6001; t echo unsupported:m1-family exit 0 elif ! compatible apple,t8112 && ! compatible apple,t6020 && ! compatible apple,t6021 && ! compatible apple,t8140 && - ! { compatible apple,t8122 && { compatible apple,j613 || compatible apple,j615; }; }; then + ! { compatible apple,t8122 && { compatible apple,j613 || compatible apple,j615; }; } && + ! { compatible apple,t8132 && compatible apple,j715; }; then echo unsupported:board exit 0 fi @@ -68,10 +69,24 @@ calibration=apple/mesa_calibration.bin if [[ -r $sensor/firmware-name ]]; then calibration=$(tr -d '\0' <"$sensor/firmware-name") fi -if ! installed "$calibration" && { compatible apple,t8140 || ! can_extract extract-mesa-calibration; }; then +if ! installed "$calibration" && { compatible apple,t8140 || compatible apple,t8132 || ! can_extract extract-mesa-calibration; }; then echo unsupported:no-calibration exit 0 fi +# A 130427-byte J715 FSC2 body worked on one reference Mac. +# Size rejects other-sized inputs, not another Mac's or forged data. +# Check every lookup candidate so a good copy cannot hide a malformed shadow. +if compatible apple,t8132; then + for directory in "$firmware" "$firmware/vendor" "$firmware/updates"; do + calibration_path=$directory/$calibration + if [[ -e $calibration_path || -L $calibration_path ]]; then + if [[ ! -f $calibration_path || ! -r $calibration_path ]] || [[ $(wc -c <"$calibration_path") != 130427 ]]; then + echo unsupported:invalid-calibration + exit 0 + fi + fi + done +fi # The Neo's sensor key is rebuilt once the owner agrees, by touchid-root-key # (Python), from the factory records asahi-installer leaves on the ESP. if compatible apple,t8140 && ! installed apple/msrk-j700.bin && @@ -79,4 +94,23 @@ if compatible apple,t8140 && ! installed apple/msrk-j700.bin && echo unsupported:no-root-key exit 0 fi +# J715 needs its own FDR MSRk and FSC2, not the Neo's reconstructed key or +# the older calibration an extractor can find in the system container. +if compatible apple,t8132; then + found=0 + for directory in "$firmware" "$firmware/vendor" "$firmware/updates"; do + key=$directory/apple/msrk-j715.bin + if [[ -e $key || -L $key ]]; then + if [[ ! -f $key || ! -r $key ]] || [[ $(stat -Lc %s -- "$key" 2>/dev/null) != 10848 ]]; then + echo unsupported:invalid-root-key + exit 0 + fi + found=1 + fi + done + if (( ! found )); then + echo unsupported:no-root-key + exit 0 + fi +fi echo available diff --git a/omarchy-mac/lib/touchid-enable b/omarchy-mac/lib/touchid-enable index a570c45c..c88c5988 100755 --- a/omarchy-mac/lib/touchid-enable +++ b/omarchy-mac/lib/touchid-enable @@ -7,6 +7,7 @@ tree=${OMARCHY_MAC_TOUCHID_TREE:-/proc/device-tree} firmware=${OMARCHY_MAC_TOUCHID_FIRMWARE:-/usr/lib/firmware} extractors=${OMARCHY_MAC_TOUCHID_EXTRACTORS:-/usr/lib/linux-aurora} agreed=${OMARCHY_MAC_TOUCHID_AGREED:-/etc/omarchy-mac/touchid-on} +sddm_agreed=${OMARCHY_MAC_TOUCHID_SDDM_AGREED:-/etc/omarchy-mac/touchid-sddm} options=${OMARCHY_MAC_TOUCHID_OPTIONS:-/etc/modprobe.d/omarchy-mac-touchid.conf} module=${OMARCHY_MAC_TOUCHID_MODULE:-/sys/module/apple_sep} status_file=${OMARCHY_MAC_TOUCHID_STATUS:-/run/omarchy-mac/touchid} @@ -21,6 +22,10 @@ container=${OMARCHY_MAC_TOUCHID_CONTAINER:-/dev/disk/by-partlabel/iBootSystemCon python=${OMARCHY_MAC_TOUCHID_PYTHON:-python3} lock_wait=${OMARCHY_MAC_TOUCHID_LOCK_WAIT:-300} omarchy-hw-apple-silicon || exit 0 +j715=0 +if tr '\0' '\n' <"$tree/compatible" | grep -Fxq apple,t8132; then + j715=1 +fi # Once this run records the agreement, a failure takes it back, so a Touch ID # that never came up doesn't load at every boot and is offered again after a @@ -29,7 +34,7 @@ recorded=0 rebuilt=0 fail() { if (( recorded )); then - rm -f "$agreed" "$options" + rm -f "$agreed" "$sddm_agreed" "$options" fi if (( rebuilt )); then rm -f "$firmware/updates/apple/msrk-j700.bin" @@ -87,6 +92,18 @@ fi eligibility=$("$helpers/touchid-eligibility") [[ $eligibility == "available" ]] || fail "this Mac can't use it yet ($eligibility)" +if (( j715 )); then + found=0 + for directory in "$firmware" "$firmware/vendor" "$firmware/updates"; do + key=$directory/apple/msrk-j715.bin + if [[ -e $key ]]; then + [[ -f $key && -r $key && $(wc -c <"$key") == 10848 ]] || + fail "this Mac's FDR sensor key at $key must be a readable 10848-byte body" + found=1 + fi + done + (( found )) || fail "this Mac's own FDR sensor key must be installed before enabling Touch ID" +fi # Factory data from this Mac's own iBoot System Container, never another's. sensor=$("$helpers/touchid-eligibility" sensor) @@ -124,6 +141,9 @@ fi { mkdir -p -m 0755 "${agreed%/*}" && printf '%s\n' "# The owner turned on Touch ID; omarchy-mac's disable-fingerprint removes this." >"$agreed" && chmod 0644 "$agreed"; } || fail "the owner's agreement could not be recorded in $agreed" +# The prompt told the owner that SDDM's login screen takes fingerprints too. +{ printf '%s\n' "# The owner agreed to Touch ID at SDDM's login; omarchy-mac's disable-fingerprint removes this." >"$sddm_agreed" && + chmod 0644 "$sddm_agreed"; } || fail "the owner's agreement to the SDDM login could not be recorded in $sddm_agreed" # The driver's options say so too. Today's kernels write by default, so this # changes nothing yet; a kernel that loads apple_sep read-only by default # (omacom/linux-aurora#180) writes only with it. A driver already running @@ -157,6 +177,9 @@ if [[ $(cat "$status_file" 2>/dev/null) == "ready" ]]; then # An fprintd that started without the reader found none and kept no # allowance for its node, so it starts again with both. systemctl try-restart fprintd.service 2>/dev/null + if ! "$python" -I "$helpers/touchid-sddm" enable; then + echo "Touch ID is on, but SDDM's PAM configuration is not one this package manages, so its login screen is unchanged." >&2 + fi echo "Touch ID is on." exit 0 elif (( preloaded )); then diff --git a/omarchy-mac/lib/touchid-pam-empty-password b/omarchy-mac/lib/touchid-pam-empty-password new file mode 100755 index 00000000..75419fb5 --- /dev/null +++ b/omarchy-mac/lib/touchid-pam-empty-password @@ -0,0 +1,11 @@ +#!/bin/bash +# pam_exec expose_authtok helper: succeed only when the greeter sent an empty +# password, which is how it asks for Touch ID. Reads all input so pam_exec never +# writes to a closed pipe; the password is never stored or printed. +password= +IFS= read -r -d '' password || true +if omarchy-hw-apple-silicon && [[ -z $password ]]; then + exit 0 +else + exit 1 +fi diff --git a/omarchy-mac/lib/touchid-pam-keyring-unlocked b/omarchy-mac/lib/touchid-pam-keyring-unlocked new file mode 100755 index 00000000..2adcdd25 --- /dev/null +++ b/omarchy-mac/lib/touchid-pam-keyring-unlocked @@ -0,0 +1,133 @@ +#!/usr/bin/python3 -I +# SPDX-License-Identifier: MIT +"""Succeed only while PAM_USER's session bus is up and no login keyring is locked.""" + +import os +from pathlib import Path +import pwd +import stat +import subprocess +import sys + +RUNTIME = Path("/run/user") +LOGINS = Path("/run/omarchy-mac/touchid-logins") +SECRETS = "org.freedesktop.secrets" +SERVICE = "/org/freedesktop/secrets" +LOGIN = "/org/freedesktop/secrets/collection/login" +# gnome-keyring's files for the login collection: the XDG path, and the legacy +# one it falls back to when only that directory exists. +LOGIN_FILES = (".local/share/keyrings/login.keyring", ".gnome2/keyrings/login.keyring") + + +def prior_login(uid: int) -> bool: + """Trust only a marker in the privileged PAM helper's boot-local directory.""" + try: + directory = LOGINS.lstat() + marker = (LOGINS / str(uid)).lstat() + except OSError: + return False + return (stat.S_ISDIR(directory.st_mode) and stat.S_ISREG(marker.st_mode) + and directory.st_uid == marker.st_uid == os.geteuid() + and not (directory.st_mode | marker.st_mode) & 0o022) + + +def record_login(user: str) -> bool: + """Remember SDDM reaching open_session after authentication and account checks.""" + try: + uid = pwd.getpwnam(user).pw_uid + LOGINS.mkdir(mode=0o700, parents=True, exist_ok=True) + directory = LOGINS.lstat() + if (not stat.S_ISDIR(directory.st_mode) or directory.st_uid != os.geteuid() + or directory.st_mode & 0o022): + return False + try: + descriptor = os.open(LOGINS / str(uid), os.O_CREAT | os.O_EXCL | os.O_NOFOLLOW | os.O_WRONLY, 0o600) + except FileExistsError: + return prior_login(uid) + os.close(descriptor) + return True + except (KeyError, OSError): + return False + + +def no_login_keyring_files(home: Path) -> bool: + """Only ENOENT proves absence; run this lookup with the user's credentials.""" + for name in LOGIN_FILES: + try: + (home / name).stat() + except FileNotFoundError: + continue + except OSError: + return False + return False + return True + + +def unlocked(user: str, run=subprocess.run, runtime: Path = RUNTIME) -> bool: + try: + entry = pwd.getpwnam(user) + except KeyError: + return False + if not prior_login(entry.pw_uid): + return False + bus = runtime / str(entry.pw_uid) / "bus" + if not bus.is_socket(): + return False + command = ["/usr/bin/setpriv", f"--reuid={entry.pw_uid}", f"--regid={entry.pw_gid}", + "--init-groups", "--reset-env", "/usr/bin/busctl", + f"--address=unix:path={bus}", "--timeout=2"] + + def ask(*arguments: str) -> str | None: + try: + done = run([*command, *arguments], capture_output=True, text=True, + timeout=5, check=False) + except (OSError, subprocess.TimeoutExpired): + return None + return done.stdout.strip() if done.returncode == 0 else None + + # Asking whether the name has an owner never starts a stopped keyring. + owner = ask("call", "org.freedesktop.DBus", "/org/freedesktop/DBus", + "org.freedesktop.DBus", "NameHasOwner", "s", SECRETS) + + def no_login_keyring_file() -> bool: + # Checked as the user, so root never follows a path the user controls. + # Anything but a clean "neither file exists" refuses. + try: + done = run(["/usr/bin/setpriv", f"--reuid={entry.pw_uid}", f"--regid={entry.pw_gid}", + "--init-groups", "--reset-env", "/usr/bin/python3", "-I", __file__, + "no-login-keyring-files", entry.pw_dir], + timeout=5, check=False) + except (OSError, subprocess.TimeoutExpired): + return False + return done.returncode == 0 + + if owner == "b false": + return no_login_keyring_file() + if owner != "b true": + return False + collections = (ask("get-property", SECRETS, SERVICE, + "org.freedesktop.Secret.Service", "Collections") or "").split() + if collections[:1] != ["ao"]: + return False + if f'"{LOGIN}"' not in collections[2:]: + # No login collection, as on omacom/omarchy, has nothing to unlock, unless + # a login keyring file exists that the service did not list. + return no_login_keyring_file() + return ask("get-property", SECRETS, LOGIN, + "org.freedesktop.Secret.Collection", "Locked") == "b false" + + +def main() -> int: + if len(sys.argv) == 3 and sys.argv[1] == "no-login-keyring-files": + return 0 if no_login_keyring_files(Path(sys.argv[2])) else 1 + if subprocess.run(["omarchy-hw-apple-silicon"], check=False).returncode != 0: + return 1 + if os.environ.get("PAM_TYPE") == "open_session" and os.environ.get("PAM_SERVICE") == "sddm": + return 0 if record_login(os.environ.get("PAM_USER", "")) else 1 + if unlocked(os.environ.get("PAM_USER", "")): + return 0 + return 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/omarchy-mac/lib/touchid-sddm b/omarchy-mac/lib/touchid-sddm new file mode 100755 index 00000000..cda75cd6 --- /dev/null +++ b/omarchy-mac/lib/touchid-sddm @@ -0,0 +1,230 @@ +#!/usr/bin/python3 -I +# SPDX-License-Identifier: MIT +"""Add or remove Touch ID in a stock SDDM PAM stack under the Touch ID lock.""" + +import os +from pathlib import Path +import re +import stat +import subprocess +import sys +import tempfile + +PREVIOUS_PREFIX = "# omarchy-mac Touch ID\n" "auth include omarchy-mac-touchid\n" +PREFIX = (PREVIOUS_PREFIX + + "session optional pam_exec.so quiet type=open_session /usr/lib/omarchy-mac/touchid-pam-keyring-unlocked\n") +# An empty password asks for Touch ID unless a login keyring is locked; any other +# password skips to the stock stack. A rejected finger counts for faillock and an +# accepted one clears the count. Faillock options come from system-auth. +POLICY_TEMPLATE = """#%PAM-1.0 +auth requisite pam_shells.so +auth requisite pam_nologin.so +auth requisite pam_faillock.so preauth{preauth} +auth [success=ignore default=4] pam_exec.so quiet expose_authtok /usr/lib/omarchy-mac/touchid-pam-empty-password +auth [success=ignore default=die] pam_exec.so quiet /usr/lib/omarchy-mac/touchid-pam-keyring-unlocked +auth [success=1 maxtries=ignore default=die] pam_fprintd.so max-tries=3 timeout=5 +auth [default=die] pam_faillock.so authfail{authfail} +auth [success=done default=die] pam_faillock.so authsucc{authsucc} +""" +# Earlier policies this helper wrote, recognised so enable can replace them. +PREVIOUS_TEMPLATES = ( + """#%PAM-1.0 +auth requisite pam_shells.so +auth requisite pam_nologin.so +auth requisite pam_faillock.so preauth{preauth} +auth [success=ignore default=3] pam_exec.so quiet expose_authtok /usr/lib/omarchy-mac/touchid-pam-empty-password +auth [success=ignore default=die] pam_exec.so quiet /usr/lib/omarchy-mac/touchid-pam-keyring-unlocked +auth [success=done maxtries=ignore default=die] pam_fprintd.so max-tries=3 timeout=5 +auth [default=die] pam_faillock.so authfail{authfail} +""", +) +FAILLOCK_OPTION = re.compile( + r"silent|no_log_info|audit|even_deny_root|(deny|unlock_time|fail_interval|root_unlock_time)=\d+") + + +def render_policy(preauth: list[str], authfail: list[str], authsucc: list[str], + template: str = POLICY_TEMPLATE) -> str: + return template.format(preauth="".join(f" {option}" for option in preauth), + authfail="".join(f" {option}" for option in authfail), + authsucc="".join(f" {option}" for option in authsucc)) + + +POLICY = render_policy([], [], []) +PREVIOUS_POLICIES = ( + """#%PAM-1.0 +auth requisite pam_shells.so +auth requisite pam_nologin.so +auth required pam_faillock.so preauth +auth sufficient pam_fprintd.so max-tries=3 timeout=10 +""", +) +AUTH = { + ("auth", "include", "system-login"), + ("-auth", "optional", "pam_gnome_keyring.so"), + ("-auth", "optional", "pam_kwallet5.so"), + ("-auth", "optional", "pam_kwallet6.so"), +} +LOGIN_AUTH = [ + ("auth", "required", "pam_shells.so"), + ("auth", "requisite", "pam_nologin.so"), + ("auth", "include", "system-auth"), +] +SYSTEM_AUTH = [ + ("auth", "required", "pam_faillock.so", "preauth"), + ("-auth", "[success=2", "default=ignore]", "pam_systemd_home.so"), + ("auth", "[success=1", "default=bad]", "pam_unix.so", "try_first_pass", "nullok"), + ("auth", "[default=die]", "pam_faillock.so", "authfail"), + ("auth", "optional", "pam_permit.so"), + ("auth", "required", "pam_env.so"), + ("auth", "required", "pam_faillock.so", "authsucc"), +] + + +class Refused(Exception): + """The existing PAM configuration is not one this helper owns.""" + + +def read_regular(path: Path) -> str | None: + try: + mode = path.lstat().st_mode + except FileNotFoundError: + return None + if not stat.S_ISREG(mode): + raise Refused(f"{path} is not a regular file") + with path.open(encoding="utf-8", newline="") as stream: + return stream.read() + + +def write_atomic(path: Path, content: str) -> None: + fd, temporary = tempfile.mkstemp(prefix=f".{path.name}.", dir=path.parent) + try: + with os.fdopen(fd, "w", encoding="utf-8", newline="\n") as stream: + stream.write(content) + stream.flush() + os.fchmod(stream.fileno(), 0o644) + os.fsync(stream.fileno()) + os.replace(temporary, path) + finally: + Path(temporary).unlink(missing_ok=True) + + +def auth_lines(content: str) -> list[tuple[str, ...]]: + auth: list[tuple[str, ...]] = [] + for line in content.splitlines(): + fields = line.split() + if not fields or fields[0].startswith("#"): + continue + kind = fields[0].lower() + if kind in ("auth", "-auth"): + auth.append(tuple(fields)) + elif kind not in ("account", "-account", "password", "-password", "session", "-session"): + raise Refused("unrecognized PAM module type") + return auth + + +def faillock_options(entries: list[tuple[str, ...]]) -> tuple[list[tuple[str, ...]], dict[str, list[str]]]: + """Strip the lockout options Omarchy adds to system-auth, and return them.""" + stripped: list[tuple[str, ...]] = [] + options: dict[str, list[str]] = {} + for entry in entries: + if (len(entry) > 4 and entry[2] == "pam_faillock.so" and entry[3] in ("preauth", "authfail", "authsucc") + and all(FAILLOCK_OPTION.fullmatch(option) for option in entry[4:])): + options[entry[3]] = list(entry[4:]) + entry = entry[:4] + stripped.append(entry) + return stripped, options + + +def owned_policy(content: str) -> bool: + """Whether content is exactly a policy this helper writes, whatever lockout options it carries.""" + options: dict[str, list[str]] = {} + for line in content.splitlines(): + fields = line.split() + if fields[:1] == ["auth"] and "pam_faillock.so" in fields[:-1]: + module = fields.index("pam_faillock.so") + options[fields[module + 1]] = fields[module + 2:] + preauth, authfail, authsucc = (options.get(mode, []) for mode in ("preauth", "authfail", "authsucc")) + return (all(FAILLOCK_OPTION.fullmatch(option) for option in preauth + authfail + authsucc) + and any(render_policy(preauth, authfail, authsucc, template) == content + for template in (POLICY_TEMPLATE, *PREVIOUS_TEMPLATES))) + + +def read_sddm(path: Path, enable: bool) -> str | None: + try: + return read_regular(path) + except Refused: + if enable: + raise + # Removal only needs to know whether this file includes our policy. + try: + text = path.read_text(encoding="utf-8", newline="") + except FileNotFoundError: + return None + except (OSError, UnicodeError) as error: + raise Refused(f"{path} could not be read") from error + if "omarchy-mac-touchid" in text: + raise Refused(f"{path} is not a regular file") + return None + + +def configure(directory: Path, enable: bool) -> None: + if not directory.exists(): + return + if not stat.S_ISDIR(directory.lstat().st_mode): + raise Refused(f"{directory} is not a regular directory") + sddm = directory / "sddm" + policy = directory / "omarchy-mac-touchid" + original = read_sddm(sddm, enable) + existing_policy = read_regular(policy) + if existing_policy is not None and existing_policy not in PREVIOUS_POLICIES and not owned_policy(existing_policy): + raise Refused(f"{policy} was changed; leaving it alone") + if original is None: + return + active = original.startswith(PREVIOUS_PREFIX) + current = original.startswith(PREFIX) + original = original.removeprefix(PREFIX if current else PREVIOUS_PREFIX) + if "omarchy-mac-touchid" in original: + raise Refused(f"{sddm} has a custom Touch ID entry") + if enable: + auth = auth_lines(original) + if auth.count(("auth", "include", "system-login")) != 1 or any( + entry not in AUTH for entry in auth): + raise Refused(f"{sddm} is not the stock system-login stack") + options: dict[str, list[str]] = {} + for name, expected in (("system-login", LOGIN_AUTH), ("system-auth", SYSTEM_AUTH)): + content = read_regular(directory / name) + entries = None if content is None else auth_lines(content) + if entries is not None and name == "system-auth": + entries, options = faillock_options(entries) + if entries != expected: + raise Refused(f"{directory / name} has custom authentication requirements") + wanted = render_policy(options.get("preauth", []), options.get("authfail", []), + options.get("authsucc", [])) + if existing_policy != wanted: + write_atomic(policy, wanted) + if not current: + write_atomic(sddm, PREFIX + original) + else: + if active: + write_atomic(sddm, original) + if existing_policy is not None: + policy.unlink() + + +def main() -> int: + if subprocess.run(["omarchy-hw-apple-silicon"], check=False).returncode != 0: + return 0 + if len(sys.argv) != 2 or sys.argv[1] not in ("enable", "disable"): + print("Usage: touchid-sddm enable|disable", file=sys.stderr) + return 2 + directory = Path(os.environ.get("OMARCHY_MAC_TOUCHID_PAM", "/etc/pam.d")) + try: + configure(directory, sys.argv[1] == "enable") + except (OSError, UnicodeError, Refused) as error: + print(f"touchid-sddm: {error}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/omarchy-mac/test/touchid-consent-test.sh b/omarchy-mac/test/touchid-consent-test.sh old mode 100644 new mode 100755 index e1725736..92a2ee9c --- a/omarchy-mac/test/touchid-consent-test.sh +++ b/omarchy-mac/test/touchid-consent-test.sh @@ -32,6 +32,7 @@ pass 'the status and load units and the enable and disable entrypoints are stage fixture=$work/fixture tree=$fixture/tree +export OMARCHY_MAC_TOUCHID_PAM=$fixture/pam mkdir -p "$fixture/bin" "$fixture/extractors" printf '#!/bin/sh\nexit 0\n' >"$fixture/bin/omarchy-hw-apple-silicon" # The stub keeps the driver options it was loaded with, as modprobe reads them. @@ -124,6 +125,8 @@ image = der(0x30, der(0x16, b"IMG4") + im4p + der(0xA0, seal)) with open(os.path.join(out, "key.bin"), "wb") as fd: fd.write(der(0x30, der(0x16, b"comb") + der(0x30, der(0x16, b"fdrd") + der(0x04, image)) + der(0x30, der(0x16, b"secb") + der(0x04, trust)))) +with open(os.path.join(out, "j715-msrk.bin"), "wb") as fd: + fd.write(bytes(index % 251 for index in range(10848))) PY python3 -I "$work/factory.py" "$work/factory" # Any copy of the sensor key under the fixture other than the one named. @@ -155,6 +158,7 @@ run() { OMARCHY_MAC_TOUCHID_OPTIONS=$fixture/etc/modprobe.conf OMARCHY_MAC_TOUCHID_MODULE=$fixture/module \ OMARCHY_MAC_TOUCHID_STATUS=$fixture/run/touchid OMARCHY_MAC_TOUCHID_HELPERS=$ROOT/lib \ OMARCHY_MAC_TOUCHID_NODE=$fixture/sep-bio OMARCHY_MAC_TOUCHID_KEYBAG=$fixture/keybag \ + OMARCHY_MAC_TOUCHID_PAM=$fixture/pam OMARCHY_MAC_TOUCHID_SDDM_AGREED=$fixture/etc/touchid-sddm \ OMARCHY_MAC_TOUCHID_ESP=$fixture/esp OMARCHY_MAC_TOUCHID_CONTAINER=${container:-$work/factory/isc.img} \ OMARCHY_MAC_TOUCHID_PYTHON=${python:-python3} "$ROOT/lib/$1" "${@:2}" } @@ -196,6 +200,32 @@ cp "$work/factory/key.bin" "$fixture/firmware/updates/apple/msrk-j700.bin" [[ $(eligibility) == "available" ]] || fail "a Neo whose sensor key is installed needs nothing else" pass 'only a Mac whose setup can finish is available' +# The J715 has no supported automatic FSC2/MSRk extractor. Neither another M4 +# board nor the Neo's key qualifies it, and checking eligibility writes nothing. +machine apple,j713 apple,t8132 apple,arm-platform +[[ $(eligibility) == "unsupported:board" ]] || fail 'an unqualified M4 board stays unsupported' +machine apple,j715 apple,t8132 apple,arm-platform +[[ $(eligibility) == "unsupported:no-calibration" ]] || fail 'J715 never substitutes the container calibration' +mkdir -p "$fixture/firmware/vendor/apple" +truncate -s 130427 "$fixture/firmware/vendor/apple/mesa_calibration.bin" +cp "$work/factory/key.bin" "$fixture/firmware/vendor/apple/msrk-j700.bin" +[[ $(eligibility) == "unsupported:no-root-key" ]] || fail "the Neo's key does not qualify J715" +cp "$work/factory/j715-msrk.bin" "$fixture/firmware/vendor/apple/msrk-j715.bin" +[[ $(eligibility) == "available" && ! -s $fixture/calls ]] || fail 'a prepared J715 is available without writes' +echo ready >"$fixture/activation" +out=$(run touchid-enable 2>&1) || fail 'J715 uses its installed FDR key' "$out" +! grep -Fxq calibration "$fixture/calls" || fail 'J715 never carves a replacement calibration' +cmp -s "$fixture/firmware/vendor/apple/msrk-j715.bin" "$work/factory/j715-msrk.bin" || + fail 'J715 keeps the supplied key unchanged' +[[ -f $fixture/etc/touchid-on ]] || fail 'J715 records boot-time enablement' +machine apple,j715 apple,t8132 apple,arm-platform +mkdir -p "$fixture/firmware/vendor/apple" +truncate -s 130427 "$fixture/firmware/vendor/apple/mesa_calibration.bin" +printf incomplete >"$fixture/firmware/vendor/apple/msrk-j715.bin" +! out=$(run touchid-enable 2>&1) && [[ ! -s $fixture/calls && ! -e $fixture/etc/touchid-on ]] || + fail 'an incomplete J715 key fails before loading or enabling the driver' "$out" +pass 'J715 keeps private factory inputs and refuses missing or incomplete inputs before enabling' + # At boot the status says so for the detector, and never loads the driver. machine apple,j414c apple,t6021 apple,arm-platform run touchid-status @@ -488,7 +518,7 @@ echo not-ready >"$fixture/activation" echo ready >"$fixture/activation" machine apple,j414c apple,t6021 apple,arm-platform touch "$fixture/modprobe-fails" -! out=$(run touchid-enable 2>&1) && [[ ! -e $fixture/etc/touchid-on && $out == *"driver did not load"* ]] && +! out=$(run touchid-enable 2>&1) && [[ ! -e $fixture/etc/touchid-on && ! -e $fixture/etc/touchid-sddm && $out == *"driver did not load"* ]] && ! grep -q 'systemctl start' "$fixture/calls" || fail 'a driver that does not load takes the agreement back and starts nothing' "$out" rm "$fixture/modprobe-fails" @@ -503,6 +533,13 @@ machine apple,j414c apple,t6021 apple,arm-platform mkdir -p "$fixture/module" echo ready >"$fixture/activation" run touchid-enable >/dev/null 2>&1 || fail 'a driver already running that writes by default turns on now' +[[ -e $fixture/etc/touchid-sddm ]] || fail 'turning it on records the agreement to the SDDM login' +# SDDM's login screen is best effort: a PAM stack this package does not manage never undoes setup. +mkdir -p "$fixture/pam" +printf 'auth required pam_deny.so\n' >"$fixture/pam/sddm" +out=$(run touchid-enable 2>&1) && [[ $out == *"login screen is unchanged"* && -e $fixture/etc/touchid-on && $(<"$fixture/pam/sddm") == 'auth required pam_deny.so' ]] || + fail "a custom SDDM PAM stack is reported, kept, and doesn't fail setup" "$out" +rm -rf "$fixture/pam" machine apple,j414c apple,t6021 apple,arm-platform mkdir -p "$fixture/module" "$fixture/etc" touch "$fixture/etc/modprobe.conf" @@ -521,6 +558,7 @@ for name in enable-fingerprint disable-fingerprint; do sed -e "s|/run/omarchy-mac/touchid|$fixture/run/touchid|g" -e "s|/var/lib/aurora-sep-keybag.bin|$fixture/keybag|g" \ -e "s|/usr/lib/omarchy-mac/touchid-enable|$fixture/bin/enable-stub|g" -e "s|/etc/omarchy-mac/touchid-on|$fixture/etc/touchid-on|g" \ -e "s|/usr/lib/omarchy-mac/touchid-eligibility|$fixture/bin/eligibility-stub|g" \ + -e "s|/usr/lib/omarchy-mac/touchid-sddm|$ROOT/lib/touchid-sddm|g" -e "s|/etc/omarchy-mac/touchid-sddm|$fixture/etc/touchid-sddm|g" \ -e "s|/etc/modprobe.d/omarchy-mac-touchid.conf|$fixture/etc/modprobe.conf|g" -e "s|/usr/lib/firmware/updates/|$fixture/firmware/updates/|g" \ -e "s|/proc/device-tree/compatible|$tree/compatible|g" -e "s|flock -w 300|flock -w 0|" "$ROOT/entrypoints/$name" >"$entry/$name" chmod +x "$entry/$name" @@ -543,7 +581,11 @@ machine apple,j414c apple,t6021 apple,arm-platform grep -q 'experimental and can be unstable' "$fixture/out" && grep -q 'Secure Enclave with macOS' "$fixture/out" && grep -q 'back up any data on your macOS partition' "$fixture/out" && grep -q "The Mac manual's" "$fixture/out" || fail 'the owner is told Touch ID is experimental, to back up macOS and where the details are' "$(<"$fixture/out")" -(( $(grep -c . "$fixture/out") <= 4 )) || fail 'the prompt stays at three lines' "$(<"$fixture/out")" +grep -q 'again later in a boot: submit an empty password' "$fixture/out" && + grep -q 'an account with no password can no' "$fixture/out" && + grep -q 'longer log in there. A custom SDDM PAM configuration is kept.' "$fixture/out" || + fail 'the owner is told about SDDM re-login, empty passwords, passwordless accounts and custom policy' "$(<"$fixture/out")" +(( $(grep -c . "$fixture/out") == 8 )) || fail 'the prompt has three warning lines, four SDDM lines and the refusal' "$(<"$fixture/out")" ask available y && grep -Fxq enable "$fixture/calls" || fail 'an owner who says yes turns Touch ID on' neo ! ask available n && [[ -z $(key_copies) ]] || fail "a Neo whose owner says no has no copy of its sensor key" "$(key_copies)" @@ -594,11 +636,62 @@ ask blocked '' && grep -Fxq 'options apple_sep xart_writes=1 provision_keybag=1' without_status available n && ! grep -qE 'experimental|stays off' "$fixture/out" && grep -q "isn't ready yet (no status)" "$fixture/out" && [[ -e $fixture/etc/touchid-on && ! -s $fixture/calls ]] || fail 'an agreed Mac with no status is told to restart, not asked again' "$(<"$fixture/out")" +# SDDM's login screen reaches only an owner who was told about it, and never stops setup. +omarchy_pam() { + mkdir -p "$fixture/pam" + printf '#%%PAM-1.0\nauth include system-login\naccount include system-login\npassword include system-login\nsession include system-login\n' >"$fixture/pam/sddm" + printf 'auth required pam_shells.so\nauth requisite pam_nologin.so\nauth include system-auth\naccount required pam_access.so\n' >"$fixture/pam/system-login" + printf 'auth required pam_faillock.so preauth silent deny=10 unlock_time=120\n-auth [success=2 default=ignore] pam_systemd_home.so\nauth [success=1 default=bad] pam_unix.so try_first_pass nullok\nauth [default=die] pam_faillock.so authfail deny=10 unlock_time=120\nauth optional pam_permit.so\nauth required pam_env.so\nauth required pam_faillock.so authsucc\n' >"$fixture/pam/system-auth" +} +rm -rf "$fixture/pam" +omarchy_pam +mkdir -p "$fixture/etc" +touch "$fixture/etc/touchid-on" "$fixture/etc/modprobe.conf" +rm -f "$fixture/etc/touchid-sddm" +ask ready '' && [[ ! -e $fixture/pam/omarchy-mac-touchid ]] && ! grep -q 'omarchy-mac-touchid' "$fixture/pam/sddm" || + fail 'a Mac that agreed before the login screen change is not given it unasked' "$(<"$fixture/out")" +touch "$fixture/etc/touchid-sddm" +ask ready '' && grep -Fxq 'auth requisite pam_faillock.so preauth silent deny=10 unlock_time=120' "$fixture/pam/omarchy-mac-touchid" && + grep -Fxq 'auth include omarchy-mac-touchid' "$fixture/pam/sddm" || + fail 'an Omarchy Mac that agreed to the login screen change gets it' "$(<"$fixture/out")" +rm -f "$fixture/pam/omarchy-mac-touchid" +omarchy_pam +printf 'auth required pam_deny.so\n' >>"$fixture/pam/sddm" +ask ready '' && grep -q 'left as it is' "$fixture/out" && [[ ! -e $fixture/pam/omarchy-mac-touchid ]] || + fail 'a custom SDDM stack is reported but never stops the fingerprint setup' "$(<"$fixture/out")" +rm -rf "$fixture/pam" +rm -f "$fixture/etc/touchid-sddm" rm -f "$fixture/etc/touchid-on" "$fixture/etc/modprobe.conf" touch "$fixture/etc/touchid-on" "$fixture/etc/modprobe.conf" PATH="$fixture/bin:$PATH" "$entry/disable-fingerprint" >"$fixture/out" 2>&1 && [[ ! -e $fixture/etc/touchid-on && ! -e $fixture/etc/modprobe.conf ]] && grep -q 'key store for Linux stays' "$fixture/out" || fail "turning it off removes the owner's agreement and says the key store stays" PATH="$fixture/bin:$PATH" "$entry/disable-fingerprint" >/dev/null 2>&1 || fail 'turning it off twice is fine' +# A PAM file that is not ours never blocks turning Touch ID off; one that still +# includes our policy is kept and reported, and consent goes either way. +mkdir -p "$fixture/pam" "$fixture/etc" "$fixture/firmware/updates/apple" +printf 'administrator PAM\n' >"$fixture/pam/custom" +ln -s custom "$fixture/pam/sddm" +touch "$fixture/etc/touchid-on" "$fixture/etc/touchid-sddm" "$fixture/etc/modprobe.conf" +cp "$work/factory/key.bin" "$fixture/firmware/updates/apple/msrk-j700.bin" +PATH="$fixture/bin:$PATH" "$entry/disable-fingerprint" >"$fixture/out" 2>&1 && + [[ ! -e $fixture/etc/touchid-on && ! -e $fixture/etc/touchid-sddm && ! -e $fixture/etc/modprobe.conf && -L $fixture/pam/sddm && -z $(key_copies) ]] && + [[ $(<"$fixture/pam/custom") == "administrator PAM" ]] || + fail 'a symlinked SDDM file without our policy neither blocks removal nor changes' "$(<"$fixture/out")" +printf '# omarchy-mac Touch ID\nauth include omarchy-mac-touchid\n' >"$fixture/pam/custom" +touch "$fixture/etc/touchid-on" "$fixture/etc/touchid-sddm" "$fixture/etc/modprobe.conf" +cp "$work/factory/key.bin" "$fixture/firmware/updates/apple/msrk-j700.bin" +! PATH="$fixture/bin:$PATH" "$entry/disable-fingerprint" >"$fixture/out" 2>&1 && + [[ ! -e $fixture/etc/touchid-on && ! -e $fixture/etc/touchid-sddm && ! -e $fixture/etc/modprobe.conf && -L $fixture/pam/sddm && -z $(key_copies) ]] && + grep -q 'review it' "$fixture/out" || + fail 'a symlinked SDDM file that includes our policy is kept and reported while consent is removed' "$(<"$fixture/out")" +rm "$fixture/pam/sddm" "$fixture/pam/custom" +printf 'administrator owned policy\n' >"$fixture/pam/omarchy-mac-touchid" +touch "$fixture/etc/touchid-on" "$fixture/etc/modprobe.conf" +! PATH="$fixture/bin:$PATH" "$entry/disable-fingerprint" >"$fixture/out" 2>&1 && + [[ ! -e $fixture/etc/touchid-on && ! -e $fixture/etc/modprobe.conf ]] && + [[ $(<"$fixture/pam/omarchy-mac-touchid") == "administrator owned policy" ]] || + fail 'edited owned PAM policy is preserved while boot consent is removed' "$(<"$fixture/out")" +rm "$fixture/pam/omarchy-mac-touchid" # A Neo's sensor key goes too, since turning Touch ID on again rebuilds it. mkdir -p "$fixture/firmware/updates/apple" "$fixture/etc" cp "$work/factory/key.bin" "$fixture/firmware/updates/apple/msrk-j700.bin" diff --git a/omarchy-mac/test/touchid-j715-calibration-test.sh b/omarchy-mac/test/touchid-j715-calibration-test.sh new file mode 100644 index 00000000..82ec1ac5 --- /dev/null +++ b/omarchy-mac/test/touchid-j715-calibration-test.sh @@ -0,0 +1,165 @@ +#!/bin/bash +set -euo pipefail +source "$(dirname "$0")/base-test.sh" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +fixture=$work/fixture +export OMARCHY_MAC_TOUCHID_TREE=$fixture/tree +export OMARCHY_MAC_TOUCHID_FIRMWARE=$fixture/firmware +export OMARCHY_MAC_TOUCHID_EXTRACTORS=$fixture/extractors +export OMARCHY_MAC_TOUCHID_AGREED=$fixture/etc/touchid-on +export OMARCHY_MAC_TOUCHID_SDDM_AGREED=$fixture/etc/touchid-sddm +export OMARCHY_MAC_TOUCHID_OPTIONS=$fixture/etc/modprobe.conf +export OMARCHY_MAC_TOUCHID_MODULE=$fixture/module +export OMARCHY_MAC_TOUCHID_STATUS=$fixture/run/touchid +export OMARCHY_MAC_TOUCHID_HELPERS=$ROOT/lib +export OMARCHY_MAC_TOUCHID_NODE=$fixture/sep-bio +export OMARCHY_MAC_TOUCHID_KEYBAG=$fixture/keybag +export OMARCHY_MAC_TOUCHID_ESP=$fixture/esp +export OMARCHY_MAC_TOUCHID_CONTAINER=$fixture/container +export OMARCHY_MAC_TOUCHID_PAM=$fixture/pam +export OMARCHY_MAC_TOUCHID_PYTHON=$fixture/bin/python +export OMARCHY_MAC_TOUCHID_LOCK_WAIT=0 +export PATH=$fixture/bin:$PATH +mkdir -p "$fixture/bin" "$fixture/extractors" +printf '#!/bin/bash\nexit 0\n' >"$fixture/bin/omarchy-hw-apple-silicon" +for command in modprobe systemctl python; do + printf '#!/bin/bash\nprintf "%%s\\n" "%s $*" >>"%s"\n' "$command" "$fixture/calls" >"$fixture/bin/$command" +done +# A missing input must not reach extraction, waiting, or any live service. +for command in "$fixture/extractors/extract-mesa-calibration" "$fixture/bin/sleep"; do + printf '#!/bin/bash\necho unexpected >>"%s"\nexit 1\n' "$fixture/calls" >"$command" +done +chmod +x "$fixture/bin/"* "$fixture/extractors/"* + +machine() { + rm -rf "$fixture/tree" "$fixture/firmware" "$fixture/etc" "$fixture/run" + mkdir -p "$OMARCHY_MAC_TOUCHID_TREE/soc/spi/fingerprint@0" "$OMARCHY_MAC_TOUCHID_TREE/chosen" \ + "$fixture/firmware/apple" "$fixture/firmware/vendor/apple" "$fixture/firmware/updates/apple" "$fixture/run" + printf '%s\0' "${1:-apple,j715}" "${2:-apple,t8132}" >"$OMARCHY_MAC_TOUCHID_TREE/compatible" + printf 'apple,mesa-fingerprint\0' >"$OMARCHY_MAC_TOUCHID_TREE/soc/spi/fingerprint@0/compatible" + printf uuid >"$OMARCHY_MAC_TOUCHID_TREE/chosen/apfs-preboot-uuid" + truncate -s 10848 "$fixture/firmware/apple/msrk-j715.bin" + touch "$fixture/sep-bio" "$fixture/keybag" + printf 'ready\n' >"$fixture/run/touchid" + : >"$fixture/calls" +} + +failures=0 +rejected() { + local name=$1 expected=${2:-unsupported:invalid-calibration} eligibility result=0 consent=no options=no loaded=no + eligibility=$("$ROOT/lib/touchid-eligibility") + "$ROOT/lib/touchid-enable" >"$fixture/output" 2>&1 || result=$? + [[ ! -e $OMARCHY_MAC_TOUCHID_AGREED ]] || consent=yes + [[ ! -e $OMARCHY_MAC_TOUCHID_OPTIONS ]] || options=yes + [[ ! -e $fixture/run/touchid-loaded ]] || loaded=yes + if [[ $eligibility == "$expected" && $result != 0 && + $consent == no && $options == no && $loaded == no && ! -s $fixture/calls ]]; then + pass "$name blocks eligibility, consent, options and loading" + else + printf 'not ok - %s: eligibility=%s enable_rc=%s consent=%s options=%s loaded=%s\n' \ + "$name" "$eligibility" "$result" "$consent" "$options" "$loaded" >&2 + failures=$((failures + 1)) + fi +} + +# The native evidence qualifies one 130427-byte body, not an FSC2 magic string. +# Synthetic bodies test only the size gate, never identity or authenticity. +for directory in "$fixture/firmware" "$fixture/firmware/vendor" "$fixture/firmware/updates"; do + for size in 0 4 122131 130426 130428; do + machine + truncate -s "$size" "$directory/apple/mesa_calibration.bin" + rejected "${directory#"$fixture/firmware"}/$size-byte calibration" + done + machine + truncate -s 130427 "$directory/apple/mesa_calibration.bin" + [[ $("$ROOT/lib/touchid-eligibility") == "available" && ! -s $fixture/calls ]] || + fail 'the qualified body size is eligible without writes' + "$ROOT/lib/touchid-enable" >"$fixture/output" 2>&1 || + fail 'a size-qualified J715 reaches the stubbed activation' "$(<"$fixture/output")" + [[ -f $OMARCHY_MAC_TOUCHID_AGREED && -f $OMARCHY_MAC_TOUCHID_OPTIONS && -f $fixture/run/touchid-loaded ]] && + grep -Fxq 'modprobe apple-sep' "$fixture/calls" || + fail 'a size-qualified J715 records consent and reaches the stubbed load' + pass "${directory#"$fixture/firmware"} qualified-size body reaches activation" +done + +# No valid copy may mask a bad copy in another firmware lookup directory. +for invalid in "$fixture/firmware" "$fixture/firmware/vendor" "$fixture/firmware/updates"; do + machine + for directory in "$fixture/firmware" "$fixture/firmware/vendor" "$fixture/firmware/updates"; do + truncate -s 130427 "$directory/apple/mesa_calibration.bin" + done + truncate -s 0 "$invalid/apple/mesa_calibration.bin" + rejected "shadowed ${invalid#"$fixture/firmware"}/empty calibration" +done + +machine +rejected 'missing calibration' unsupported:no-calibration +for invalid in directory dangling-link; do + machine + truncate -s 130427 "$fixture/firmware/vendor/apple/mesa_calibration.bin" + if [[ $invalid == "directory" ]]; then + mkdir "$fixture/firmware/updates/apple/mesa_calibration.bin" + else + ln -s missing "$fixture/firmware/updates/apple/mesa_calibration.bin" + fi + rejected "$invalid shadowing a qualified-size calibration" +done +machine +truncate -s 130427 "$fixture/firmware/vendor/apple/private-fsc2.bin" +ln -s private-fsc2.bin "$fixture/firmware/vendor/apple/mesa_calibration.bin" +[[ $("$ROOT/lib/touchid-eligibility") == "available" ]] || fail 'a readable firmware symlink remains eligible' +pass 'a readable firmware symlink remains eligible' +machine +printf 'apple/private-fsc2.bin\0' >"$OMARCHY_MAC_TOUCHID_TREE/soc/spi/fingerprint@0/firmware-name" +truncate -s 130427 "$fixture/firmware/apple/mesa_calibration.bin" +truncate -s 4 "$fixture/firmware/vendor/apple/private-fsc2.bin" +rejected 'truncated device-tree firmware-name' +truncate -s 130427 "$fixture/firmware/vendor/apple/private-fsc2.bin" +[[ $("$ROOT/lib/touchid-eligibility") == "available" ]] || fail 'device-tree firmware-name is honored' +pass 'device-tree firmware-name selects the calibration' + +# Every present J715 key must be whole, even with good copies elsewhere. +for directory in "$fixture/firmware" "$fixture/firmware/vendor" "$fixture/firmware/updates"; do + for invalid in 0 10847 10849 directory dangling-link; do + machine + truncate -s 130427 "$fixture/firmware/apple/mesa_calibration.bin" + for candidate in "$fixture/firmware" "$fixture/firmware/vendor" "$fixture/firmware/updates"; do + truncate -s 10848 "$candidate/apple/msrk-j715.bin" + done + key=$directory/apple/msrk-j715.bin + rm "$key" + case $invalid in + directory) mkdir "$key" ;; + dangling-link) ln -s missing "$key" ;; + *) truncate -s "$invalid" "$key" ;; + esac + rejected "shadowed ${directory#"$fixture/firmware"}/$invalid J715 key" unsupported:invalid-root-key + done + machine + truncate -s 130427 "$fixture/firmware/apple/mesa_calibration.bin" + rm "$fixture/firmware/apple/msrk-j715.bin" + truncate -s 10848 "$directory/apple/msrk-j715.bin" + [[ $("$ROOT/lib/touchid-eligibility") == "available" ]] || fail 'a whole J715 key remains eligible' + pass "${directory#"$fixture/firmware"} whole J715 key remains eligible" + mv "$directory/apple/msrk-j715.bin" "$directory/apple/private-msrk.bin" + ln -s private-msrk.bin "$directory/apple/msrk-j715.bin" + [[ $("$ROOT/lib/touchid-eligibility") == "available" ]] || fail 'a readable J715 key symlink remains eligible' + pass "${directory#"$fixture/firmware"} readable J715 key symlink remains eligible" +done +machine +truncate -s 130427 "$fixture/firmware/apple/mesa_calibration.bin" +rm "$fixture/firmware/apple/msrk-j715.bin" +rejected 'missing J715 key' unsupported:no-root-key + +for board in 'apple,j414c apple,t6021' 'apple,j700 apple,t8140'; do + read -r model chip <<<"$board" + machine "$model" "$chip" + printf legacy >"$fixture/firmware/apple/mesa_calibration.bin" + truncate -s 0 "$fixture/firmware/apple/msrk-j715.bin" + truncate -s 1 "$fixture/firmware/apple/msrk-j700.bin" + [[ $("$ROOT/lib/touchid-eligibility") == "available" ]] || fail 'other boards keep their calibration rules' +done +pass 'other boards keep their calibration rules' +(( failures == 0 )) || fail "$failures calibration/key regressions" diff --git a/omarchy-mac/test/touchid-pam-state-test.sh b/omarchy-mac/test/touchid-pam-state-test.sh new file mode 100644 index 00000000..555948e5 --- /dev/null +++ b/omarchy-mac/test/touchid-pam-state-test.sh @@ -0,0 +1,84 @@ +#!/bin/bash +set -euo pipefail +source "$(dirname "$0")/base-test.sh" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT + +python3 -I - "$ROOT/lib/touchid-pam-keyring-unlocked" "$work" <<'PY' +import os +from pathlib import Path +import pwd +import runpy +import socket +import subprocess +import sys +from types import SimpleNamespace + +helper, work = Path(sys.argv[1]), Path(sys.argv[2]) +module = runpy.run_path(str(helper)) +unlocked = module["unlocked"] +home = work / "home" +home.mkdir() +entry = pwd.getpwuid(os.getuid()) +user = pwd.struct_passwd((*entry[:5], str(home), entry.pw_shell)) +unlocked.__globals__["pwd"] = SimpleNamespace(getpwnam=lambda name: user) +logins = work / "logins" +unlocked.__globals__["LOGINS"] = logins +runtime = work / "runtime" +bus = runtime / str(user.pw_uid) / "bus" +bus.parent.mkdir(parents=True) +listener = socket.socket(socket.AF_UNIX) +listener.bind(str(bus)) + +def run(command, **options): + if "/usr/bin/busctl" in command: + assert "NameHasOwner" in command, command + return subprocess.CompletedProcess(command, 0, "b false\n", "") + # The fixture already runs as its user: exercise the real file lookup without + # requiring root to call setpriv in CI. + start = command.index("--reset-env") + 1 + return subprocess.run(command[start:], **options) + +failures = [] +if unlocked(user.pw_name, run, runtime): + failures.append("a lingering bus without a prior login allowed fingerprints") +assert module["record_login"](user.pw_name), "SDDM reaching open_session records the login" +assert module["record_login"](user.pw_name), "recording the same login is idempotent" +assert unlocked(user.pw_name, run, runtime), "a prior login with no keyring allows re-login" +marker = logins / str(user.pw_uid) +marker.chmod(0o666) +assert not unlocked(user.pw_name, run, runtime), "a user-writable marker is not proof" +marker.chmod(0o600) +marker.unlink() +marker.symlink_to(home) +assert not unlocked(user.pw_name, run, runtime), "a symlink is not login proof" +assert not module["record_login"](user.pw_name), "recording does not follow a forged marker" +marker.unlink() +assert module["record_login"](user.pw_name) +private = home / ".local" +(private / "share/keyrings").mkdir(parents=True) +(private / "share/keyrings/login.keyring").touch() +private.chmod(0) +try: + if unlocked(user.pw_name, run, runtime): + failures.append("an inaccessible parent hid a login keyring") +finally: + private.chmod(0o700) +for name in module["LOGIN_FILES"]: + key = home / name + key.parent.mkdir(parents=True, exist_ok=True) + key.touch() + assert not unlocked(user.pw_name, run, runtime), f"{name} is not missed" + key.parent.chmod(0) + try: + assert not unlocked(user.pw_name, run, runtime), f"an inaccessible {name} refuses" + finally: + key.parent.chmod(0o700) + key.unlink() +assert unlocked(user.pw_name, run, runtime), "confirmed absence allows re-login" +marker.unlink() +assert not unlocked(user.pw_name, run, runtime), "a fresh boot with no marker refuses" +listener.close() +assert not failures, "; ".join(failures) +print("ok - a lingering bus needs trusted boot-local login proof and file lookups distinguish absence from errors") +PY diff --git a/omarchy-mac/test/touchid-sddm-test.sh b/omarchy-mac/test/touchid-sddm-test.sh new file mode 100644 index 00000000..94ecb89f --- /dev/null +++ b/omarchy-mac/test/touchid-sddm-test.sh @@ -0,0 +1,423 @@ +#!/bin/bash +set -euo pipefail +source "$(dirname "$0")/base-test.sh" +work=$(mktemp -d) +trap 'rm -rf "$work"' EXIT +mkdir "$work/bin" +printf '#!/bin/sh\nexit 0\n' >"$work/bin/omarchy-hw-apple-silicon" +chmod +x "$work/bin/omarchy-hw-apple-silicon" +export PATH="$work/bin:$PATH" +export OMARCHY_MAC_TOUCHID_PAM=$work/pam +mkdir "$OMARCHY_MAC_TOUCHID_PAM" +helper=$ROOT/lib/touchid-sddm + +python3 -I "$helper" enable +[[ -z $(ls -A "$OMARCHY_MAC_TOUCHID_PAM") ]] || fail 'no SDDM means no PAM changes' +cat >"$work/original" <<'PAM' +#%PAM-1.0 +auth include system-login +-auth optional pam_gnome_keyring.so +account include system-login +password include system-login +session include system-login +PAM +cp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +cat >"$OMARCHY_MAC_TOUCHID_PAM/system-login" <<'PAM' +auth required pam_shells.so +auth requisite pam_nologin.so +auth include system-auth +account required pam_access.so +PAM +cat >"$OMARCHY_MAC_TOUCHID_PAM/system-auth" <<'PAM' +auth required pam_faillock.so preauth +-auth [success=2 default=ignore] pam_systemd_home.so +auth [success=1 default=bad] pam_unix.so try_first_pass nullok +auth [default=die] pam_faillock.so authfail +auth optional pam_permit.so +auth required pam_env.so +auth required pam_faillock.so authsucc +PAM +python3 -I "$helper" enable +cp "$OMARCHY_MAC_TOUCHID_PAM/sddm" "$work/enabled" +python3 -I "$helper" enable +cmp "$work/enabled" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'enabling twice changes nothing' +python3 -I "$helper" disable +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'disabling restores the exact original' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'the owned include is removed' +python3 -I "$helper" disable +pass 'SDDM enablement is optional, idempotent and reversible' + +sed 's/$/\r/' "$work/original" >"$work/crlf" +cp "$work/crlf" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +python3 -I "$helper" enable +python3 -I "$helper" disable +cmp "$work/crlf" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'disabling must preserve original line endings' +cp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +pass 'SDDM removal preserves the original line endings' + +cp "$OMARCHY_MAC_TOUCHID_PAM/system-login" "$work/system-login" +printf 'auth required pam_deny.so\n' >>"$OMARCHY_MAC_TOUCHID_PAM/system-login" +! python3 -I "$helper" enable 2>"$work/error" || fail 'an inherited mandatory auth rule must not be bypassed' +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'inherited policy refusal changed SDDM' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'inherited policy refusal installed a policy' +cp "$work/system-login" "$OMARCHY_MAC_TOUCHID_PAM/system-login" +cp "$OMARCHY_MAC_TOUCHID_PAM/system-auth" "$work/system-auth" +printf 'auth required pam_deny.so\n' >>"$OMARCHY_MAC_TOUCHID_PAM/system-auth" +! python3 -I "$helper" enable 2>"$work/error" || fail 'a custom system-auth rule must not be bypassed' +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'custom system-auth refusal changed SDDM' +cp "$work/system-auth" "$OMARCHY_MAC_TOUCHID_PAM/system-auth" +pass 'inherited authentication requirements are preserved' + +for name in sddm system-login system-auth; do + cp "$OMARCHY_MAC_TOUCHID_PAM/$name" "$work/case-original" + for kind in AUTH Auth -AUTH --auth not-a-pam-type; do + printf '%s required pam_deny.so\n' "$kind" >>"$OMARCHY_MAC_TOUCHID_PAM/$name" + cp "$OMARCHY_MAC_TOUCHID_PAM/sddm" "$work/case-sddm" + cp "$OMARCHY_MAC_TOUCHID_PAM/$name" "$work/case-source" + ! python3 -I "$helper" enable 2>"$work/error" || fail 'case-variant authentication rules must be refused' + cmp "$work/case-sddm" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'case-variant refusal changed SDDM' + cmp "$work/case-source" "$OMARCHY_MAC_TOUCHID_PAM/$name" || fail 'case-variant refusal changed the source policy' + [[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'case-variant refusal installed a policy' + cp "$work/case-original" "$OMARCHY_MAC_TOUCHID_PAM/$name" + done +done +pass 'case-variant authentication rules are refused without writes' + +printf 'auth required pam_deny.so\n' >>"$OMARCHY_MAC_TOUCHID_PAM/sddm" +cp "$OMARCHY_MAC_TOUCHID_PAM/sddm" "$work/custom" +! python3 -I "$helper" enable 2>"$work/error" || fail 'custom auth rules must be preserved' +cmp "$work/custom" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'a refusal modified custom PAM' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'a refusal installed a policy' +rm "$OMARCHY_MAC_TOUCHID_PAM/sddm" +ln -s "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +! python3 -I "$helper" enable 2>"$work/error" || fail 'a symlink must be refused' +rm "$OMARCHY_MAC_TOUCHID_PAM/sddm" +cp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +printf 'administrator policy\n' >"$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" +! python3 -I "$helper" enable 2>"$work/error" || fail 'an administrator policy must be preserved' +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'a refusal enabled custom policy' +pass 'custom and symlinked PAM files are refused before writes' + +previous=$(python3 -I -c 'import runpy, sys; print(runpy.run_path(sys.argv[1])["PREVIOUS_POLICIES"][0], end="")' "$helper") +printf '%s\n' "$previous" >"$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" +printf '# omarchy-mac Touch ID\nauth include omarchy-mac-touchid\n' | cat - "$work/original" >"$OMARCHY_MAC_TOUCHID_PAM/sddm" +python3 -I "$helper" enable +current=$(python3 -I -c 'import runpy, sys; print(runpy.run_path(sys.argv[1])["POLICY"], end="")' "$helper") +[[ $(<"$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid") == "$current" ]] || fail 'enabling replaces the previous owned policy' +python3 -I - "$helper" "$OMARCHY_MAC_TOUCHID_PAM/sddm" "$work/original" <<'PY' +from pathlib import Path +import runpy +import sys +prefix = runpy.run_path(sys.argv[1])["PREFIX"].encode() +assert Path(sys.argv[2]).read_bytes() == prefix + Path(sys.argv[3]).read_bytes(), "an old include gains the session hook" +PY +python3 -I "$helper" disable +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'disabling after an upgrade restores the original' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'the upgraded policy is removed' +printf '%s\n' "$previous" >"$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" +python3 -I "$helper" disable +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'a previous owned policy is removed on disable' +pass 'the previous owned policy is upgraded and removed' + +# Omarchy rewrites the faillock lines in system-auth; the policy carries its limits. +cp "$OMARCHY_MAC_TOUCHID_PAM/system-auth" "$work/stock-system-auth" +cat >"$OMARCHY_MAC_TOUCHID_PAM/system-auth" <<'PAM' +auth required pam_faillock.so preauth silent deny=10 unlock_time=120 +-auth [success=2 default=ignore] pam_systemd_home.so +auth [success=1 default=bad] pam_unix.so try_first_pass nullok +auth [default=die] pam_faillock.so authfail deny=10 unlock_time=120 +auth optional pam_permit.so +auth required pam_env.so +auth required pam_faillock.so authsucc +PAM +python3 -I "$helper" enable || fail "Omarchy's lockout options must not make system-auth custom" +grep -Fxq 'auth requisite pam_faillock.so preauth silent deny=10 unlock_time=120' "$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" && + grep -Fxq 'auth [default=die] pam_faillock.so authfail deny=10 unlock_time=120' "$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" || + fail "the policy must use system-auth's lockout options" +cp "$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" "$work/omarchy-policy" +python3 -I "$helper" enable +cmp "$work/omarchy-policy" "$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" || fail 'enabling twice keeps the same lockout options' +cp "$work/stock-system-auth" "$OMARCHY_MAC_TOUCHID_PAM/system-auth" +python3 -I "$helper" disable || fail 'an owned policy with earlier lockout options is still ours to remove' +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'disabling after the options changed restores the original' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'the owned policy is removed whatever its lockout options' +sed -i 's/^auth required pam_faillock.so preauth$/& dir=\/tmp\/lock/' "$OMARCHY_MAC_TOUCHID_PAM/system-auth" +! python3 -I "$helper" enable 2>"$work/error" || fail 'an unknown lockout option is custom policy and must be refused' +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'refusing an unknown lockout option changed SDDM' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'refusing an unknown lockout option installed a policy' +cp "$work/stock-system-auth" "$OMARCHY_MAC_TOUCHID_PAM/system-auth" +pass "Omarchy's lockout options are accepted and carried into the policy" + +# A policy from before authsucc, with Omarchy's options, is still ours: enable replaces it. +sed -e 's/^auth required pam_faillock.so preauth$/& silent deny=10 unlock_time=120/' \ + -e 's/^auth \[default=die\] pam_faillock.so authfail$/& deny=10 unlock_time=120/' \ + -e 's/^auth required pam_faillock.so authsucc$/& deny=10/' "$work/stock-system-auth" >"$OMARCHY_MAC_TOUCHID_PAM/system-auth" +python3 -I - "$helper" "$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" <<'PY' +import runpy, sys +module = runpy.run_path(sys.argv[1]) +old = module["render_policy"](["silent", "deny=10", "unlock_time=120"], ["deny=10", "unlock_time=120"], [], + module["PREVIOUS_TEMPLATES"][0]) +assert "authsucc" not in old +open(sys.argv[2], "w").write(old) +PY +printf '# omarchy-mac Touch ID\nauth include omarchy-mac-touchid\n' | cat - "$work/original" >"$OMARCHY_MAC_TOUCHID_PAM/sddm" +python3 -I "$helper" enable || fail 'a policy from before authsucc is ours to replace' +grep -Fxq 'auth [success=done default=die] pam_faillock.so authsucc deny=10' "$OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid" || + fail "the replaced policy clears failures with system-auth's options" +python3 -I "$helper" disable +cmp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" || fail 'disabling after replacing a pre-authsucc policy restores the original' +[[ ! -e $OMARCHY_MAC_TOUCHID_PAM/omarchy-mac-touchid ]] || fail 'the replaced policy is removed' +cp "$work/stock-system-auth" "$OMARCHY_MAC_TOUCHID_PAM/system-auth" +pass 'a policy from before authsucc is replaced and removed' + +# Removal only cares whether SDDM's file includes our policy, even through a symlink. +mv "$OMARCHY_MAC_TOUCHID_PAM/sddm" "$work/real-sddm" +ln -s "$work/real-sddm" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +python3 -I "$helper" disable || fail 'a symlinked SDDM file that does not include the policy has nothing to remove' +[[ -L $OMARCHY_MAC_TOUCHID_PAM/sddm ]] && cmp "$work/original" "$work/real-sddm" || fail 'removal changed a symlinked SDDM file' +ln -sfn "$work/missing" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +python3 -I "$helper" disable || fail 'a dangling SDDM symlink has nothing to remove' +ln -sfn "$work/real-sddm" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +printf '# omarchy-mac Touch ID\nauth include omarchy-mac-touchid\n' | cat - "$work/original" >"$work/real-sddm" +cp "$work/real-sddm" "$work/included" +! python3 -I "$helper" disable 2>"$work/error" || fail 'a symlinked SDDM file that includes the policy must be reported' +cmp "$work/included" "$work/real-sddm" || fail 'a refused removal changed the symlink target' +rm "$OMARCHY_MAC_TOUCHID_PAM/sddm" +cp "$work/original" "$OMARCHY_MAC_TOUCHID_PAM/sddm" +pass 'removal ignores SDDM files that do not include the policy and reports ones that do' + +# Exercise the generated control flow with libpam and the real empty-password +# helper through pam_exec, substituting only the keyring, fingerprint and +# password providers' results. +python3 -I - "$helper" "$work" "$ROOT/lib" <<'PY' +import ctypes +import ctypes.util +import os +from pathlib import Path +import pwd +import runpy +import sys + +helper, work, lib = Path(sys.argv[1]), Path(sys.argv[2]), Path(sys.argv[3]) +root = work / "dispatch" +root.mkdir() +policy = runpy.run_path(str(helper))["POLICY"] +prefix = runpy.run_path(str(helper))["PREFIX"] +logins = work / "dispatch-logins" +user = pwd.getpwuid(os.getuid()) +login_marker = logins / str(user.pw_uid) +library = ctypes.util.find_library("pam") +if library is None: + raise RuntimeError("libpam is required for the PAM dispatch test") +pam = ctypes.CDLL(library) +libc = ctypes.CDLL(ctypes.util.find_library("c")) +libc.malloc.restype = ctypes.c_void_p +libc.strdup.restype = ctypes.c_void_p +libc.strdup.argtypes = [ctypes.c_char_p] +pointer = ctypes.c_void_p + +class Message(ctypes.Structure): + _fields_ = [("style", ctypes.c_int), ("text", ctypes.c_char_p)] + +class Response(ctypes.Structure): + _fields_ = [("text", pointer), ("code", ctypes.c_int)] + +CONVERSE = ctypes.CFUNCTYPE(ctypes.c_int, ctypes.c_int, + ctypes.POINTER(ctypes.POINTER(Message)), + ctypes.POINTER(ctypes.POINTER(Response)), pointer) + +class Conversation(ctypes.Structure): + _fields_ = [("function", CONVERSE), ("data", pointer)] + +pam.pam_start_confdir.argtypes = [ctypes.c_char_p, ctypes.c_char_p, + ctypes.POINTER(Conversation), ctypes.c_char_p, + ctypes.POINTER(pointer)] +pam.pam_authenticate.argtypes = [pointer, ctypes.c_int] +pam.pam_acct_mgmt.argtypes = [pointer, ctypes.c_int] +pam.pam_open_session.argtypes = [pointer, ctypes.c_int] +pam.pam_close_session.argtypes = [pointer, ctypes.c_int] +pam.pam_end.argtypes = [pointer, ctypes.c_int] + +def script(name, body): + path = work / name + path.write_text("#!/bin/bash\n" + body) + path.chmod(0o755) + return path + +record = work / "authfail-record" +cleared = work / "authsucc-record" +# pam_exec passes no PATH, so point the real helper's platform check at the stub. +empty = script("empty-password", (lib / "touchid-pam-empty-password").read_text().removeprefix("#!/bin/bash\n") + .replace("omarchy-hw-apple-silicon", str(work / "bin" / "omarchy-hw-apple-silicon"))) +recorder = work / "record-login" +recorder.write_text((lib / "touchid-pam-keyring-unlocked").read_text() + .replace('Path("/run/omarchy-mac/touchid-logins")', f"Path({str(logins)!r})") + .replace('["omarchy-hw-apple-silicon"]', f"[{str(work / 'bin/omarchy-hw-apple-silicon')!r}]")) +recorder.chmod(0o755) +prefix = prefix.replace("/usr/lib/omarchy-mac/touchid-pam-keyring-unlocked", str(recorder)) +keyring = {True: script("keyring-unlocked", "exit 0\n"), + False: script("keyring-locked", "exit 1\n")} +authfail = script("authfail", f"echo >>{record}\nexit 0\n") +authsucc = script("authsucc", f"echo >>{cleared}\nexit 0\n") +check = script("password-check", "IFS= read -r -d '' typed || true\n" + "if [[ $typed == secret ]]; then exit 0; else exit 1; fi\n") + +def attempt(typed, unlocked, fingerprint, password=True, shell=True, nologin=True, + lockout=True, account=True): + current = policy.replace("/usr/lib/omarchy-mac/touchid-pam-empty-password", str(empty)) + current = current.replace("/usr/lib/omarchy-mac/touchid-pam-keyring-unlocked", + str(keyring[unlocked])) + current = current.replace("pam_fprintd.so max-tries=3 timeout=5", + f"pam_debug.so auth={fingerprint}") + current = current.replace("pam_faillock.so authfail", f"pam_exec.so {authfail}") + current = current.replace("pam_faillock.so authsucc", f"pam_exec.so {authsucc}") + for module, result in (("pam_shells.so", shell), ("pam_nologin.so", nologin), + ("pam_faillock.so preauth", lockout)): + current = current.replace(module, "pam_permit.so" if result else "pam_deny.so") + (root / "omarchy-mac-touchid").write_text(current) + stack = (f"auth required pam_exec.so expose_authtok {check}\n" if password + else "auth required pam_deny.so\n") + (root / "sddm").write_text( + prefix + stack + + "account required " + ("pam_permit.so" if account else "pam_deny.so") + "\n" + "session required pam_permit.so\n") + record.unlink(missing_ok=True) + cleared.unlink(missing_ok=True) + login_marker.unlink(missing_ok=True) + prompts = [] + + def converse(count, messages, responses, data): + answers = ctypes.cast(libc.malloc(ctypes.sizeof(Response) * count), + ctypes.POINTER(Response)) + for index in range(count): + message = messages[index].contents if count == 1 else messages[0][index] + answers[index].code = 0 + answers[index].text = None + if message.style == 1: + prompts.append(message.text) + answers[index].text = libc.strdup(typed.encode()) + responses[0] = answers + return 0 + + function = CONVERSE(converse) + conversation = Conversation(function, None) + handle = pointer() + result = pam.pam_start_confdir(b"sddm", user.pw_name.encode(), ctypes.byref(conversation), + str(root).encode(), ctypes.byref(handle)) + if result != 0: + raise RuntimeError(f"pam_start_confdir: {result}") + try: + result = pam.pam_authenticate(handle, 0) + if result == 0: + result = pam.pam_acct_mgmt(handle, 0) + if result == 0: + result = pam.pam_open_session(handle, 0) + assert login_marker.exists() == (result == 0), "only a session after successful authentication records login proof" + pam.pam_close_session(handle, 0) + assert login_marker.exists() == (result == 0), "close_session does not create or remove login proof" + finally: + pam.pam_end(handle, result) + return result == 0, len(prompts), record.exists(), cleared.exists() + +# (succeeds, prompts, failure counted, failures cleared) +cases = ( + (dict(typed="", unlocked=True, fingerprint="success"), (True, 1, False, True)), + (dict(typed="", unlocked=True, fingerprint="authinfo_unavail"), (False, 1, False, False)), + (dict(typed="", unlocked=True, fingerprint="auth_err"), (False, 1, False, False)), + (dict(typed="", unlocked=True, fingerprint="maxtries"), (False, 1, True, False)), + (dict(typed="", unlocked=False, fingerprint="success"), (False, 1, False, False)), + (dict(typed="", unlocked=True, fingerprint="authinfo_unavail", password=True), (False, 1, False, False)), + (dict(typed="secret", unlocked=True, fingerprint="success", password=False), (False, 1, False, False)), + (dict(typed="secret", unlocked=False, fingerprint="maxtries"), (True, 1, False, False)), + (dict(typed="wrong", unlocked=True, fingerprint="success"), (False, 1, False, False)), + (dict(typed="", unlocked=True, fingerprint="success", shell=False), (False, 0, False, False)), + (dict(typed="", unlocked=True, fingerprint="success", nologin=False), (False, 0, False, False)), + (dict(typed="", unlocked=True, fingerprint="success", lockout=False), (False, 0, False, False)), + (dict(typed="secret", unlocked=True, fingerprint="success", lockout=False), (False, 0, False, False)), + (dict(typed="", unlocked=True, fingerprint="success", account=False), (False, 1, False, True)), +) +for arguments, expected in cases: + observed = attempt(**arguments) + assert observed == expected, (arguments, expected, observed) +print("ok - real PAM sends empty passwords to Touch ID only with an unlocked keyring, clears the failure count after an accepted finger, sends typed passwords straight to the password stack with one prompt, and keeps shell, nologin, lockout and account checks") +PY + +# The keyring check never starts a stopped keyring and refuses only a login keyring that is or would start locked. +python3 -I - "$ROOT/lib/touchid-pam-keyring-unlocked" "$work" <<'PY' +import os +from pathlib import Path +import pwd +import runpy +import socket +import subprocess +import sys + +module = runpy.run_path(sys.argv[1]) +unlocked = module["unlocked"] +runtime = Path(sys.argv[2]) / "runtime" +user = pwd.getpwuid(os.getuid()) +bus = runtime / str(user.pw_uid) / "bus" +logins = Path(sys.argv[2]) / "logins" +unlocked.__globals__["LOGINS"] = logins + +LOGIN = '"/org/freedesktop/secrets/collection/login"' +DEFAULT = '"/org/freedesktop/secrets/collection/Default_5fkeyring"' +SESSION = '"/org/freedesktop/secrets/collection/session"' + +def fake(owner, locked, collections=(LOGIN, SESSION), login_file_exists=False, failure=None): + # login_file_exists: whether any of the two login keyring files exists + calls = [] + + def run(command, **options): + calls.append(command) + assert command[:2] == ["/usr/bin/setpriv", f"--reuid={user.pw_uid}"], command + if failure: + raise failure + if "no-login-keyring-files" in command: + assert command[-1] == user.pw_dir and "--init-groups" in command, command + return subprocess.CompletedProcess(command, 1 if login_file_exists else 0) + assert f"--address=unix:path={bus}" in command, command + if "NameHasOwner" in command: + return subprocess.CompletedProcess(command, 0, f"b {owner}\n", "") + if "Collections" in command: + listed = " ".join(("ao", str(len(collections)), *collections)) + return subprocess.CompletedProcess(command, 0, listed + "\n", "") + assert "Locked" in command and "/org/freedesktop/secrets/collection/login" in command, command + return subprocess.CompletedProcess(command, 0, f"b {locked}\n", "") + return run, calls + +run, calls = fake("true", "false") +assert not unlocked(user.pw_name, run, runtime) and not calls, "no user bus means locked" +bus.parent.mkdir(parents=True) +listener = socket.socket(socket.AF_UNIX) +listener.bind(str(bus)) +assert not unlocked(user.pw_name, run, runtime) and not calls, "a lingering user bus proves no login" +assert module["record_login"](user.pw_name), "the session hook records the login" +assert unlocked(user.pw_name, run, runtime) and len(calls) == 3, "an unlocked login collection" +run, calls = fake("true", "true") +assert not unlocked(user.pw_name, run, runtime), "a locked login collection" +run, calls = fake("true", "true", collections=(DEFAULT, SESSION)) +assert unlocked(user.pw_name, run, runtime) and len(calls) == 3, "omacom/omarchy's keyring has no login collection to unlock" +run, calls = fake("true", "true", collections=(DEFAULT, SESSION), login_file_exists=True) +assert not unlocked(user.pw_name, run, runtime), "a running keyring that omits a login keyring file on disk is not taken as empty" +run, calls = fake("true", "false", collections=(DEFAULT, SESSION), failure=OSError("setpriv")) +assert not unlocked(user.pw_name, run, runtime), "an unverifiable disk check refuses" +run, calls = fake("false", "true") +assert unlocked(user.pw_name, run, runtime) and len(calls) == 2, "a stopped keyring without a login keyring file" +assert not any("Locked" in call or "Collections" in call for call in calls), "a stopped keyring is never queried" +run, calls = fake("false", "false", login_file_exists=True) +assert not unlocked(user.pw_name, run, runtime), "a stopped keyring with a login keyring would start locked" + +run, calls = fake("true", "false", failure=subprocess.TimeoutExpired("busctl", 5)) +assert not unlocked(user.pw_name, run, runtime) +run, calls = fake("false", "false", failure=OSError("setpriv")) +assert not unlocked(user.pw_name, run, runtime) + +def broken(command, **options): + if "NameHasOwner" in command: + return subprocess.CompletedProcess(command, 0, "b true\n", "") + return subprocess.CompletedProcess(command, 1, "", "Object does not exist") +assert not unlocked(user.pw_name, broken, runtime), "an unreadable collection list is not taken as empty" +assert not unlocked("no-such-user-omarchy-mac", run, runtime) +print("ok - the keyring check refuses a locked or would-be-locked login keyring and passes a keyring without one") +PY