diff --git a/CHANGELOG.md b/CHANGELOG.md index 1e4039e..815b2b8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,49 @@ # Changelog +## Unreleased + +**The password says who you are**, as in Omarchy PR #16920. This replaces the list of +users on the login screen. See "Coming from an earlier version" in the README. + +- Each account's password is also its own LUKS key slot, on encrypted installs, in + `/etc/omarchy-multiuser/slots`. It has at least 6 characters and is nobody else's. +- The disk prompt picks the person: the boot image notes which slot opened the disk + (`omarchy-mu-luks-slot`), and `omarchy-mu-login-select` opens that person's desktop, + once. With one account on an encrypted disk, it is logged in. +- The login screen is a password box that finds the account (`omarchy-mu-login-match`). + The user list, **Other user…** and choosing a password at the first login are gone. +- `omarchy-mu-user-password` changes a password everywhere at once, also from + *Update › Password › User*. `omarchy-mu-user-helper` does it as root, journaled. +- `omarchy-mu-user-add` asks for the new password and yours; `--luks` and + `--set-password` are gone. `omarchy-mu-user-remove` takes the key off the disk without + anyone's disk password. `omarchy-mu-luks-enroll` and `omarchy-mu-accounts first-login` + are gone. +- Logging out a desktop opened by the disk prompt, when removing an account or taking + its rights, brings the login screen back: SDDM shows nothing there after a forced end. +- Greeter: typing and the F keys work again after going to another console and back. +- Removing the package turns off its path units first, which kept the PAM line in place, + and leaves no dangling link to the migration watchers. +- Depends on `perl`, no longer on `gettext`. + +Also from Omarchy PRs #16100 and #16920, and the session-switching findings posted there. + +- Lock screen: **Switch user** isn't offered while a desktop holds the first + console, as an automatic login's does until its first logout. SDDM's greeter + fails there and leaves the screen dark. +- Lock screen: a login screen already running is gone back to instead of asking + for a second one, which fails on the same console; F5 can't ask twice in a row. +- Lock screen: a password or fingerprint accepted once the session is in the + background doesn't open it, and neither a resume nor a screen coming back gives + a session in the background the fingerprint reader. +- Menu: **System › Switch User** (`omarchy-mu-user-switch`) locks this desktop, then + opens the person's running session or the login screen. +- Menu: *Setup › Users*' entries no longer turn up in the search of users outside + wheel. +- `omarchy-mu-user-add` refuses while `/etc/sddm.conf` logs someone in automatically. +- `omarchy-mu-user-remove` stops when the account's key can't be taken off the disk, + instead of saying it removed the account while that password still opens the disk. +- SDDM: `ReuseSession=true` is set here, since coming back to a session relies on it. + ## 0.9.0 (2026-11-03) The lock screen can switch user and turn the machine off without unlocking. diff --git a/Justfile b/Justfile index 7b22694..aceec52 100644 --- a/Justfile +++ b/Justfile @@ -7,7 +7,7 @@ default: test: test-js test-sh lint greeter-smoke visudo -cf etc/sudoers.d/omarchy-multiuser -# The greeter's pure helpers (UserList.js, Strings.js). +# The greeter's pure helpers (Password.js, Strings.js). test-js: node --test tests/js/ diff --git a/README.md b/README.md index 6202ef9..d4b3e7b 100644 --- a/README.md +++ b/README.md @@ -9,28 +9,40 @@ points the Omarchy menu at them. | Omarchy (single owner) | omarchy-multiuser | |---|---| -| Greeter: a password box for the last user | Every user listed by **full name**, plus an optional **Other user…** field for any username | -| Autologin of the owner, for good on encrypted installs | Always the greeter (`zz-omarchy-multiuser.conf`, `omarchy-mu-sddm-guard`) | +| One password opens the disk, logs in and is root's | **Each person's password is their own LUKS key slot**: typing it at the disk prompt or the login screen says who they are | +| Greeter: a password box for the last user | A password box that **finds the account**: no list, no username (`omarchy-mu-login-match`) | +| Autologin of the owner, for good on encrypted installs | One automatic login, at that boot, for **whoever opened the disk** (`omarchy-mu-login-select`); the login screen any other time | | `omarchy-setup-security-fido2` writes `/etc/fido2/fido2` for one user and refuses a second | Each user adds their own line (`omarchy-mu-setup-security-fido2`); several keys per user | | `omarchy-remove-security-{fido2,fingerprint}` tear PAM and packages down for everyone | Each user removes their own keys/prints; machine-wide teardown only when nobody has any left | | `omarchy-apply-lock` drops fingerprint unlock if *the caller* has no prints | Kept while *any* user has prints (`omarchy-mu-apply-lock`, re-run by a path unit) | | Migrations stall for users outside `wheel` | Run what they can, privileged parts gated on an admin's run (`omarchy-mu-migrate`) | | Root has the owner's password; ISO installs grant the owner sudo by name | Root locked while there are several accounts; sudo grants by name or UID removed with the account (`omarchy-mu-accounts`) | | Update lock per user, update log at a fixed `/tmp` path | One machine-wide lock for administrators' updates and migrations, also from the migrations notice; a finished update's log moved aside | -| — | `omarchy-mu-user-add`, `omarchy-mu-user-remove`, `omarchy-mu-user-admin`, `omarchy-mu-luks-enroll` | +| — | `omarchy-mu-user-add`, `omarchy-mu-user-remove`, `omarchy-mu-user-admin`, `omarchy-mu-user-password` | ## The lock screen `shell/lock` is Omarchy's own lock screen (`upstream/shell/plugins/lock`, the `omarchy.lock` plugin) with, at the bottom, what doesn't need unlocking: -- **Switch user** (F5): a new login screen, the session staying locked behind it; +- **Switch user** (F5): the login screen, the session staying locked behind it; - **Suspend** (F1), **Reboot** (F3) and **Shut down** (F4), the greeter's keys. Reboot and Shut down ask first: Enter or a click confirms; Esc, typing or - 10 seconds cancels. A key or click that wakes a dark screen only wakes it. + 10 seconds cancels. A click or an F key that wakes a dark screen only wakes it; + a letter or a space also goes into the password box, as on Omarchy's own lock. Each is there only when the machine can do it (`omarchy-mu-lock-action -capabilities`); Suspend follows the same switches as the system menu. +capabilities`); Suspend follows the same switches as the system menu. Switch user +also waits for the first console: SDDM 0.21 puts a new greeter there, and with an +automatic login's desktop holding it that greeter fails and the screen stays dark. +So on a desktop opened by the disk prompt, which is an automatic login, it appears +only once you have logged out and back in at the login screen. + +**System › Switch User** in the menu does the same from an open desktop, for +anyone once there are two accounts: it locks this desktop, then opens the person's +running session, where their own lock asks for their password, or the login screen. +With an automatic login's desktop on the first console it offers to log out instead. +A session left unlocked on another console is opened as it is, as Ctrl+Alt+F*n* would. `omarchy-mu-login` enables it once per account, as `lbssousa.lock`, in place of `omarchy.lock`. To go back: `omarchy plugin disable lbssousa.lock`; it stays off. @@ -42,55 +54,73 @@ twice: SDDM asks logind to unlock it, and a lock left with Switch user listens f that until it ends. A lock left any other way doesn't. Telling logind to unlock someone else's session takes an administrator's password (polkit's `lock-sessions`), but the session's own programs can do it while it waits in the -background. Anyone at the keyboard can reboot or shut down from here, as they can from the greeter, +background. A password or fingerprint accepted only after the session went to the +background is ignored, and the reader isn't taken back there, so the session can't +open unattended behind the login screen. Anyone at the keyboard can reboot or shut down from here, as they can from the greeter, which also closes the other users' sessions. +## One password, one person + +The model comes from [Omarchy PR #16920](https://github.com/omacom/omarchy/pull/16920): + +- **Every account's password is also its own LUKS key slot**, recorded in + `/etc/omarchy-multiuser/slots` (` `, root's alone, no key material). A password has at least 6 + characters and opens no other account or slot: it is what says who you are. +- **The disk prompt picks the person.** Once the map exists, the boot image carries a + small `cryptsetup` wrapper after `encrypt` (`omarchy-mu-luks-slot`), which runs the + real unlock once, keeps its exit status and only then notes which slot opened the + disk. `omarchy-mu-login-select`, before every SDDM start, turns that into one + automatic login for the slot's owner. Anything else shows the login screen: no + record, an unknown slot, a password changed with plain `passwd`, a change left + unfinished, a second SDDM start. With one account on an encrypted disk, that account + is logged in, as Omarchy does. +- **The login screen is a password box alone.** Enter tries it for the last account, + then each other one SDDM lists, until one logs in. `omarchy-mu-login-match` runs first + in `/etc/pam.d/sddm` (`omarchy-mu-sddm-guard` keeps it there) and ends an attempt when + the password is another account's, so the wrong account costs neither a delay nor a + failed-login strike. A password that is nobody's counts once against each account. +- **Changes go through `omarchy-mu-user-password`** (*Update › Password › User*, and + *Setup › Users › Change Password* for administrators), with `omarchy-mu-user-helper` + as root behind it. Each change is journaled, keeps the old password working until the + new one is proven everywhere, and is rolled back or forward by the next run if it + stopped part way. Adding a key takes a key the disk already knows, so it asks for + your own password. + +What it costs: + +- **Every password opens the whole disk**, and the disk is as strong as the weakest one. + With a live USB, anyone with a password can read and change everything. +- **A desktop opened by the disk prompt holds the first console**, where SDDM 0.21 can't + put a login screen. From there, switching reaches only people already signed in; + for anyone else, log out first (*System › Switch User* offers it). Someone who logs in + at the login screen has no such limit. +- **New accounts need their password up front.** There is no list to pick them from, so + they can no longer choose it at their first login. +- **Boot code of our own.** The wrapper sits in the initramfs. It is checked with + `busybox ash -n` at build time and left out if it doesn't parse. Omarchy's PR ran + it through Plymouth and the console on real installs; a wrong copy here could stop the + disk from opening, so keep a live USB at hand the first time. Each slot also adds a key + derivation, about a second, to a wrong password at the disk prompt. +- **Accounts SDDM doesn't list can't log in here** (UIDs outside `MinimumUid`..`MaximumUid`, + or on directory accounts): use a text console. +- **Apple Silicon** refuses a second person's slot until its boot package records them, + and a systemd initramfs (no `encrypt` hook) shows the login screen after the disk prompt. + +**Coming from an earlier version.** Run `omarchy-mu-user-password` for each person, yours +first. Your login password has to open the disk; if it doesn't, make them the same with +`omarchy-drive-password`. Slots recorded by the old `omarchy-mu-luks-enroll` are replaced +then. Until then the machine shows the login screen after the disk prompt, and accounts +that were waiting to choose a password can't log in. + ## The greeter `/usr/share/sddm/themes/omarchy-multiuser` is Omarchy's own theme -(`upstream/sddm/omarchy/Main.qml`) with a user list above the password row: - -- one row per account SDDM lists (uid ≥ 1000, a login shell), showing the - GECOS full name, or the username when it is empty, with the username in - small print underneath; -- the last user preselected (`RememberLastUser`); -- a last **Outro usuário… / Other user…** row that reveals a username field; -- ↑/↓ (which wrap around) or the mouse wheel over the list change the user from - either field, Tab moves between username and password, Enter logs in, Esc - clears the password, a click selects. -- an account that chooses its password at this login — an empty, expired - password, what `omarchy-mu-user-add` leaves by default and - `omarchy-mu-accounts first-login ` gives a locked account — gets - **Nova senha** and **Repita a senha** boxes instead, and logs in once both - match; -- at the bottom, **Suspend** (F1), **Hibernate** (F2), **Reboot** (F3) and - **Shut down** (F4), by click or key, each only when SDDM says the machine can - do it. An action keeps its key when another is missing. Reboot and Shut down - ask first: Enter or a click confirms; Esc, typing or 10 seconds cancels. - -SDDM has no way to show PAM's "new password" prompts: it answers translated -ones with what was typed in the greeter. For such an account that text becomes -the new password at once, so the greeter has it typed twice first. -`omarchy-mu-sddm-sync` lists these accounts in `theme.conf.user` -(`passwordChangeUsers`), rerun whenever `/etc/shadow` changes; an account -PAM reports as expired after that is added on the spot. An expired password -that isn't empty can't be changed from the greeter (PAM would get the old -password as the new one): log in on a text console for that. - -Limits of choosing the password at the login screen: - -- **Language.** It needs PAM's prompts translated, as `/etc/locale.conf` has - them: SDDM 0.21 recognizes the English "New password", answers it with the - user name and the repeat with the typed text, and PAM refuses the change. - `first-login` checks this and refuses; `omarchy-mu-user-add` then asks for - the password as before. -- **First come.** Until the password is chosen, anyone at the login screen or - a text console can choose it, so an administrator's account gives them root. - `su` asks for a password (no `nullok`) and sshd refuses empty ones by default. - `omarchy-mu-user-add --set-password` asks for it up front instead. -- **Keep the stack's `nullok`.** The empty password only gets past - `system-auth` with it. Without it the account can't log in until an - administrator runs `passwd `. +(`upstream/sddm/omarchy/Main.qml`) with the password search above and, at the bottom, +**Suspend** (F1), **Hibernate** (F2), **Reboot** (F3) and **Shut down** (F4), by click or +key, each only when SDDM says the machine can do it. An action keeps its key when another +is missing. Reboot and Shut down ask first: Enter or a click confirms; Esc, typing or 10 +seconds cancels. It keeps following **Appearance › Unlock**: the images come from the stock theme, which `omarchy-plymouth-set` recolors, and `omarchy-mu-sddm-sync` (run by @@ -99,7 +129,7 @@ The recolor applies to everyone's login screen, so the menu offers it to administrators only. Full names come from GECOS: `chfn -f "Full Name" `, or -`omarchy-mu-user-add`, which asks for one. +`omarchy-mu-user-add`, which asks for one. *System › Switch User* shows them. ## Who can do what @@ -110,6 +140,9 @@ Administrators are the members of `wheel`; everyone else is in - add or remove **their own** line in `/etc/fido2/fido2` through `omarchy-mu-fido2-authfile` (the user comes from `SUDO_USER`, never from the arguments), with their own password; +- change **their own** password through `omarchy-mu-user-helper password-self`, + which takes the user from `SUDO_USER`, asks for the current password and allows + three tries an hour; - re-run `omarchy-mu-apply-lock`, which takes no input, without a password. The same helper also runs through `pkexec`, for the @@ -148,8 +181,9 @@ administrator's theme set. ## Accounts and root -`omarchy-mu-user-add` and `-remove` hold `/run/lock/omarchy-mu-accounts.lock` -(as does `omarchy-mu-luks-enroll`), so two account changes never interleave. +`omarchy-mu-user-add` and `-remove` hold `/run/lock/omarchy-mu-accounts.lock`, +so two account changes never interleave, and `omarchy-mu-user-helper` holds +`omarchy-mu-slots.lock` (root's alone) for each password change. The lock files come from `tmpfiles.d`, `root:wheel 0640`: only administrators can open them. @@ -171,7 +205,9 @@ administrators can open them. (`--keep-home` and `--delete-home` answer for it; keeping is the default answer), and every question comes before anything changes. An account with programs running, in a session or not, is logged out if you agree, and its - lingering turned off. A home holding the note of an unfinished disk password + lingering turned off. SDDM shows nothing on the first console after a desktop it + logged in automatically is forced to end, so it is asked for the login screen, + which takes over the screen; Ctrl+Alt+F*n* goes back to your console. A home holding the note of an unfinished disk password change (`drive-password.state`) isn't deleted. System accounts are refused, and the last administrator is the last one who can log in. - **Administrator rights.** `omarchy-mu-user-admin on|off` diff --git a/bin/omarchy-mu-accounts b/bin/omarchy-mu-accounts index 281e3e7..a732ee1 100755 --- a/bin/omarchy-mu-accounts +++ b/bin/omarchy-mu-accounts @@ -32,13 +32,9 @@ # root that account's password hash back (the installer's # setup), but only when it is the caller's and an # administrator's -# first-login let , whose password is locked, choose it at the -# login screen: an empty password that has to be changed, -# in one write. Refused, the account staying locked, when -# it has a password or the greeter can't take a new one # # Usage: omarchy-mu-accounts ensure-wheel-sudo|drop-grants |check-root | -# sync-migration-watchers|lock-root|root-sync|first-login +# sync-migration-watchers|lock-root|root-sync set -euo pipefail @@ -208,47 +204,6 @@ root_sync() { echo "Root has $user's password again, as with a single owner." } -# What the greeter needs to set a password. The daemon answers a prompt it reads -# as "new password" (an English one: SDDM 0.21 matches the words) as part of a -# pair, with the user name as the new password and the typed text as the repeat, -# so PAM refuses the change. A translated prompt goes one at a time and gets the -# typed text. SDDM runs in the locale of /etc/locale.conf. -greeter_takes_new_password() { - local prompt - if [[ ! -f $OMU_SDDM_THEMES/$OMU_THEME/Main.qml ]]; then - echo "The multi-user greeter isn't installed." >&2 - return 1 - fi - prompt=$( - unset LANG LANGUAGE - # shellcheck disable=SC1091 # the machine's, not this package's - [[ ! -r $OMU_ROOT/etc/locale.conf ]] || . "$OMU_ROOT/etc/locale.conf" - LANGUAGE=${LANGUAGE:-} LC_ALL=${LANG:-C} gettext -d Linux-PAM 'New password: ' - ) || return 1 - if [[ -z $prompt || ${prompt,,} == *new*password* ]]; then - echo "SDDM can't take a new password in this machine's language (PAM asks \"${prompt:-?}\")." >&2 - return 1 - fi -} - -first_login() { - local user=$1 hash - omu_human_users | grep -qx -- "$user" || omu_die "$user isn't an account people log in to." - hash=$(getent shadow "$user" | cut -d: -f2) - # Only ever opens an account nobody can log in to yet. - [[ -z $hash || $hash == '!'* || $hash == '*'* ]] || omu_die "$user already has a password." - greeter_takes_new_password || omu_die "$user can't choose a password at the login screen." - # -e after -d, in the same run: passwd -d alone counts as a password change, - # which would leave an empty password that nothing asks to replace. - passwd -d -e "$user" >/dev/null || true - if [[ $(getent shadow "$user" | cut -d: -f2,3) != ":0" ]]; then - usermod -L "$user" || true - omu_die "Couldn't set $user up for the first login; the password stays locked." - fi - # The path unit does this too, but the next greeter shouldn't depend on it. - omarchy-mu-sddm-sync >/dev/null || echo "Warning: the greeter doesn't list $user yet: run omarchy-mu-sddm-sync." >&2 -} - case ${1:-} in ensure-wheel-sudo) ensure_wheel_sudo ;; drop-grants) @@ -262,9 +217,5 @@ case ${1:-} in sync-migration-watchers) sync_migration_watchers ;; lock-root) lock_root ;; root-sync) root_sync ;; - first-login) - [[ -n ${2:-} ]] || omu_die "Usage: omarchy-mu-accounts first-login " - first_login "$2" - ;; - *) omu_die "Usage: omarchy-mu-accounts ensure-wheel-sudo|drop-grants |check-root |sync-migration-watchers|lock-root|root-sync|first-login " ;; + *) omu_die "Usage: omarchy-mu-accounts ensure-wheel-sudo|drop-grants |check-root |sync-migration-watchers|lock-root|root-sync" ;; esac diff --git a/bin/omarchy-mu-lock-action b/bin/omarchy-mu-lock-action index 327d323..7779d51 100755 --- a/bin/omarchy-mu-lock-action +++ b/bin/omarchy-mu-lock-action @@ -11,11 +11,14 @@ # watch-unlock prints logind's signals for this session until killed # wait-active exits 0 once this session is in the foreground and has had # a moment to settle, 1 if it isn't within 5 seconds -# switchUser a new login screen; this session stays locked behind it +# switchUser the login screen; this session stays locked behind it # suspend | reboot | powerOff set -uo pipefail +# shellcheck source=../lib/omarchy-multiuser/common.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" + seat=${XDG_SEAT_PATH:-/org/freedesktop/DisplayManager/Seat0} # "yes" only: "challenge" would ask polkit for a password, in a prompt the lock @@ -27,7 +30,15 @@ logind_can() { can_switch() { [[ $(busctl get-property org.freedesktop.DisplayManager "$seat" \ - org.freedesktop.DisplayManager.Seat CanSwitch 2>/dev/null) == "b true" ]] + org.freedesktop.DisplayManager.Seat CanSwitch 2>/dev/null) == "b true" ]] && omu_first_console_free +} + +# The greeter already running, left by coming straight back to this session. +# SDDM 0.21 would start a second one on its console, and that one fails with +# nothing left on the screen. +greeter_session() { + loginctl list-sessions --json=short 2>/dev/null | + jq -r 'first(.[] | select(.class == "greeter" and .seat == "seat0") | .session) // empty' 2>/dev/null } # The same conditions as the suspend entry in Omarchy's system menu. @@ -72,6 +83,10 @@ wait-active) exit 1 ;; switchUser) + greeter=$(greeter_session) + if [[ -n $greeter ]] && loginctl activate "$greeter" 2>/dev/null; then + exit 0 + fi busctl call org.freedesktop.DisplayManager "$seat" \ org.freedesktop.DisplayManager.Seat SwitchToGreeter ;; diff --git a/bin/omarchy-mu-login-match b/bin/omarchy-mu-login-match new file mode 100755 index 0000000..c94e88c --- /dev/null +++ b/bin/omarchy-mu-login-match @@ -0,0 +1,50 @@ +#!/bin/bash -p + +# omarchy:summary=End a login attempt whose password belongs to another account, from SDDM's PAM stack +# omarchy:hidden=true +# +# The login screen asks for a password alone and tries each account in turn, as +# the disk prompt does. This runs first in SDDM's auth stack, as +# `[success=die default=ignore]`: it succeeds, ending the attempt, only when the +# password is another account's, so trying the wrong account first costs neither +# pam_unix's delay nor a failed-login strike. A password that is nobody's, and any +# failure of this script, fall through to the usual stack and count as before. + +set -uo pipefail +set +x +[[ -n ${OMU_ROOT:-} ]] || export PATH=/usr/local/sbin:/usr/local/bin:/usr/bin +umask 077 + +# shellcheck source=../lib/omarchy-multiuser/common.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" || exit 1 +# shellcheck source=../lib/omarchy-multiuser/slots.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/slots.sh" || exit 1 + +(( EUID == 0 )) || [[ -n $OMU_ROOT ]] || exit 1 +[[ ${PAM_TYPE:-} == auth ]] || exit 1 +user=${PAM_USER:-} +[[ $user =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || exit 1 + +# pam_exec's expose_authtok hands over the password ending in a NUL. +password="" +IFS= read -r -d '' password || [[ -n $password ]] || exit 1 + +# A stalled lookup must not hold every login: past the deadline this ends +# nonzero, which leaves the attempt to the usual stack. +( sleep 10; pkill -KILL -P $$; kill -KILL $$ ) 2>/dev/null & +watchdog=$! + +# Only an owner with no failed logins on record ends the attempt early. A locked +# owner's password then takes the same slow refusal as any wrong one, so a fast +# refusal never tells a guesser what a lockout is hiding. +match() { + local owner + omu_password_matches "$password" "$user" && return 1 + owner=$(omu_password_owner "$password") || return 1 + [[ $owner != "$user" ]] && ! omu_has_failed_logins "$owner" +} + +match +status=$? +kill "$watchdog" 2>/dev/null +exit "$status" diff --git a/bin/omarchy-mu-login-select b/bin/omarchy-mu-login-select new file mode 100755 index 0000000..d96120f --- /dev/null +++ b/bin/omarchy-mu-login-select @@ -0,0 +1,64 @@ +#!/bin/bash + +# omarchy:summary=Choose whose desktop SDDM opens at this start +# omarchy:requires-sudo=true +# omarchy:hidden=true +# +# Runs as root before every SDDM start (sddm.service.d/omarchy-mu-login-select.conf). +# --clear runs first and must succeed for SDDM to start: it takes away any automatic +# login. The second run then names, in the last-sorting drop-in, the one account on +# an encrypted disk or, with more than one, the account whose key slot unlocked the +# disk this boot, used once. Anything it can't be sure of shows the login screen. +# +# Usage: omarchy-mu-login-select [--clear] + +set -uo pipefail + +# shellcheck source=../lib/omarchy-multiuser/common.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" +# shellcheck source=../lib/omarchy-multiuser/slots.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/slots.sh" + +umask 022 +managed=$OMU_SDDM_AUTOLOGIN +mapfile -t accounts < <(omu_human_users) + +autologin() { + mkdir -p "${managed%/*}" && + printf '[Autologin]\nUser=%s\nSession=omarchy.desktop\nRelogin=false\n' "$1" >"$managed.tmp" && + mv -f "$managed.tmp" "$managed" +} + +if [[ ${1:-} == --clear ]]; then + rm -f "$OMU_SDDM_CONF_DIR/autologin.conf" "$managed" || exit 1 + # /etc/sddm.conf outranks every drop-in; a desktop would open for whoever + # starts the computer. omarchy-mu-user-add refuses this; a later edit stops here. + if (( ${#accounts[@]} > 1 )) && omu_fixed_autologin; then + echo "/etc/sddm.conf logs someone in automatically on a computer with more than one person; remove its [Autologin] User=." >&2 + exit 1 + fi + exit 0 +fi + +# The record the unlock left, renamed so no later start this boot reuses it. +consume_slot_record() { + local record=$OMU_SLOT_RECORD.used + [[ -f $OMU_SLOT_RECORD ]] || return 1 + mv -f "$OMU_SLOT_RECORD" "$record" || return 1 + cat "$record" +} + +omu_load_drive || exit 1 +omu_encrypted || exit 0 + +if (( ${#accounts[@]} == 1 )); then + autologin "${accounts[0]}" +elif (( ${#accounts[@]} > 1 )); then + read -r uuid slot < <(consume_slot_record) || exit 0 + [[ $uuid == "$OMU_UUID" && $slot =~ ^[0-9]+$ ]] || exit 0 + ! omu_journal_pending || exit 0 + omu_map_valid || exit 0 + user=$(omu_map_user_for_slot "$uuid" "$slot") + [[ -n $user ]] && printf '%s\n' "${accounts[@]}" | grep -qx -- "$user" && omu_in_sync "$user" || exit 0 + autologin "$user" +fi diff --git a/bin/omarchy-mu-luks-enroll b/bin/omarchy-mu-luks-enroll deleted file mode 100755 index e6124b7..0000000 --- a/bin/omarchy-mu-luks-enroll +++ /dev/null @@ -1,109 +0,0 @@ -#!/bin/bash - -# omarchy:summary=Give a user their own password for unlocking the disk -# omarchy:requires-sudo=true -# -# omarchy-provision-owner re-keys the encrypted root to the owner's password -# and removes every other keyslot. This adds a keyslot for another user (any -# existing disk password is needed to authorize it) and records which slot is -# theirs in /etc/omarchy-multiuser/luks-slots, so --remove can drop exactly -# that one. The boot prompt is the same for everyone; whichever password -# matches a slot unlocks the disk. -# -# Usage: omarchy-mu-luks-enroll [] add a keyslot for -# omarchy-mu-luks-enroll --remove remove the recorded keyslot -# omarchy-mu-luks-enroll --list -# -# Takes the account-change lock, unless --locked says the caller -# (omarchy-mu-user-add/-remove) already holds it. - -set -euo pipefail - -# shellcheck source=../lib/omarchy-multiuser/common.sh -source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" - -if (( EUID != 0 )); then - exec sudo "$0" "$@" -fi - -registry=$OMU_ROOT/etc/omarchy-multiuser/luks-slots - -if [[ ${1:-} == --locked ]]; then - shift -elif [[ ${1:-} != --list ]]; then - omu_hold_lock accounts || omu_die "Another account change is in progress." -fi - -# The LUKS device holding root: crypttab's "root" entry, else the kernel -# command line (cryptdevice= or rd.luks.uuid=). -luks_device() { - local spec="" arg - if [[ -f /etc/crypttab ]]; then - spec=$(awk '!/^#/ && $1 == "root" { print $2; exit }' /etc/crypttab) - fi - if [[ -z $spec ]]; then - for arg in $(" - slot=$(awk -v u="$user" '$1 == u { print $2 }' "$registry" 2>/dev/null | tail -1) - if [[ -z $slot ]]; then - echo "No disk keyslot recorded for $user." - exit 0 - fi - (( $(slots "$device" | wc -l) > 1 )) || omu_die "Keyslot $slot is the last one; refusing to lock the disk for good." - echo "Removing $user's disk keyslot ($slot); authorize with any disk password." - cryptsetup luksKillSlot "$device" "$slot" - grep -v "^$user " "$registry" | omu_atomic_write "$registry" 600 - omu_info "Removed $user's disk password." - exit 0 - ;; -esac - -user=${1:-} -if [[ -z $user ]]; then - mapfile -t candidates < <(omu_human_users) - user=$(gum choose --header "Add a disk password for which user?" "${candidates[@]}") || exit 1 -fi -getent passwd "$user" >/dev/null || omu_die "No such user: $user" - -echo "Adding a disk password for $user on $device." -echo "First type an EXISTING disk password, then $user types their new one (twice)." -echo "Tip: keep a header backup: cryptsetup luksHeaderBackup $device --header-backup-file " - -before=$(slots "$device") -cryptsetup luksAddKey "$device" -after=$(slots "$device") -slot=$(comm -13 <(echo "$before") <(echo "$after") | head -1) -[[ -n $slot ]] || omu_die "Couldn't tell which keyslot was added." - -install -d -m 700 "$(dirname "$registry")" -{ grep -v "^$user " "$registry" 2>/dev/null || true; echo "$user $slot"; } | omu_atomic_write "$registry" 600 -omu_info "$user can now unlock the disk with their own password (keyslot $slot)." diff --git a/bin/omarchy-mu-sddm-guard b/bin/omarchy-mu-sddm-guard index c8f1a40..98dd476 100755 --- a/bin/omarchy-mu-sddm-guard +++ b/bin/omarchy-mu-sddm-guard @@ -1,16 +1,15 @@ #!/bin/bash -# omarchy:summary=Keep SDDM showing the multi-user greeter, with no autologin +# omarchy:summary=Keep SDDM on the multi-user greeter, with only the automatic login it chooses # omarchy:requires-sudo=true # omarchy:hidden=true # # Omarchy logs its single owner in automatically: omarchy-provision-owner and -# omarchy-upgrade-to-quattro write /etc/sddm.conf.d/autologin.conf, which -# stays on for good on encrypted installs, and unencrypted ones get a -# self-deleting omarchy-provision-autologin-once.service. With several users -# that skips the greeter, so this removes both. The package's -# zz-omarchy-multiuser.conf (read last, with an empty [Autologin]) already -# overrides them; this keeps the files from lingering and checks the result. +# omarchy-upgrade-to-quattro write /etc/sddm.conf.d/autologin.conf, and unencrypted +# installs get a self-deleting omarchy-provision-autologin-once.service. Who is +# logged in is omarchy-mu-login-select's to say, at each SDDM start, so this removes +# both, and checks the result. It also keeps omarchy-mu-login-match first in SDDM's +# PAM stack, where an upgrade of sddm may leave a new /etc/pam.d/sddm without it. # # Run by omarchy-mu-sddm-guard.path when /etc/sddm.conf.d changes and by the # pacman hook. Never restarts sddm, which would end every open session. @@ -26,6 +25,21 @@ check=false [[ ${1:-} == --check ]] && check=true problems=0 +# Before the first auth line, whatever its indentation; only an active line counts. +login_match="auth [success=die default=ignore] pam_exec.so quiet expose_authtok /usr/bin/omarchy-mu-login-match" +pam=$OMU_PAM_DIR/sddm +if [[ -f $pam ]] && ! grep -Eq '^[[:space:]]*auth[[:space:]].*/usr/bin/omarchy-mu-login-match' "$pam"; then + if $check; then + echo "login-match: not in $pam" >&2 + problems=1 + elif grep -Eq '^[[:space:]]*-?auth[[:space:]]' "$pam"; then + sed -E -i "0,/^[[:space:]]*-?auth[[:space:]]/s||$login_match\n&|" "$pam" + echo "Added omarchy-mu-login-match to $pam." + else + echo "No auth line in $pam; the login screen will count a wrong account as a failed login." >&2 + fi +fi + autologin=$OMU_SDDM_CONF_DIR/autologin.conf if [[ -e $autologin || -L $autologin ]]; then if $check; then @@ -46,12 +60,12 @@ fi # SDDM reads /etc/sddm.conf.d/*.conf in name order, then /etc/sddm.conf; the # last value of a key wins. Report what the effective theme and autologin -# user are. +# user are, leaving out the automatic login omarchy-mu-login-select chose. effective() { local section=$1 key=$2 file value="" local files=("$OMU_SDDM_CONF_DIR"/*.conf "$OMU_ROOT/etc/sddm.conf") for file in "${files[@]}"; do - [[ -f $file ]] || continue + [[ -f $file && $file != "$OMU_SDDM_AUTOLOGIN" ]] || continue local v v=$(awk -F= -v s="[$section]" -v k="$key" ' /^\[/ { insec = ($0 == s) } diff --git a/bin/omarchy-mu-sddm-sync b/bin/omarchy-mu-sddm-sync index f8b1e50..5fa5148 100755 --- a/bin/omarchy-mu-sddm-sync +++ b/bin/omarchy-mu-sddm-sync @@ -1,6 +1,6 @@ #!/bin/bash -# omarchy:summary=Copy Appearance > Unlock's greeter colors and first-login accounts to the multi-user greeter +# omarchy:summary=Copy Appearance > Unlock's greeter colors to the multi-user greeter # omarchy:requires-sudo=true # omarchy:hidden=true # @@ -13,20 +13,7 @@ # background the first `color: "#rrggbb"` in the stock Main.qml # textColor the center pixel of the stock bullet.png # -# and the accounts that must choose their password at the next login, which -# the greeter asks for twice instead of the usual password: -# -# passwordChangeUsers accounts with an empty password that has to be -# changed (omarchy-mu-accounts first-login), -# space-separated: QSettings reads "a,b" as a list, -# and SDDM drops lists from theme.conf.user -# -# SDDM answers translated PAM prompts with what was typed in the greeter, so -# for such an account the new password is whatever goes in the box: the greeter -# needs to know beforehand to have it confirmed. -# -# Run by omarchy-mu-sddm-sync.path whenever the stock theme or /etc/shadow -# changes, by the pacman hook and on package install. Without ImageMagick or +# Run by omarchy-mu-sddm-sync.path whenever the stock theme changes, by the pacman hook and on package install. Without ImageMagick or # the stock files it leaves theme.conf's colors alone. set -euo pipefail @@ -52,17 +39,9 @@ if [[ -f $stock/bullet.png ]] && command -v magick >/dev/null; then [[ $hex =~ ^[0-9A-Fa-f]{6} ]] && text="#${hex:0:6}" fi -# Empty password field (not "!" or "*": those are locked) and last change -# on day 0, which is what `chage -d 0` sets. -change_users="" -if [[ -r $OMU_SHADOW ]]; then - change_users=$(awk -F: '$2 == "" && $3 == "0" { print $1 }' "$OMU_SHADOW" | paste -sd' ' -) -fi - content="[General]" [[ -n $background ]] && content+=$'\n'"background=$background" [[ -n $text ]] && content+=$'\n'"textColor=$text" -[[ -n $change_users ]] && content+=$'\n'"passwordChangeUsers=$change_users" if [[ $content == "[General]" ]]; then rm -f "$conf" @@ -72,5 +51,4 @@ fi if [[ ! -f $conf || $(<"$conf") != "$content" ]]; then printf '%s\n' "$content" | omu_atomic_write "$conf" 644 echo "Greeter colors: background=${background:-default} text=${text:-default}" - [[ -z $change_users ]] || echo "Greeter asks for a new password: ${change_users// /, }" fi diff --git a/bin/omarchy-mu-user-add b/bin/omarchy-mu-user-add index 056810a..b23f3df 100755 --- a/bin/omarchy-mu-user-add +++ b/bin/omarchy-mu-user-add @@ -17,14 +17,13 @@ # rule when an ISO install granted the owner sudo by name only, and the watcher # that records the migrations it runs. # -# The account stays locked until everything else is done. Then its owner chooses -# the password at the login screen (omarchy-mu-accounts first-login), or, with -# --set-password or when the greeter can't do that here, it is asked for now. -# Until it is chosen, whoever reaches the login screen first can choose it. +# The password is asked here and goes in last: the account stays locked until +# everything else is done. It is also the account's own key to the disk, and what +# picks the account at the disk prompt and the login screen, so it must be nobody +# else's. Adding that key takes your own password. # # Usage: omarchy-mu-user-add [ --full-name ] [--email
] -# [--admin] [--shell ] [--groups g1,g2] [--luks] -# [--set-password] +# [--admin] [--shell ] [--groups g1,g2] # Without a user name it asks for everything. set -euo pipefail @@ -35,7 +34,7 @@ source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" omu_is_admin || omu_die "Only an administrator can add users." omu_hold_lock accounts || omu_die "Another account change is in progress." -user="" full_name="" email="" admin=false shell=/bin/bash groups="" luks=false set_password=false +user="" full_name="" email="" admin=false shell=/bin/bash groups="" while (($#)); do case $1 in --full-name) full_name=${2:-}; shift 2 ;; @@ -43,8 +42,6 @@ while (($#)); do --admin) admin=true; shift ;; --shell) shell=${2:-}; shift 2 ;; --groups) groups=${2:-}; shift 2 ;; - --luks) luks=true; shift ;; - --set-password) set_password=true; shift ;; -h|--help) sed -n '3,/^set -euo/{/^set -euo/d;s/^# \{0,1\}//;p}' "$0"; exit 0 ;; -*) omu_die "Unknown option: $1" ;; *) user=$1; shift ;; @@ -56,8 +53,6 @@ if [[ -z $user ]]; then full_name=$(gum input --placeholder "Full name, as the login screen shows it" --header "Full name") || exit 1 email=$(gum input --placeholder "e-mail (optional, for git)" --header "E-mail") || exit 1 gum confirm --default=false "Make $user an administrator (wheel)?" && admin=true - gum confirm --default=false "Let $user unlock the disk with their own password?" && luks=true - gum confirm "Let $user choose their password at the login screen? (Otherwise you set it now.)" || set_password=true fi [[ $user =~ ^[a-z_][a-z0-9_-]{0,31}$ ]] || omu_die "Invalid user name: $user" @@ -66,6 +61,9 @@ getent group "$user" >/dev/null && omu_die "A group named $user already exists." # useradd would keep it, owned by the account it was kept for (the new one # never gets that UID), and the new account couldn't use its own home. [[ ! -e $OMU_HOME_DIR/$user ]] || omu_die "$OMU_HOME_DIR/$user already exists; move it aside first (sudo mv $OMU_HOME_DIR/$user $OMU_HOME_DIR/$user.old)." +# It outranks zz-omarchy-multiuser.conf: the first person would keep being logged +# in automatically, at every boot, with a second one on the machine. +! omu_fixed_autologin || omu_die "/etc/sddm.conf logs someone in automatically; remove User= from its [Autologin] section first." [[ -n ${full_name//[[:space:]]/} ]] || omu_die "A full name is required (the login screen lists it)." [[ $full_name != *[:,]* && $full_name != *$'\n'* ]] || omu_die "The full name can't contain ':' ',' or line breaks." [[ -x $shell ]] || omu_die "No such shell: $shell" @@ -77,6 +75,12 @@ $admin && group_list+=",$OMU_ADMIN_GROUP" uid=$(omu_free_uid) || omu_die "No free UID left." +# Before anything changes: a password someone else has stops here. +new_password=$(omu_ask_new_password "$user's password") || exit 1 +own_password=$(gum input --password --header "Your password ($(id -un)), the current one") || exit 1 +sudo -v +printf '%s\n' "$new_password" | sudo omarchy-mu-user-helper check-new || exit 1 + sudo groupadd -f "$OMU_USERS_GROUP" $admin && sudo omarchy-mu-accounts ensure-wheel-sudo sudo omarchy-mu-accounts lock-root @@ -103,20 +107,8 @@ if $admin; then echo "Warning: the migrations $user runs won't be recorded; run: sudo omarchy-mu-accounts sync-migration-watchers" >&2 fi -if $luks; then - sudo omarchy-mu-luks-enroll --locked "$user" -fi - -if ! $set_password && sudo omarchy-mu-accounts first-login "$user"; then - omu_info "\n$user chooses their password at their first login: select them on the login screen, type it twice." - echo "Until then, anyone at the login screen can choose it." - $admin && echo "Warning: $user is an administrator, so that person would get root. Have them log in soon." >&2 - exit 0 +if ! printf '%s\n%s\n' "$own_password" "$new_password" | sudo omarchy-mu-user-helper password "$user"; then + omu_die "$user has no password yet, so nobody can log in as them. Run: omarchy-mu-user-password $user" fi -echo "Set $user's password:" -until sudo passwd "$user"; do - echo "Try again." -done - -omu_info "\n$user can now log in from the login screen." +omu_info "\n$user can now log in by typing their password, at the disk prompt or the login screen." diff --git a/bin/omarchy-mu-user-helper b/bin/omarchy-mu-user-helper new file mode 100755 index 0000000..f7baf56 --- /dev/null +++ b/bin/omarchy-mu-user-helper @@ -0,0 +1,97 @@ +#!/bin/bash + +# omarchy:summary=Root's side of changing passwords: the login and the disk key together +# omarchy:requires-sudo=true +# omarchy:hidden=true +# +# Called through sudo; authorises every request itself, by SUDO_USER and nothing +# from the arguments. Passwords come on stdin, one per line, never in argv. +# +# check-new new password may this be someone's next password? +# password caller's password, new password (administrators) +# password-self caller's password, new password (anyone, for themselves; +# sudoers grants it to omarchy-users without a password, and +# three tries an hour keep it from being a way to test guesses) +# forget take the account's key off the disk (administrators) +# finish finish a change that stopped part way (administrators) +# +# Usage: omarchy-mu-user-helper check-new|password |password-self|forget |finish + +set -euo pipefail +set +x + +# shellcheck source=../lib/omarchy-multiuser/common.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" +# shellcheck source=../lib/omarchy-multiuser/slots.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/slots.sh" + +if (( EUID != 0 )) && [[ -z $OMU_ROOT ]]; then + exec sudo "$0" "$@" +fi +umask 077 + +caller=${SUDO_USER:-} +omu_human_users | grep -qx -- "$caller" || omu_die "Run this through sudo, from a person's account." + +require_admin() { + omu_is_admin "$caller" || omu_die "Only an administrator can do that." +} + +require_person() { + omu_human_users | grep -qx -- "${1:-}" || omu_die "There is no user named ${1:-}." +} + +# Three an hour, counted whether or not they go through. +self_allowed() { + local state now recent + mkdir -p "$OMU_RATE_DIR" + state=$OMU_RATE_DIR/$(getent passwd "$caller" | cut -d: -f3) + now=$(date +%s) + recent="" + [[ ! -f $state ]] || recent=$(awk -v since=$(( now - 3600 )) '$1 > since' "$state") + if (( $(grep -c . <<<"$recent") >= 3 )); then + omu_die "That's three password changes this hour. Try again later, or ask an administrator." + fi + { [[ -z $recent ]] || printf '%s\n' "$recent"; echo "$now"; } >"$state" +} + +read_secrets() { + IFS= read -r caller_password || [[ -n ${caller_password:-} ]] || omu_die "No password given." + IFS= read -r new_password || [[ -n ${new_password:-} ]] || omu_die "No new password given." +} + +omu_hold_lock slots || omu_die "Another password change is in progress." +omu_load_drive || exit 1 + +action=${1:-} +case $action in + check-new) + require_admin + IFS= read -r new_password || [[ -n ${new_password:-} ]] || omu_die "No password given." + omu_check_new_password "$new_password" "" + ;; + password) + require_admin + require_person "${2:-}" + read_secrets + omu_slots_finish + omu_slots_change_password "$caller" "$2" "$new_password" "$caller_password" + ;; + password-self) + omu_is_admin "$caller" || self_allowed + read_secrets + omu_slots_finish + omu_slots_change_password "$caller" "$caller" "$new_password" "$caller_password" + ;; + forget) + require_admin + require_person "${2:-}" + omu_slots_finish + omu_slots_forget "$2" + ;; + finish) + require_admin + omu_slots_finish + ;; + *) omu_die "Usage: omarchy-mu-user-helper check-new|password |password-self|forget |finish" ;; +esac diff --git a/bin/omarchy-mu-user-password b/bin/omarchy-mu-user-password new file mode 100755 index 0000000..646200f --- /dev/null +++ b/bin/omarchy-mu-user-password @@ -0,0 +1,41 @@ +#!/bin/bash + +# omarchy:summary=Change a password: the login, the lock screen and the disk together +# +# Each account's password also opens the disk and tells the machine who you are, +# so plain passwd leaves the disk key behind. Administrators can change anyone's, +# with their own password; everyone else their own. +# +# Usage: omarchy-mu-user-password [] + +set -euo pipefail + +# shellcheck source=../lib/omarchy-multiuser/common.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" + +me=$(id -un) +user=${1:-} +if [[ -z $user ]]; then + if omu_is_admin; then + mapfile -t candidates < <(omu_human_users) + user=$(gum choose --header "Change whose password?" "${candidates[@]}") || exit 1 + else + user=$me + fi +fi +[[ $user == "$me" ]] || omu_is_admin || omu_die "Only an administrator can change someone else's password." + +new_password=$(omu_ask_new_password "New password for $user") || exit 1 +own=$(gum input --password --header "Your password ($me), the current one") || exit 1 + +if omu_is_admin; then + sudo -v + if [[ $user == "$me" ]]; then + printf '%s\n%s\n' "$own" "$new_password" | sudo omarchy-mu-user-helper password-self + else + printf '%s\n%s\n' "$own" "$new_password" | sudo omarchy-mu-user-helper password "$user" + fi +else + printf '%s\n%s\n' "$own" "$new_password" | sudo -n omarchy-mu-user-helper password-self +fi +omu_info "$user's password changed, for the login screen, the lock screen and the disk." diff --git a/bin/omarchy-mu-user-remove b/bin/omarchy-mu-user-remove index 413275c..fecfebb 100755 --- a/bin/omarchy-mu-user-remove +++ b/bin/omarchy-mu-user-remove @@ -86,7 +86,9 @@ fi sudo omarchy-mu-fido2-authfile remove --user "$user" >/dev/null 2>&1 || true sudo fprintd-delete "$user" >/dev/null 2>&1 || true -sudo omarchy-mu-luks-enroll --locked --remove "$user" || true +# Before userdel: running this again still knows whose keyslot it is. +sudo omarchy-mu-user-helper forget "$user" || + omu_die "$user's password still opens the disk, so the account stays. Run this again to finish." # Before userdel: the grants must not outlive the account, even if this stops. sudo omarchy-mu-accounts drop-grants "$user" diff --git a/bin/omarchy-mu-user-switch b/bin/omarchy-mu-user-switch new file mode 100755 index 0000000..7540dc3 --- /dev/null +++ b/bin/omarchy-mu-user-switch @@ -0,0 +1,75 @@ +#!/bin/bash + +# omarchy:summary=Switch to another person's desktop, locking yours first +# omarchy:args=[NAME] +# +# Their own desktop when they have one running, whose lock asks their password; +# otherwise the login screen. Either way the password is typed on their side of +# the switch, never here. +# +# Usage: omarchy-mu-user-switch [] +# omarchy-mu-user-switch --available exits 0 when there is someone to pick + +set -euo pipefail + +# shellcheck source=../lib/omarchy-multiuser/common.sh +source "$(dirname "$(readlink -f "$0")")/../lib/omarchy-multiuser/common.sh" + +me=$(id -un) +mapfile -t others < <(omu_human_users | grep -vx -- "$me" || true) + +if [[ ${1:-} == --available ]]; then + (( ${#others[@]} > 0 )) + exit +fi + +if (( ${#others[@]} == 0 )); then + omarchy-notification-send -g 󰀄 "There is no one else to switch to." + exit 1 +fi + +name=${1:-} +if [[ -z $name ]]; then + options=() + for other in "${others[@]}"; do + full_name=$(getent passwd "$other" | cut -d: -f5 | cut -d, -f1) + options+=("󰀄"$'\t'"${full_name:-$other}"$'\t'"$other") + done + # The label and the subtext come back: the subtext is the account. + choice=$(omarchy-menu-select "Switch to" "${options[@]}" -- --width 440) || exit 0 + [[ -n $choice ]] || exit 0 + name=${choice##*$'\t'} +fi +printf '%s\n' "${others[@]}" | grep -qx -- "$name" || omu_die "There is no one else named $name." + +session=$(loginctl list-sessions --json=short | + jq -r --arg user "$name" 'first(.[] | select(.user == $user and .seat == "seat0" and .class == "user") | .session) // empty') + +if [[ -z $session ]] && ! omu_first_console_free; then + omarchy-notification-send -u critical -g 󰍃 "Log out to let $name sign in" \ + "This desktop holds the console the login screen needs. Click to log out." \ + --exec omarchy-system logout + exit 0 +fi + +# Locked before anything switches, so this desktop is never left open behind the +# other one. +omarchy-system-lock +locked=false +for _ in {1..50}; do + if omarchy-hyprland-session-locked; then + locked=true + break + fi + sleep 0.1 +done +$locked || omu_die "Could not lock this desktop, so nothing was switched." + +# Omarchy's own lock screen, if it is the one running, knows neither request: this +# desktop then keeps the reader until it blanks, and asks for the password on return. +if [[ -n $session ]]; then + omarchy-shell lock releaseReader >/dev/null 2>&1 || true + loginctl activate "$session" +elif [[ $(omarchy-shell lock switchUser 2>/dev/null) != ok ]]; then + omarchy-mu-lock-action switchUser +fi diff --git a/etc/mkinitcpio.conf.d/zz-omarchy-mu-luks-slot.conf b/etc/mkinitcpio.conf.d/zz-omarchy-mu-luks-slot.conf new file mode 100644 index 0000000..8c4814a --- /dev/null +++ b/etc/mkinitcpio.conf.d/zz-omarchy-mu-luks-slot.conf @@ -0,0 +1,14 @@ +# Once accounts have their own key slots, the unlock records which one opened the +# disk (omarchy-mu-luks-slot, after encrypt), so omarchy-mu-login-select can open +# that person's desktop. Its own file, sorting after the others: an older hooks +# drop-in, or one edited by hand, sets HOOKS whole and would drop it. A systemd +# initramfs (sd-encrypt) has no encrypt hook and shows the login screen. +if [[ -f ${OMU_SLOT_MAP_FILE:-/etc/omarchy-multiuser/slots} && " ${HOOKS[*]} " == *" encrypt "* && " ${HOOKS[*]} " != *" omarchy-mu-luks-slot "* ]]; then + _omu_hooks=() + for _omu_hook in "${HOOKS[@]}"; do + _omu_hooks+=("$_omu_hook") + [[ $_omu_hook == "encrypt" ]] && _omu_hooks+=(omarchy-mu-luks-slot) + done + HOOKS=("${_omu_hooks[@]}") + unset _omu_hooks _omu_hook +fi diff --git a/etc/sddm.conf.d/zz-omarchy-multiuser.conf b/etc/sddm.conf.d/zz-omarchy-multiuser.conf index c75ffc4..0ef90c7 100644 --- a/etc/sddm.conf.d/zz-omarchy-multiuser.conf +++ b/etc/sddm.conf.d/zz-omarchy-multiuser.conf @@ -1,14 +1,15 @@ -# omarchy-multiuser: the greeter lists every user (full names) with an -# optional field for any other username, and nobody is logged in -# automatically. SDDM reads /etc/sddm.conf.d in name order and the last value -# wins, so this sorts after Omarchy's 10-theme.conf, 99-omarchy-login.conf and -# autologin.conf ('z' > 'a' > '9'). +# omarchy-multiuser: the password-only login screen, and nobody logged in +# automatically unless omarchy-mu-login-select says so. SDDM reads /etc/sddm.conf.d +# in name order and the last value wins, so this sorts after Omarchy's 10-theme.conf, +# 99-omarchy-login.conf and autologin.conf, and before the zzz- drop-in that +# omarchy-mu-login-select writes for one boot. [Theme] Current=omarchy-multiuser [Users] RememberLastUser=true RememberLastSession=true +ReuseSession=true MinimumUid=1000 HideShells=/usr/bin/nologin,/sbin/nologin,/usr/bin/false,/bin/false diff --git a/etc/sudoers.d/omarchy-multiuser b/etc/sudoers.d/omarchy-multiuser index e57c68b..10bd208 100644 --- a/etc/sudoers.d/omarchy-multiuser +++ b/etc/sudoers.d/omarchy-multiuser @@ -4,6 +4,10 @@ # SUDO_USER and nothing else); asks for the user's own password. Only the # bare actions: --user is for administrators. %omarchy-users ALL=(root) /usr/bin/omarchy-mu-fido2-authfile add, /usr/bin/omarchy-mu-fido2-authfile remove +# Their own password: the login and the disk key together. The helper takes the +# user from SUDO_USER, asks for the current password on stdin, and allows three +# tries an hour. +%omarchy-users ALL=(root) NOPASSWD: /usr/bin/omarchy-mu-user-helper password-self # Recompute the lock screen's fingerprint PAM after enrolling or deleting # prints. Idempotent; its only options are --check and --quiet. %omarchy-users ALL=(root) NOPASSWD: /usr/bin/omarchy-mu-apply-lock "", /usr/bin/omarchy-mu-apply-lock --quiet, /usr/bin/omarchy-mu-apply-lock --check diff --git a/initcpio/cryptsetup b/initcpio/cryptsetup new file mode 100644 index 0000000..137ed04 --- /dev/null +++ b/initcpio/cryptsetup @@ -0,0 +1,54 @@ +#!/usr/bin/ash +# From Omarchy PR #16920, which ran it on real installs through Plymouth and the console. +# Stands in for cryptsetup in the initramfs to note which key slot unlocked the +# disk, so omarchy-mu-login-select can open that person's desktop. Every call but +# an unlock goes straight through. An unlock, whether Plymouth hands the +# password over or cryptsetup prompts on the console itself, runs the real +# cryptsetup once, verbose, with its prompt and errors on screen as before, +# keeps its exit status, and only after it succeeded writes +# " " to /run, which switch_root carries into the system. +# Nothing here may turn an unlock that worked into one that failed. + +real=${CRYPTSETUP_REAL:-/usr/bin/cryptsetup.real} +record=${LUKS_SLOT_RECORD:-/run/omarchy-multiuser/luks-slot} + +case " $* " in + *" open "*) ;; + *) exec "$real" "$@" ;; +esac + +out=${record%/*}/luks-open.out +mkdir -p "${record%/*}" 2>/dev/null +# Somewhere to keep the output first, or the unlock goes straight through; +# `true`, since a redirect failing on `:` would end this shell instead. +true >"$out" 2>/dev/null || exec "$real" "$@" +# Only stdout is kept aside, where verbose names the slot; the prompt and any +# error stay on stderr, on screen. +"$real" --verbose "$@" >"$out" +status=$? +grep -v -e '^Key slot [0-9]* unlocked' -e '^Command successful' -e '^No usable token' "$out" 2>/dev/null +[ "$status" -eq 0 ] || { rm -f "$out"; exit "$status"; } + +slot=$(sed -n 's/^Key slot \([0-9][0-9]*\) unlocked.*/\1/p' "$out" 2>/dev/null | head -n 1) +rm -f "$out" + +# The device is the first argument after "open" that is neither an option nor +# the value of --type. +device="" +seen_open=0 +skip=0 +for arg in "$@"; do + if [ "$skip" -eq 1 ]; then skip=0; continue; fi + case $arg in + open) seen_open=1 ;; + --type) skip=1 ;; + -*) ;; + *) if [ "$seen_open" -eq 1 ]; then device=$arg; break; fi ;; + esac +done + +if [ -n "$slot" ] && [ -n "$device" ]; then + uuid=$("$real" luksUUID "$device" 2>/dev/null) + [ -n "$uuid" ] && echo "$uuid $slot" >"$record" 2>/dev/null +fi +exit 0 diff --git a/initcpio/install/omarchy-mu-luks-slot b/initcpio/install/omarchy-mu-luks-slot new file mode 100644 index 0000000..181cf3d --- /dev/null +++ b/initcpio/install/omarchy-mu-luks-slot @@ -0,0 +1,23 @@ +#!/bin/bash + +# Puts /usr/share/omarchy-multiuser/initcpio/cryptsetup in front of the real +# cryptsetup, so the unlock records which key slot opened the disk. Ordered after +# encrypt, which adds the real one first. A wrapper that would not parse is left +# out, so the unlock never depends on it. + +build() { + local wrapper=/usr/share/omarchy-multiuser/initcpio/cryptsetup + if ! /usr/lib/initcpio/busybox ash -n "$wrapper"; then + warning "omarchy-mu-luks-slot: '%s' does not parse; leaving cryptsetup as it is" "$wrapper" + return 0 + fi + add_binary /usr/bin/cryptsetup /usr/bin/cryptsetup.real + add_file "$wrapper" /usr/bin/cryptsetup 755 +} + +help() { + cat < — end their sessions, then whatever outlives them. -# Fails when something is still running. +# Whether loginctl lists a session matching the jq filter on the first console. +_omu_first_console_has() { + local sessions + sessions=$(loginctl list-sessions --json=short 2>/dev/null) || return 1 + jq -e --arg user "${2:-}" "any(.[]; .tty == \"tty1\" and ($1))" <<<"$sessions" >/dev/null 2>&1 +} + +# SDDM takes the end of a desktop it logged in automatically, when it is forced, +# for a crash and shows nothing more on the first console until it is asked. +# Asking also switches to that console, and that stays: a greeter whose console is +# taken back before its compositor has set up the screen stays dark for good, and +# how long that takes depends on the graphics card. +_omu_login_screen_back() { + local active="" _ + [[ ! -r $OMU_ROOT/sys/class/tty/tty0/active ]] || active=$(<"$OMU_ROOT/sys/class/tty/tty0/active") + for _ in {1..10}; do + _omu_first_console_has '.class != "greeter"' || break + sleep 0.5 + done + sudo busctl call org.freedesktop.DisplayManager /org/freedesktop/DisplayManager/Seat0 \ + org.freedesktop.DisplayManager.Seat SwitchToGreeter >/dev/null 2>&1 || return 1 + [[ $active != tty[0-9]* || $active == tty1 ]] || + echo "The login screen takes over the screen. To come back here: Ctrl+Alt+F${active#tty}." + for _ in {1..20}; do + _omu_first_console_has '.class == "greeter"' && return 0 + sleep 0.5 + done + return 1 +} + +# omu_sign_out — end their sessions, then whatever outlives them, and bring +# back the login screen if their desktop was on the first console. Fails when +# something is still running. omu_sign_out() { + local on_first_console=false status=0 + # shellcheck disable=SC2016 # $user is jq's + _omu_first_console_has '.user == $user' "$1" && on_first_console=true sudo loginctl terminate-user "$1" 2>/dev/null || true if ! _omu_programs_end "$1"; then sudo pkill -KILL -u "$1" || true - _omu_programs_end "$1" + _omu_programs_end "$1" || status=$? + fi + if $on_first_console && ! _omu_login_screen_back; then + echo "Warning: the login screen didn't come back on the first console. Reboot, or run: sudo systemctl restart sddm (it ends every open desktop)." >&2 fi + return "$status" +} + +# SDDM 0.21 starts a new greeter on the first console. An automatic login's +# desktop holds that console, so the greeter fails there and leaves the desktop +# dark with no way back. A normal login's desktop has a console of its own, and +# an earlier greeter on the first one can be gone back to. Not knowing counts as +# held: the cost of a wrong yes is a dark screen, of a wrong no a missing entry. +omu_first_console_free() { + local sessions + sessions=$(loginctl list-sessions --json=short 2>/dev/null) || return 1 + jq -e 'all(.[]; .tty != "tty1" or .class == "greeter")' <<<"$sessions" >/dev/null 2>&1 +} + +# omu_fixed_autologin — /etc/sddm.conf, which outranks every drop-in, names +# someone to log in automatically: the login screen would never show. +omu_fixed_autologin() { + [[ -f $OMU_ROOT/etc/sddm.conf ]] || return 1 + awk '/^\[/ { section = $0 } + section == "[Autologin]" && /^[ \t]*User[ \t]*=[ \t]*[^ \t]/ { found = 1 } + END { exit !found }' "$OMU_ROOT/etc/sddm.conf" +} + +# omu_ask_new_password
— prints the password, asked twice until both match. +omu_ask_new_password() { + local first second + while :; do + first=$(gum input --password --header "$1") || return 1 + second=$(gum input --password --header "$1, again") || return 1 + [[ $first != "$second" ]] || break + echo "The passwords don't match." >&2 + done + printf '%s' "$first" } # omu_atomic_write — stdin to a sibling temp file, then rename, diff --git a/lib/omarchy-multiuser/slots.sh b/lib/omarchy-multiuser/slots.sh new file mode 100644 index 0000000..0f39788 --- /dev/null +++ b/lib/omarchy-multiuser/slots.sh @@ -0,0 +1,549 @@ +# shellcheck shell=bash +# Every account's password is also its own LUKS key slot on the system disk, +# recorded in the slot map so boot can tell who unlocked it. From Omarchy PR +# #16920 (bin/omarchy-user-functions). Sourced after common.sh, as root. +# +# Passwords live in variables and reach other programs on stdin or through +# process substitution, never argv; never trace them. + +OMU_SLOT_DIR=${OMU_SLOT_DIR:-$OMU_ROOT/etc/omarchy-multiuser} +OMU_SLOT_MAP=$OMU_SLOT_DIR/slots +# What omarchy-mu-luks-enroll recorded before each slot had to be the login password. +OMU_SLOT_LEGACY=$OMU_SLOT_DIR/luks-slots +OMU_SLOT_JOURNAL=${OMU_SLOT_JOURNAL:-$OMU_STATE_DIR/password-journal} +OMU_SLOT_RECORD=${OMU_SLOT_RECORD:-$OMU_ROOT/run/omarchy-multiuser/luks-slot} +OMU_RATE_DIR=${OMU_RATE_DIR:-$OMU_ROOT/run/omarchy-multiuser/rate} +OMU_LIFECYCLE_DISPATCH=${OMU_LIFECYCLE_DISPATCH:-/usr/bin/omarchy-lifecycle-dispatch} +OMU_REFUSAL_DELAY=${OMU_REFUSAL_DELAY:-3} +OMU_MIN_PASSWORD=6 + +omu_say() { + printf '%s\n' "$*" >&2 +} + +# --- Passwords --------------------------------------------------------------- + +omu_shadow_hash() { + awk -F: -v user="$1" '$1 == user { print $2; exit }' "$OMU_SHADOW" +} + +# The hash travels in the environment, which only root can read for a root +# process, and the password on stdin. +omu_password_matches_hash() { + local password=$1 hash=$2 + [[ $hash == \$* ]] || return 1 + printf '%s' "$password" | OMU_HASH=$hash perl -e 'local $/; my $p = ; my $h = $ENV{OMU_HASH}; exit(crypt($p, $h) eq $h ? 0 : 1)' +} + +omu_password_matches() { + omu_password_matches_hash "$1" "$(omu_shadow_hash "$2")" +} + +# The account whose password this is. Accounts share no password, so there is +# at most one. +omu_password_owner() { + local password=$1 user + while read -r user; do + if omu_password_matches "$password" "$user"; then + echo "$user" + return 0 + fi + done < <(omu_human_users) + return 1 +} + +# A locked account always has failed logins. Counts as yes when faillock can't say. +omu_has_failed_logins() { + local tally + tally=$(faillock --user "$1" 2>/dev/null) || return 0 + [[ -n $(awk 'NR > 2 && NF' <<<"$tally") ]] +} + +# Changes whenever the account's shadow password does, without holding it. +omu_fingerprint() { + omu_shadow_hash "$1" | sha256sum | cut -c1-16 +} + +# One chpasswd run commits every line in one write of shadow. +omu_set_passwords() { + local password=$1 user + shift + for user in "$@"; do + printf '%s:%s\n' "$user" "$password" + done | chpasswd +} + +# --- The system disk --------------------------------------------------------- + +# The LUKS partition beneath /, or nothing when / is not encrypted. Fails when +# it can't tell. +omu_root_luks_device() { + local root_source ancestry device + if [[ -n ${OMU_SYSTEM_DRIVE+set} ]]; then + printf '%s' "$OMU_SYSTEM_DRIVE" + return 0 + fi + root_source=$(findmnt -no SOURCE /) && [[ -n $root_source ]] || return 1 + ancestry=$(lsblk -nsrpo NAME,TYPE,FSTYPE "${root_source%%[*}") || return 1 + device=$(awk '$3 == "crypto_LUKS" { print $1; exit }' <<<"$ancestry") + if [[ -n $device ]]; then + readlink -f "$device" + elif awk '$2 == "crypt" { found = 1 } END { exit !found }' <<<"$ancestry"; then + return 1 + fi +} + +# Sets OMU_DRIVE (empty when / is not encrypted) and OMU_UUID. +omu_load_drive() { + OMU_DRIVE=$(omu_root_luks_device) || { + omu_say "Could not tell whether the system disk is encrypted." + return 1 + } + OMU_UUID=- + if [[ -n $OMU_DRIVE ]]; then + OMU_UUID=$(cryptsetup luksUUID "$OMU_DRIVE") && [[ -n $OMU_UUID ]] || { + omu_say "Could not read the system disk's UUID." + return 1 + } + fi +} + +omu_encrypted() { + [[ -n ${OMU_DRIVE:-} ]] +} + +# Platforms whose boot checks want every kept key slot recorded (Apple Silicon) +# can't take a slot for another person until their boot package records one. +omu_slot_recorder_present() { + local out status=0 + out=$("$OMU_LIFECYCLE_DISPATCH" --resolve luks-slots 2>/dev/null) || status=$? + (( status == 0 )) && [[ -n $out ]] +} + +# The slot the password opens. Returns 2 when it opens none. Tokens are tried +# before the key and report their own slot, so allow only a token type no token +# has. +omu_slot_of() { + local out status=0 + out=$(printf '%s' "$1" | LC_ALL=C cryptsetup open --test-passphrase --verbose --token-type passphrase-only --key-file - "$OMU_DRIVE" 2>&1) || status=$? + (( status == 0 )) || return "$status" + grep -o 'Key slot [0-9]* unlocked' <<<"$out" | grep -o '[0-9]*' | head -1 +} + +# Whether the password opens that one slot. Returns 2 when it doesn't. +omu_slot_opens() { + printf '%s' "$1" | cryptsetup open --test-passphrase --token-type passphrase-only --key-slot "$2" --key-file - "$OMU_DRIVE" >/dev/null 2>&1 +} + +omu_drive_slots() { + local dump + dump=$(cryptsetup luksDump "$OMU_DRIVE") || return 1 + awk ' + /^[^ \t]/ { keyslots = ($0 == "Keyslots:") } + keyslots && /^ +[0-9]+: luks2/ { sub(":", "", $1); print $1 } + /^Key Slot [0-9]+: ENABLED/ { sub(":", "", $3); print $3 }' <<<"$dump" | paste -sd, - +} + +# 0 when the slot holds a key, 1 when it doesn't, 2 when the disk can't be read. +omu_slot_enabled() { + local slots + slots=$(omu_drive_slots) || return 2 + [[ ,$slots, == *",$1,"* ]] +} + +omu_free_slot() { + local slots slot last=31 + slots=$(omu_drive_slots) || return 1 + cryptsetup isLuks --type luks2 "$OMU_DRIVE" || last=7 + for (( slot = 0; slot <= last; slot++ )); do + if [[ ,$slots, != *",$slot,"* ]]; then + echo "$slot" + return 0 + fi + done + return 1 +} + +# Puts NEW in SLOT, chosen and journaled beforehand so an interrupted run knows +# which slot to take back, authorised by CURRENT, and succeeds once NEW opens it. +omu_add_slot() { + local slot=$1 current=$2 new=$3 opened + local -a pbkdf + # shellcheck disable=SC2206 # the tests' cheap key derivation, as words + pbkdf=(${OMU_LUKS_PBKDF:---iter-time 2000}) + if [[ -z ${OMU_LUKS_PBKDF:-} ]] && cryptsetup isLuks --type luks2 "$OMU_DRIVE"; then + pbkdf+=(--pbkdf argon2id) + fi + # shellcheck disable=SC2016 # the inner shell's + printf '%s\n%s' "$current" "$new" | + bash -c 'IFS= read -r current; drive=$1; shift; exec cryptsetup luksAddKey -q "$@" --key-file <(printf "%s" "$current") "$drive" <(cat)' bash "$OMU_DRIVE" --key-slot "$slot" "${pbkdf[@]}" || return 1 + opened=$(omu_slot_of "$new") || return 1 + [[ $opened == "$slot" ]] +} + +# Batch mode needs no remaining key, so an interrupted change can be finished by +# a run that never saw the passwords, and removing an account needs nobody's disk +# password. A disk that can't be read is a failure, never a slot already gone. +omu_kill_slot() { + local status=0 out + omu_slot_enabled "$1" || status=$? + if (( status == 1 )); then + return 0 + elif (( status != 0 )); then + return 1 + fi + # With stdin not a terminal it reads a passphrase from there, batch mode or not, + # and would wait for good on a pipe nobody closes. An empty one goes through, with + # a remark about it that means nothing here. + out=$(cryptsetup luksKillSlot -q "$OMU_DRIVE" "$1" &1) || { + omu_say "$out" + return 1 + } +} + +# --- Durable files ------------------------------------------------------------- + +# Written whole, synced, then renamed and the directory synced, so a power cut +# leaves the old file or the new one, never a LUKS change without the record that +# explains it. +omu_durable_write() { + local target=$1 tmp + mkdir -p "${target%/*}" || return 1 + tmp=$(mktemp "${target%/*}/.${target##*/}.XXXXXX") || return 1 + if cat >"$tmp" && chmod 600 "$tmp" && sync "$tmp" && mv -f "$tmp" "$target"; then + sync "${target%/*}" + else + rm -f "$tmp" + return 1 + fi +} + +# --- The slot map -------------------------------------------------------------- + +# One line per account: . + +omu_map_lines() { + [[ -f $OMU_SLOT_MAP ]] && cat "$OMU_SLOT_MAP" + true +} + +omu_map_field() { + omu_map_lines | awk -v user="$1" -v field="$2" '$4 == user { print $field; exit }' +} + +omu_map_slot() { + omu_map_field "$1" 2 +} + +omu_map_user_for_slot() { + omu_map_lines | awk -v uuid="$1" -v slot="$2" '$1 == uuid && $2 == slot { print $4; exit }' +} + +omu_map_set() { + local user=$1 slot=$2 uid + uid=$(getent passwd "$user" | cut -d: -f3) + [[ -n $uid ]] || return 1 + { omu_map_lines | awk -v user="$user" '$4 != user' + printf '%s %s %s %s %s\n' "$OMU_UUID" "$slot" "$uid" "$user" "$(omu_fingerprint "$user")" + } | omu_durable_write "$OMU_SLOT_MAP" +} + +omu_map_remove() { + [[ -n $(omu_map_slot "$1") ]] || return 0 + omu_map_lines | awk -v user="$1" '$4 != user' | omu_durable_write "$OMU_SLOT_MAP" +} + +omu_legacy_slot() { + [[ -f $OMU_SLOT_LEGACY ]] || return 0 + awk -v user="$1" '$1 == user { slot = $2 } END { if (slot != "") print slot }' "$OMU_SLOT_LEGACY" +} + +omu_legacy_owner() { + [[ -f $OMU_SLOT_LEGACY ]] || return 0 + awk -v slot="$1" '$2 == slot { print $1; exit }' "$OMU_SLOT_LEGACY" +} + +omu_legacy_remove() { + [[ -n $(omu_legacy_slot "$1") ]] || return 0 + awk -v user="$1" '$1 != user' "$OMU_SLOT_LEGACY" | omu_durable_write "$OMU_SLOT_LEGACY" +} + +# The map is trusted only whole: every line for this disk, no slot or account +# twice, every account still there under its uid. +omu_map_valid() { + local uuid slot uid user fp + local -A slots=() names=() + while read -r uuid slot uid user fp; do + [[ $uuid == "$OMU_UUID" && $slot =~ ^[0-9]+$ && -n $fp ]] || return 1 + [[ -z ${slots[$slot]:-} && -z ${names[$user]:-} ]] || return 1 + [[ $(getent passwd "$user" | cut -d: -f3) == "$uid" ]] || return 1 + slots[$slot]=1 + names[$user]=1 + done < <(omu_map_lines) +} + +# A password changed with plain passwd no longer selects the account at boot: +# drift costs the convenience, never the boundary. +omu_in_sync() { + [[ -n $(omu_map_slot "$1") && $(omu_map_field "$1" 5) == "$(omu_fingerprint "$1")" ]] +} + +# --- The journal --------------------------------------------------------------- + +# The account, the disk, slot numbers, a fingerprint of the account's password +# before the change, and the phase; never key material. + +omu_journal_get() { + [[ -f $OMU_SLOT_JOURNAL ]] || return 1 + awk -F= -v key="$1" '$1 == key { print substr($0, length(key) + 2); exit }' "$OMU_SLOT_JOURNAL" +} + +omu_journal_put() { + local key value + local -A updates=() + while (( $# )); do + updates[$1]=$2 + shift 2 + done + { if [[ -f $OMU_SLOT_JOURNAL ]]; then + while IFS='=' read -r key value; do + [[ -n ${updates[$key]+set} ]] || printf '%s=%s\n' "$key" "$value" + done <"$OMU_SLOT_JOURNAL" + fi + for key in "${!updates[@]}"; do + printf '%s=%s\n' "$key" "${updates[$key]}" + done + } | omu_durable_write "$OMU_SLOT_JOURNAL" +} + +omu_journal_clear() { + # shellcheck disable=SC2015 # a failed sync doesn't matter once the file is gone + rm -f "$OMU_SLOT_JOURNAL" && sync "${OMU_SLOT_JOURNAL%/*}" 2>/dev/null || [[ ! -e $OMU_SLOT_JOURNAL ]] +} + +omu_journal_pending() { + [[ -f $OMU_SLOT_JOURNAL ]] +} + +# --- Rules --------------------------------------------------------------------- + +# Saying a password is taken says it is somebody's. The disk prompt says as much +# at every boot, so the delay only keeps this from being any cheaper. +omu_refuse_taken() { + sleep "$OMU_REFUSAL_DELAY" + omu_say "That password already unlocks this computer. Choose a different one." +} + +# Every password is a disk key and picks its account, so it must be long enough +# and nobody else's: no other account's login password, and no key slot at all +# on the disk. An old password left in a slot no longer matches any hash but +# still opens it. +omu_check_new_password() { + local password=$1 except_user=$2 user status=0 + if [[ $password == *$'\n'* ]]; then + omu_say "A password can't contain a line break." + return 1 + elif (( ${#password} < OMU_MIN_PASSWORD )); then + omu_say "The password must be at least $OMU_MIN_PASSWORD characters." + return 1 + fi + while read -r user; do + [[ $user != "$except_user" ]] || continue + if omu_password_matches "$password" "$user"; then + omu_refuse_taken + return 1 + fi + done < <(omu_human_users) + if omu_encrypted; then + omu_slot_of "$password" >/dev/null || status=$? + if (( status == 0 )); then + omu_refuse_taken + return 1 + elif (( status != 2 )); then + omu_say "Could not check the password against the system disk." + return 1 + fi + fi +} + +# The caller's own password, proving they are who sudo says, and the key that +# lets a new slot be added. Once the map knows them, the password that opens +# their own slot proves it, which is also how someone whose login password was +# changed with plain passwd gets back in step. The first time, it must be their +# login password and open a slot nobody else holds, which then becomes theirs. +omu_authenticate() { + local caller=$1 password=$2 mapped slot status=0 holder + if ! omu_encrypted; then + omu_password_matches "$password" "$caller" && return 0 + sleep "$OMU_REFUSAL_DELAY" + omu_say "That isn't $caller's password." + return 1 + fi + + mapped=$(omu_map_slot "$caller") + if [[ -n $mapped ]]; then + omu_slot_opens "$password" "$mapped" || status=$? + if (( status == 0 )); then + return 0 + elif (( status == 2 )); then + sleep "$OMU_REFUSAL_DELAY" + omu_say "That isn't the password that unlocks this computer for $caller." + else + omu_say "Could not check the password against the system disk." + fi + return 1 + fi + + if ! omu_password_matches "$password" "$caller"; then + sleep "$OMU_REFUSAL_DELAY" + omu_say "That isn't $caller's password." + return 1 + fi + slot=$(omu_slot_of "$password") || status=$? + if (( status == 2 )); then + omu_say "$caller's password doesn't open the system disk. Make them the same first, with omarchy-drive-password." + return 1 + elif (( status != 0 )); then + omu_say "Could not check the password against the system disk." + return 1 + fi + holder=$(omu_map_user_for_slot "$OMU_UUID" "$slot") + [[ -n $holder ]] || holder=$(omu_legacy_owner "$slot") + if [[ -n $holder && $holder != "$caller" ]]; then + omu_say "$caller's password opens $holder's key slot." + return 1 + fi + omu_map_set "$caller" "$slot" && omu_legacy_remove "$caller" +} + +# --- Operations ---------------------------------------------------------------- + +# Journals its phase before every step that changes something, keeping old access +# until its replacement is proven, so omu_slots_finish can roll an interrupted one +# back (before the account took the new password) or forward (after). Whether the +# account took it is read from shadow itself, by its fingerprint, not the phase. +omu_slots_change_password() { + local caller=$1 name=$2 password=$3 caller_password=$4 slot=- old_slot=- + local -a accounts=("$name") people + omu_authenticate "$caller" "$caller_password" || return 1 + if omu_password_matches "$password" "$name"; then + omu_say "That's already $name's password." + return 1 + fi + omu_check_new_password "$password" "$name" || return 1 + mapfile -t people < <(omu_human_users) + if omu_encrypted; then + if (( ${#people[@]} > 1 )) && omu_slot_recorder_present; then + omu_say "This machine's boot checks can't take a second person's disk password yet." + return 1 + fi + old_slot=$(omu_map_slot "$name") + [[ -n $old_slot ]] || old_slot=$(omu_legacy_slot "$name") + old_slot=${old_slot:--} + slot=$(omu_free_slot) || { omu_say "The system disk has no free key slot."; return 1; } + fi + # With one account root keeps its password, as the installer set it up. + if (( ${#people[@]} == 1 )) && [[ $(omu_shadow_hash root) == \$* ]]; then + accounts+=(root) + fi + + omu_journal_put user "$name" uuid "$OMU_UUID" slot "$slot" old_slot "$old_slot" old_fp "$(omu_fingerprint "$name")" phase key || return 1 + if [[ $slot != "-" ]] && ! omu_add_slot "$slot" "$caller_password" "$password"; then + omu_say "Could not add the new password to the system disk." + omu_slots_finish + return 1 + fi + omu_set_passwords "$password" "${accounts[@]}" || { omu_slots_finish; return 1; } + omu_journal_put phase shadow || return 1 + omu_slots_finish || return 1 + omu_boot_records_slot +} + +# Takes the account's key off the disk and out of the records. Key first: a stop +# in between is finished by running this again, which still knows whose slot it is. +omu_slots_forget() { + local user=$1 slot enabled status=0 + slot=$(omu_map_slot "$user") + [[ -n $slot ]] || slot=$(omu_legacy_slot "$user") + if [[ -z $slot ]] || ! omu_encrypted; then + omu_map_remove "$user" && omu_legacy_remove "$user" + return + fi + omu_slot_enabled "$slot" || status=$? + if (( status == 0 )); then + enabled=$(omu_drive_slots) || return 1 + if [[ $enabled == "$slot" ]]; then + omu_say "Key slot $slot is the disk's last one; refusing to lock the disk for good." + return 1 + fi + fi + omu_kill_slot "$slot" || return 1 + omu_map_remove "$user" && omu_legacy_remove "$user" +} + +# Finishes whatever the journal says was under way, and succeeds once nothing is. +omu_slots_finish() { + local user slot old_slot phase uuid + omu_journal_pending || return 0 + user=$(omu_journal_get user) + slot=$(omu_journal_get slot) + old_slot=$(omu_journal_get old_slot) + phase=$(omu_journal_get phase) + uuid=$(omu_journal_get uuid) + + if [[ $uuid != "$OMU_UUID" ]]; then + omu_say "The password journal records a change on another disk ($uuid); remove $OMU_SLOT_JOURNAL once you've checked that disk." + return 1 + fi + + case $phase in + key) + if [[ -n $(omu_shadow_hash "$user") && $(omu_fingerprint "$user") != "$(omu_journal_get old_fp)" ]]; then + omu_journal_put phase shadow && omu_slots_finish + return + fi + # The new password may have reached the disk but not the account: back to + # the old one everywhere. + if [[ $slot != "-" ]]; then + omu_kill_slot "$slot" || return 1 + fi + omu_journal_clear + ;; + shadow) + if [[ $slot != "-" ]]; then + omu_map_set "$user" "$slot" || return 1 + if [[ $old_slot != "-" ]]; then + omu_kill_slot "$old_slot" || return 1 + fi + omu_legacy_remove "$user" || return 1 + fi + omu_journal_clear + ;; + *) + omu_say "The password journal records an unknown change ($phase)." + return 1 + ;; + esac +} + +# --- Boot ------------------------------------------------------------------------ + +# The boot image picks up the hook that records which slot unlocked the disk once +# the map exists (zz-omarchy-mu-luks-slot.conf), so it is rebuilt the first time +# there is more than one person. Until it is, every boot shows the login screen, +# which is safe. +omu_boot_records_slot() { + local marker=$OMU_SLOT_DIR/boot-records-slot rebuild=${OMU_REBUILD_BOOT:-limine-mkinitcpio} + local -a people + omu_encrypted && [[ ! -f $marker ]] || return 0 + mapfile -t people < <(omu_human_users) + (( ${#people[@]} > 1 )) || return 0 + command -v "$rebuild" >/dev/null || rebuild="mkinitcpio -P" + omu_say "Updating the boot image so the computer knows whose password unlocked it..." + # shellcheck disable=SC2086 # a command and its option + if $rebuild >/dev/null 2>&1; then + : | omu_durable_write "$marker" + else + omu_say "Could not update the boot image, so the computer shows the login screen after the disk prompt. Run: sudo limine-mkinitcpio" + fi +} diff --git a/libalpm/hooks/90-omarchy-mu-sddm.hook b/libalpm/hooks/90-omarchy-mu-sddm.hook index ca3a982..831a376 100644 --- a/libalpm/hooks/90-omarchy-mu-sddm.hook +++ b/libalpm/hooks/90-omarchy-mu-sddm.hook @@ -8,6 +8,6 @@ Target = sddm Target = omarchy-multiuser [Action] -Description = Keeping the multi-user greeter without autologin... +Description = Keeping the multi-user greeter and its automatic login... When = PostTransaction Exec = /bin/sh -c '/usr/bin/omarchy-mu-sddm-guard; /usr/bin/omarchy-mu-sddm-sync; exit 0' diff --git a/packaging/PKGBUILD b/packaging/PKGBUILD index 6581626..11f2dd0 100644 --- a/packaging/PKGBUILD +++ b/packaging/PKGBUILD @@ -6,14 +6,14 @@ pkgname=omarchy-multiuser pkgver=0.9.0 pkgrel=1 -pkgdesc='Several users on one Omarchy machine: a greeter listing them, per-user FIDO2/fingerprint, migrations for non-admins' +pkgdesc='Several people on one Omarchy machine, picked by their own password: per-user disk keys, FIDO2 and fingerprints, migrations for non-admins' arch=(any) url='https://github.com/lbssousa/omarchy-multiuser' license=(MIT) -depends=(omarchy omarchy-settings sddm qt6-declarative imagemagick sudo jq gum gettext) +depends=(omarchy omarchy-settings sddm qt6-declarative imagemagick sudo jq gum perl) optdepends=('pam-u2f: FIDO2 keys for sudo and polkit' 'fprintd: fingerprints for sudo, polkit and the lock screen' - 'cryptsetup: per-user disk unlock passwords') + 'cryptsetup: each account its own disk key, on encrypted installs') checkdepends=(nodejs fakeroot) backup=(etc/sddm.conf.d/zz-omarchy-multiuser.conf) install=omarchy-multiuser.install @@ -37,7 +37,7 @@ package() { install -Dm644 -t "$pkgdir/usr/share/omarchy-multiuser" share/* local theme=usr/share/sddm/themes/omarchy-multiuser - install -Dm644 -t "$pkgdir/$theme" sddm/omarchy-multiuser/{Main.qml,UserList.js,Strings.js,Password.js,Power.js,theme.conf,metadata.desktop} + install -Dm644 -t "$pkgdir/$theme" sddm/omarchy-multiuser/{Main.qml,Strings.js,Password.js,Power.js,theme.conf,metadata.desktop} install -Dm644 -t "$pkgdir/$theme/fallback" sddm/omarchy-multiuser/fallback/*.png local lock=usr/share/omarchy-multiuser/lock-plugin @@ -45,12 +45,16 @@ package() { install -Dm644 -t "$pkgdir/$lock/i18n" shell/lock/i18n/*.json install -Dm644 -t "$pkgdir/etc/sddm.conf.d" etc/sddm.conf.d/zz-omarchy-multiuser.conf + install -Dm644 -t "$pkgdir/etc/mkinitcpio.conf.d" etc/mkinitcpio.conf.d/zz-omarchy-mu-luks-slot.conf + install -Dm644 -t "$pkgdir/usr/lib/initcpio/install" initcpio/install/omarchy-mu-luks-slot + install -Dm755 -t "$pkgdir/usr/share/omarchy-multiuser/initcpio" initcpio/cryptsetup install -Dm440 -t "$pkgdir/etc/sudoers.d" etc/sudoers.d/omarchy-multiuser install -Dm644 -t "$pkgdir/usr/share/polkit-1/rules.d" polkit/10-omarchy-multiuser.rules install -Dm644 -t "$pkgdir/usr/share/polkit-1/actions" polkit/*.policy install -Dm644 -t "$pkgdir/usr/lib/sysusers.d" sysusers.d/omarchy-multiuser.conf install -Dm644 -t "$pkgdir/usr/lib/tmpfiles.d" tmpfiles.d/omarchy-multiuser.conf install -Dm644 -t "$pkgdir/usr/lib/systemd/system" systemd/system/* + install -Dm644 -t "$pkgdir/usr/lib/systemd/system/sddm.service.d" systemd/sddm.service.d/*.conf install -Dm644 -t "$pkgdir/usr/lib/systemd/user" systemd/user/*.service install -Dm644 -t "$pkgdir/usr/lib/systemd/user/omarchy-migrate-notify.service.d" \ systemd/user/omarchy-migrate-notify.service.d/*.conf diff --git a/packaging/omarchy-multiuser.install b/packaging/omarchy-multiuser.install index 43cae9a..aeb0d14 100644 --- a/packaging/omarchy-multiuser.install +++ b/packaging/omarchy-multiuser.install @@ -8,13 +8,25 @@ _enable_update_units() { post_install() { systemd-sysusers omarchy-multiuser.conf systemd-tmpfiles --create omarchy-multiuser.conf + /usr/bin/omarchy-mu-sddm-guard || true /usr/bin/omarchy-mu-sddm-sync || true _enable_update_units echo ":: Enable the watchers and the per-login unit (omarchy-setup does this):" echo " systemctl enable --now omarchy-mu-sddm-guard.path omarchy-mu-sddm-sync.path omarchy-mu-apply-lock.path" echo " systemctl --global enable omarchy-mu-login.service" - echo ":: Add users to the omarchy-users group; the greeter changes at the next login screen." + echo ":: Add users to the omarchy-users group; the login screen changes the next time it shows." + _warn_passwords echo ":: With several accounts, lock root's password: omarchy-mu-accounts root-sync" + echo ":: Switch user appears after logging out once: an automatic login's desktop can't leave for the login screen." +} + +# The login screen finds the account by its password alone, so a person needs one, +# nobody else's. Accounts waiting to choose theirs at the login screen can't any more. +_warn_passwords() { + local waiting + waiting=$(awk -F: '$2 == "" { print $1 }' /etc/shadow | paste -sd' ' -) + [[ -z $waiting ]] || echo ":: These accounts have no password and can't log in: $waiting. Run: omarchy-mu-user-password " + echo ":: Each person's password has to be their own, and also opens the disk. Run omarchy-mu-user-password for each of them." } post_upgrade() { @@ -23,6 +35,10 @@ post_upgrade() { if (( $(vercmp "$2" 0.7.0) < 0 )); then _enable_update_units fi + if (( $(vercmp "$2" 0.10.0) < 0 )); then + /usr/bin/omarchy-mu-sddm-guard || true + _warn_passwords + fi } # Each user's shell runs the lock screen from this package; with it gone and @@ -38,14 +54,31 @@ _restore_lock_screens() { done < <(getent passwd) } +# systemd keeps these links after their unit file is gone, each one dangling. +_disable_migration_watchers() { + local wants=${1:-/etc/systemd/system/multi-user.target.wants} link + for link in "$wants"/omarchy-mu-migrate-record@*.path; do + [[ -L $link ]] || continue + systemctl disable --now "${link##*/}" >/dev/null 2>&1 || rm -f -- "$link" + done +} + pre_remove() { + # First: the guard watches /etc/sddm.conf.d, so cleaning up below would run it, + # and it would put back the PAM line that is about to go. + systemctl disable --now omarchy-mu-sddm-guard.path omarchy-mu-sddm-sync.path omarchy-mu-apply-lock.path >/dev/null 2>&1 || true + systemctl stop omarchy-mu-sddm-guard.service >/dev/null 2>&1 || true _restore_lock_screens systemctl disable --now omarchy-mu-update-log.path >/dev/null 2>&1 || true + _disable_migration_watchers rm -f /usr/share/sddm/themes/omarchy-multiuser/theme.conf.user systemctl --global disable omarchy-mu-login.service >/dev/null 2>&1 || true + rm -f /etc/sddm.conf.d/zzz-omarchy-mu-autologin.conf + [[ ! -f /etc/pam.d/sddm ]] || sed -i '/\/usr\/bin\/omarchy-mu-login-match/d' /etc/pam.d/sddm } post_remove() { echo ":: SDDM goes back to Omarchy's greeter at the next login screen." + echo ":: Each person's disk key stays on the disk; /etc/omarchy-multiuser/slots says whose is whose." echo ":: Autologin stays off; Omarchy's tools turn it back on if you want it." } diff --git a/sddm/omarchy-multiuser/Main.qml b/sddm/omarchy-multiuser/Main.qml index f8bf55a..0c64585 100644 --- a/sddm/omarchy-multiuser/Main.qml +++ b/sddm/omarchy-multiuser/Main.qml @@ -1,19 +1,16 @@ pragma ComponentBehavior: Bound import QtQuick 2.15 +import QtQuick.Window 2.15 import SddmComponents 2.0 -import "UserList.js" as UserList import "Strings.js" as Strings import "Password.js" as Password import "Power.js" as Power -// Omarchy's greeter (upstream/sddm/omarchy/Main.qml) with a user list: every -// account SDDM lists, by full name, plus an optional "Other user…" row that -// reveals a username field. The password row is the stock one, asked twice -// for an account that chooses its password at this login (Password.js). What -// that account also needs hangs below the password row, so the logo and the -// boxes stay put between users. The power actions SDDM offers sit at the -// bottom, by click or F key (Power.js). +// Omarchy's greeter (upstream/sddm/omarchy/Main.qml) as Omarchy PR #16920 made it: +// a password alone, as at the disk prompt, tried for the last account and then each +// other one until one logs in (Password.js, omarchy-mu-login-match). The power +// actions SDDM offers sit at the bottom, by click or F key (Power.js). Rectangle { id: root width: 640 @@ -25,35 +22,22 @@ Rectangle { var dir = config.assetDir || "/usr/share/sddm/themes/omarchy/" return dir.charAt(dir.length - 1) === "/" ? dir : dir + "/" } - readonly property bool allowOther: String(config.allowOtherUser || "true") !== "false" - readonly property bool showUsername: String(config.showUsername || "true") !== "false" - readonly property int maxVisibleUsers: Math.max(1, parseInt(config.maxVisibleUsers || "6") || 6) readonly property string localeName: Qt.locale().name readonly property string fontFamily: "JetBrainsMono Nerd Font" // Filled from userModel by the Repeater below. property var userSlots: ({}) - property var users: [] - readonly property var entries: UserList.buildEntries(users, allowOther, showUsername) - property int selectedIndex: 0 - // Set once someone moves the selection, so late model rows don't reset it. - property bool selectionTouched: false - readonly property var selected: entries.length > 0 ? entries[Math.min(selectedIndex, entries.length - 1)] : null - readonly property bool otherSelected: selected !== null && selected.other === true - + property var userNames: [] property bool loginFailed: false - // Accounts with an empty, expired password, from omarchy-mu-sddm-sync, - // plus any PAM reports as one; for them the password box takes the new - // password and a second box confirms it. - property var changeUsers: Password.parseUsers(config.passwordChangeUsers) - readonly property string loginName: UserList.loginUser(selected, otherUser.text) - readonly property bool changeMode: Password.needsChange(changeUsers, loginName) - // PAM's "change your password" notice comes with a login failure from - // SDDM while the change goes on: that one failure is skipped. - property bool changeNoticeSeen: false - property string lastPamMessage: "" - // Shown under the boxes: what is wrong with the new password. - property string message: "" + property var attemptUsers: [] + property int attempt: 0 + property string pending: "" + property bool awaiting: false + property int resends: 0 + // SDDM sends LoginFailed twice for one failure. The second is consumed as such + // even if it arrives after the next account was sent, so it is never taken for + // that account's answer. + property int duplicates: 0 readonly property var powerActions: Power.available(powerCaps) // All false until the daemon tells SDDM what the machine can do. readonly property var powerCaps: ({ @@ -77,72 +61,34 @@ Rectangle { return "file://" + assetDir + name } - function addUser(index, name, realName) { - userSlots[index] = { name: name, realName: realName } - var list = [] - var keys = Object.keys(userSlots).map(Number).sort(function (a, b) { return a - b }) - for (var i = 0; i < keys.length; i++) - list.push(userSlots[keys[i]]) - users = list - if (!selectionTouched) - selectedIndex = UserList.initialIndex(entries, userModel.lastUser) - Qt.callLater(focusInput) - } - - function select(index) { - selectionTouched = true - selectedIndex = Math.max(0, Math.min(index, entries.length - 1)) - password.input.text = "" - confirm.input.text = "" - loginFailed = false - message = "" - pendingPower = null - focusInput() - } - - function moveSelection(delta) { - select(UserList.step(selectedIndex, delta, entries.length)) + function addUser(index, name) { + userSlots[index] = name + userNames = Object.keys(userSlots).map(Number).sort(function (a, b) { return a - b }) + .map(function (key) { return userSlots[key] }) } - // The wheel stops at the ends, where it must not clear the password either. - function scrollSelection(delta) { - var next = UserList.clampedStep(selectedIndex, delta, entries.length) - if (next !== selectedIndex) - select(next) + function login() { + attemptUsers = Password.candidates(userModel.lastUser, userNames) + if (attemptUsers.length === 0 || password.input.text.length === 0) + return + pending = password.input.text + attempt = 0 + resends = 0 + send() } - // The username field when "Other user…" is selected and still empty, - // otherwise the password. - function focusInput() { - if (otherSelected && otherUser.text.trim().length === 0) - otherUser.forceActiveFocus() - else - password.input.forceActiveFocus() + function failLogin() { + pending = "" + awaiting = false + password.input.text = "" + loginFailed = true + password.input.forceActiveFocus() } - function login() { - var user = loginName - if (user.length === 0) { - otherUser.forceActiveFocus() - return - } - if (changeMode) { - var problem = Password.check(password.input.text, confirm.input.text) - if (problem !== "") { - // Clearing a box clears the message, so that goes first. - confirm.input.text = "" - message = Strings.t(localeName, problem === "empty" ? "emptyPassword" : "mismatch") - if (problem === "empty") - password.input.forceActiveFocus() - else - confirm.input.forceActiveFocus() - return - } - } - message = "" - lastPamMessage = "" - changeNoticeSeen = false - sddm.login(user, password.input.text, root.sessionIndex) + function send() { + awaiting = true + sddm.login(attemptUsers[attempt], pending, root.sessionIndex) + unanswered.restart() } function requestPower(action) { @@ -158,11 +104,10 @@ Rectangle { function runPower(action) { pendingPower = null password.input.text = "" - confirm.input.text = "" sddm[action.id]() } - // Shared by the text fields: list navigation, Escape and the power keys. + // Escape and the power keys. function handleCommonKey(event) { if (pendingPower !== null) { if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { @@ -181,13 +126,8 @@ Rectangle { if (event.key < Qt.Key_F1 || event.key > Qt.Key_F4) pendingPower = null } - if (event.key === Qt.Key_Up) { - moveSelection(-1) - } else if (event.key === Qt.Key_Down) { - moveSelection(1) - } else if (event.key === Qt.Key_Escape) { + if (event.key === Qt.Key_Escape) { password.input.text = "" - confirm.input.text = "" } else if (event.key >= Qt.Key_F1 && event.key <= Qt.Key_F4) { // Held down, the key would run it again as the machine wakes up. var action = Power.forFKey(powerCaps, event.key - Qt.Key_F1 + 1) @@ -202,39 +142,70 @@ Rectangle { Connections { target: sddm - function onInformationMessage(text) { - root.lastPamMessage = text - if (Password.isChangeNotice(text)) { - root.changeNoticeSeen = true - root.changeUsers = Password.withUser(root.changeUsers, root.loginName) - } - } function onLoginFailed() { - if (root.changeNoticeSeen) { - root.changeNoticeSeen = false + if (root.duplicates > 0) { + root.duplicates-- return } - root.loginFailed = true - password.input.text = "" - confirm.input.text = "" - if (root.changeMode) - root.message = root.lastPamMessage || Strings.t(root.localeName, "changeFailed") - password.input.forceActiveFocus() + root.duplicates = 1 + pairWindow.restart() + if (!root.awaiting) + return + root.awaiting = false + unanswered.stop() + if (root.pending !== "" && root.attempt + 1 < root.attemptUsers.length) { + root.attempt++ + root.resends = 0 + nextAttempt.start() + return + } + root.failLogin() } function onLoginSucceeded() { + root.awaiting = false + unanswered.stop() + root.pending = "" root.loginFailed = false } } - // userModel's roles (name, realName) are only reachable by name from a - // delegate, so each delegate reports its row to root.users. + // SDDM reports a failure before its helper has exited, and silently drops a login + // sent before then, so the next account waits a moment; an attempt still unanswered + // after pam_unix's failure delay was dropped, and is sent again, a few times at most. + Timer { + id: nextAttempt + interval: 300 + onTriggered: root.send() + } + + Timer { + id: unanswered + interval: 5000 + onTriggered: { + if (root.pending === "") + return + if (root.resends >= 3) { + root.failLogin() + return + } + root.resends++ + root.send() + } + } + + Timer { + id: pairWindow + interval: 1000 + onTriggered: root.duplicates = 0 + } + + // userModel's name role is only reachable from a delegate, so each reports its row. Repeater { model: userModel delegate: Item { required property int index required property string name - required property string realName - Component.onCompleted: root.addUser(index, name, realName) + Component.onCompleted: root.addUser(index, name) } } @@ -251,11 +222,10 @@ Rectangle { } // A password box: the stock entry image with a bullet per character (the - // text itself is transparent), and a hint while it is empty. + // text itself is transparent). component SecretField: Item { id: field property alias input: secret - property string placeholder: "" signal keyPressed(var event) width: fieldEntry.width height: fieldEntry.height @@ -283,18 +253,6 @@ Rectangle { } } - Text { - text: field.placeholder - visible: secret.text.length === 0 && text.length > 0 - color: root.textColor - opacity: 0.4 - font.family: root.fontFamily - font.pixelSize: 22 - anchors.left: parent.left - anchors.leftMargin: 20 - anchors.verticalCenter: parent.verticalCenter - } - TextInput { id: secret anchors.fill: parent @@ -313,7 +271,6 @@ Rectangle { onTextChanged: { root.loginFailed = false - root.message = "" } Keys.onPressed: function (event) { @@ -323,12 +280,7 @@ Rectangle { } Column { - // Centered, or higher when what hangs below the password row wouldn't - // clear the power actions. Counted for every user, so it never moves. - readonly property real centeredY: (root.height - height) / 2 - readonly property real clearY: root.height - height - belowPassword.reservedHeight - 64 - anchors.horizontalCenter: parent.horizontalCenter - y: Math.round(Math.max(0, Math.min(centeredY, clearY))) + anchors.centerIn: parent spacing: 40 ThemeImage { @@ -340,249 +292,29 @@ Rectangle { anchors.horizontalCenter: parent.horizontalCenter } - Column { + Row { + id: passwordRow anchors.horizontalCenter: parent.horizontalCenter spacing: 15 - ListView { - id: userList - readonly property int rowHeight: root.showUsername ? 52 : 36 - width: password.width - height: Math.min(count, root.maxVisibleUsers) * rowHeight - anchors.right: passwordRow.right - clip: true - interactive: count > root.maxVisibleUsers - boundsBehavior: Flickable.StopAtBounds - snapMode: ListView.SnapToItem - model: root.entries - currentIndex: root.selectedIndex - // A row stays visible on each side of the selected one, when it fits. - readonly property int contextHeight: root.maxVisibleUsers >= 3 ? rowHeight : 0 - highlightRangeMode: ListView.ApplyRange - preferredHighlightBegin: contextHeight - preferredHighlightEnd: height - contextHeight - // Slides once someone moves; the last user starts in place. - highlightMoveVelocity: -1 - highlightMoveDuration: root.selectionTouched ? 150 : 0 - visible: count > 0 - - delegate: Item { - id: row - required property int index - required property var modelData - readonly property bool current: index === root.selectedIndex - width: userList.width - height: userList.rowHeight - - Text { - id: marker - text: "›" - color: root.textColor - visible: row.current - font.family: root.fontFamily - font.pixelSize: 22 - anchors.left: parent.left - anchors.leftMargin: 4 - anchors.verticalCenter: label.verticalCenter - } - - Text { - id: label - text: row.modelData.other ? Strings.t(root.localeName, "otherUser") : row.modelData.label - color: root.textColor - opacity: row.current ? 1.0 : 0.55 - elide: Text.ElideRight - font.family: root.fontFamily - font.pixelSize: 22 - anchors.left: parent.left - anchors.leftMargin: 24 - anchors.right: parent.right - anchors.top: parent.top - anchors.topMargin: 2 - } - - Text { - text: row.modelData.secondary - visible: text.length > 0 - color: root.textColor - opacity: row.current ? 0.6 : 0.35 - elide: Text.ElideRight - font.family: root.fontFamily - font.pixelSize: 14 - anchors.left: label.left - anchors.right: parent.right - anchors.top: label.bottom - anchors.topMargin: 2 - } - - MouseArea { - anchors.fill: parent - onClicked: root.select(row.index) - } - } - } - - // Over the list, so the wheel selects instead of scrolling past the - // selection. Clicks and drags go through to the rows below. - MouseArea { - property real pending: 0 - parent: userList - anchors.fill: parent - z: 1 - acceptedButtons: Qt.NoButton - onWheel: function (event) { - pending += event.angleDelta.y - var notches = pending > 0 ? Math.floor(pending / 120) : Math.ceil(pending / 120) - if (notches !== 0) { - pending -= notches * 120 - root.scrollSelection(-notches) - } - } - } - - // Username field, only while "Other user…" is selected. - Item { - id: otherRow - visible: root.otherSelected - width: passwordRow.width - height: visible ? otherEntry.height : 0 - - ThemeImage { - id: otherEntry - assetName: root.loginFailed ? "entry-failed.png" : "entry.png" - anchors.right: parent.right - } - - TextInput { - id: otherUser - anchors.fill: otherEntry - anchors.leftMargin: 20 - anchors.rightMargin: 20 - verticalAlignment: TextInput.AlignVCenter - clip: true - color: root.textColor - selectionColor: root.textColor - selectedTextColor: root.color - font.family: root.fontFamily - font.pixelSize: 22 - inputMethodHints: Qt.ImhNoAutoUppercase | Qt.ImhNoPredictiveText | Qt.ImhPreferLowercase - enabled: root.otherSelected - - onTextChanged: root.loginFailed = false - - Text { - text: Strings.t(root.localeName, "username") - visible: otherUser.text.length === 0 - color: root.textColor - opacity: 0.4 - font: otherUser.font - anchors.verticalCenter: parent.verticalCenter - } - - Keys.onPressed: function (event) { - if (root.handleCommonKey(event)) - return - if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter - || event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) { - if (otherUser.text.trim().length > 0) - password.input.forceActiveFocus() - event.accepted = true - } - } - } - } - - Row { - id: passwordRow - anchors.horizontalCenter: parent.horizontalCenter - spacing: 15 - - ThemeImage { - assetName: root.loginFailed ? "lock-failed.png" : "lock.png" - width: 34 - height: 38 - fillMode: Image.PreserveAspectFit - anchors.verticalCenter: parent.verticalCenter - } - - SecretField { - id: password - placeholder: root.changeMode ? Strings.t(root.localeName, "newPassword") : "" - - onKeyPressed: function (event) { - if (root.handleCommonKey(event)) - return - if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { - if (root.changeMode && password.input.text.length > 0 && confirm.input.text.length === 0) - confirm.input.forceActiveFocus() - else - root.login() - event.accepted = true - } else if (event.key === Qt.Key_Tab && root.changeMode) { - confirm.input.forceActiveFocus() - event.accepted = true - } else if ((event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) && root.otherSelected) { - otherUser.forceActiveFocus() - event.accepted = true - } - } - } + ThemeImage { + assetName: root.loginFailed ? "lock-failed.png" : "lock.png" + width: 34 + height: 38 + fillMode: Image.PreserveAspectFit + anchors.verticalCenter: parent.verticalCenter } - // Hangs from this row, so none of it moves what is above. One pixel tall: - // a Column skips an item with no height, and what is inside it. - Item { - width: passwordRow.width - height: 1 - - Column { - id: belowPassword - // The box and the notice, plus a line for a message. Not its height, - // which changes with the user. - readonly property real reservedHeight: confirm.height + notice.height + 24 + 2 * spacing - width: password.width - anchors.right: parent.right - spacing: 15 - - // The new password again, only for an account choosing it now. - SecretField { - id: confirm - visible: root.changeMode - placeholder: Strings.t(root.localeName, "confirmPassword") - input.enabled: root.changeMode - - onKeyPressed: function (event) { - if (root.handleCommonKey(event)) - return - if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { - root.login() - event.accepted = true - } else if (event.key === Qt.Key_Tab || event.key === Qt.Key_Backtab) { - password.input.forceActiveFocus() - event.accepted = true - } - } - } - - Text { - id: notice - width: parent.width - text: Strings.t(root.localeName, "choosePassword") - visible: root.changeMode - color: root.textColor - wrapMode: Text.WordWrap - font.family: root.fontFamily - font.pixelSize: 18 - } + SecretField { + id: password - Text { - width: parent.width - text: root.message - visible: text.length > 0 - color: root.textColor - wrapMode: Text.WordWrap - font.family: root.fontFamily - font.pixelSize: 16 + onKeyPressed: function (event) { + if (root.handleCommonKey(event)) + return + if (event.key === Qt.Key_Return || event.key === Qt.Key_Enter) { + if (root.pending === "" && !root.awaiting) + root.login() + event.accepted = true } } } @@ -666,5 +398,13 @@ Rectangle { } } - Component.onCompleted: focusInput() + // Going to another console and back takes the keyboard away, and Qt drops the + // field's focus with it. Nothing gives it back when the keyboard returns, so typing + // and the F keys went nowhere until the field was clicked. + function restorePasswordFocus() { + if (!password.input.activeFocus) password.input.forceActiveFocus() + } + Window.onActiveFocusItemChanged: Qt.callLater(restorePasswordFocus) + + Component.onCompleted: password.input.forceActiveFocus() } diff --git a/sddm/omarchy-multiuser/Password.js b/sddm/omarchy-multiuser/Password.js index afd25ee..a2c98e9 100644 --- a/sddm/omarchy-multiuser/Password.js +++ b/sddm/omarchy-multiuser/Password.js @@ -1,64 +1,20 @@ -// Pure helpers for the first-login password. Loaded by Main.qml and, in the -// tests, by node (module.exports at the bottom), so no QML here. -// -// SDDM answers translated PAM prompts with what was typed in the greeter, so for -// an account with an empty, expired password (`passwd -d -e`) the typed text -// becomes "Nova senha" and "Redigite a nova senha" at once. The greeter asks for -// it twice instead, for the accounts omarchy-mu-sddm-sync lists in -// theme.conf.user (passwordChangeUsers). English prompts can't work: see -// greeter_takes_new_password in omarchy-mu-accounts. +// Pure helper for the login screen, which asks for a password alone. Loaded by +// Main.qml and, in the tests, by node (module.exports at the bottom), so no QML here. -// passwordChangeUsers as SDDM hands it over: a space-separated string (a -// list, from "a,b", only when the theme.conf default has one; SDDM drops -// lists from theme.conf.user). -function parseUsers(value) { - var list = Array.isArray(value) ? value : String(value || "").split(/[,\s]+/) - var users = [] - for (var i = 0; i < list.length; i++) { - var name = String(list[i] || "").trim() - if (name.length > 0 && users.indexOf(name) === -1) - users.push(name) +// The accounts to try the password for, in order: the last one to log in, then +// everyone else SDDM lists. omarchy-mu-login-match ends an attempt on the wrong +// one at once, so only a password that is nobody's counts as a failed login. +function candidates(lastUser, names) { + var list = [] + var all = [lastUser].concat(names || []) + for (var i = 0; i < all.length; i++) { + var name = String(all[i] || "") + if (name.length > 0 && list.indexOf(name) === -1) + list.push(name) } - return users -} - -function needsChange(users, user) { - return String(user || "").length > 0 && (users || []).indexOf(String(user)) !== -1 -} - -// The list with one more account, for one PAM reports after the list was -// written (a new array, so QML bindings see the change). -function withUser(users, user) { - var list = (users || []).slice() - if (String(user || "").length > 0 && list.indexOf(String(user)) === -1) - list.push(String(user)) return list } -// pam_unix's notice before it asks for the new password ("You are required -// to change your password immediately (...)", "Your password has expired; -// ...") and its Portuguese translations ("Mude sua senha imediatamente"). SDDM relays it as an error and reports the -// login as failed while the change still goes on. -function isChangeNotice(message) { - return /(required to change your password|password has expired|(mude|mudar|altere|alterar|troque|trocar) (a |sua )?senha|senha (expirou|expirada))/i - .test(String(message || "")) -} - -// "" when the two fields can go to sddm.login(), else what is wrong with them. -function check(password, confirmation) { - if (String(password || "").length === 0) - return "empty" - if (password !== confirmation) - return "mismatch" - return "" -} - if (typeof module !== "undefined") { - module.exports = { - parseUsers: parseUsers, - needsChange: needsChange, - withUser: withUser, - isChangeNotice: isChangeNotice, - check: check - } + module.exports = { candidates: candidates } } diff --git a/sddm/omarchy-multiuser/Strings.js b/sddm/omarchy-multiuser/Strings.js index 1aad57a..fc25b5f 100644 --- a/sddm/omarchy-multiuser/Strings.js +++ b/sddm/omarchy-multiuser/Strings.js @@ -3,14 +3,6 @@ var catalogs = { en: { - otherUser: "Other user…", - username: "Username", - choosePassword: "First login: choose your password", - newPassword: "New password", - confirmPassword: "Repeat the password", - emptyPassword: "Type a password", - mismatch: "The passwords don't match", - changeFailed: "The password wasn't changed", suspend: "Suspend", hibernate: "Hibernate", reboot: "Reboot", @@ -21,14 +13,6 @@ var catalogs = { cancel: "Cancel" }, pt: { - otherUser: "Outro usuário…", - username: "Nome de usuário", - choosePassword: "Primeiro acesso: escolha sua senha", - newPassword: "Nova senha", - confirmPassword: "Repita a senha", - emptyPassword: "Digite uma senha", - mismatch: "As senhas não coincidem", - changeFailed: "A senha não foi alterada", suspend: "Suspender", hibernate: "Hibernar", reboot: "Reiniciar", diff --git a/sddm/omarchy-multiuser/UserList.js b/sddm/omarchy-multiuser/UserList.js deleted file mode 100644 index 279e345..0000000 --- a/sddm/omarchy-multiuser/UserList.js +++ /dev/null @@ -1,82 +0,0 @@ -// Pure helpers for the greeter's user list. Loaded by Main.qml and, in the -// tests, by node (module.exports at the bottom), so no QML here. - -// What a row shows: the GECOS full name, or the username when it is empty. -function displayName(realName, name) { - var real = String(realName || "").trim() - return real.length > 0 ? real : String(name || "") -} - -// The username under the full name, only when it adds something. -function secondaryName(realName, name, showUsername) { - if (!showUsername) - return "" - var real = String(realName || "").trim() - var user = String(name || "") - return real.length > 0 && real !== user ? user : "" -} - -// Rows of the list: one per listed user, then "Other user…" when allowed (or -// when nobody is listed, since the greeter would otherwise have no way in). -function buildEntries(users, allowOther, showUsername) { - var entries = [] - var list = users || [] - for (var i = 0; i < list.length; i++) { - var u = list[i] - if (!u || !u.name) - continue - entries.push({ - other: false, - name: String(u.name), - label: displayName(u.realName, u.name), - secondary: secondaryName(u.realName, u.name, showUsername !== false) - }) - } - if (allowOther || entries.length === 0) - entries.push({ other: true, name: "", label: "", secondary: "" }) - return entries -} - -// Row selected at startup: SDDM's last user when listed, else the first row. -function initialIndex(entries, lastUser) { - var list = entries || [] - var last = String(lastUser || "") - for (var i = 0; i < list.length; i++) { - if (!list[i].other && list[i].name === last) - return i - } - return 0 -} - -// Up/Down move one row and wrap around. -function step(index, delta, count) { - if (count <= 0) - return 0 - return ((index + delta) % count + count) % count -} - -// The wheel moves too, but stops at the ends. -function clampedStep(index, delta, count) { - if (count <= 0) - return 0 - return Math.max(0, Math.min(index + delta, count - 1)) -} - -// Username handed to sddm.login(): the selected row's, or what was typed. -function loginUser(entry, typed) { - if (!entry) - return "" - return entry.other ? String(typed || "").trim() : entry.name -} - -if (typeof module !== "undefined") { - module.exports = { - displayName: displayName, - secondaryName: secondaryName, - buildEntries: buildEntries, - initialIndex: initialIndex, - step: step, - clampedStep: clampedStep, - loginUser: loginUser - } -} diff --git a/sddm/omarchy-multiuser/theme.conf b/sddm/omarchy-multiuser/theme.conf index 9a86d6f..46fbfb7 100644 --- a/sddm/omarchy-multiuser/theme.conf +++ b/sddm/omarchy-multiuser/theme.conf @@ -7,9 +7,3 @@ textColor=#c0caf5 # Images (logo, entry, lock, bullet) are read from the stock theme, which # omarchy-plymouth-set recolors; fallback/ holds the original copies. assetDir=/usr/share/sddm/themes/omarchy/ -# Offer an "Other user…" row that reveals a username field. -allowOtherUser=true -# Show the username under the full name when they differ. -showUsername=true -# Rows visible before the list scrolls. -maxVisibleUsers=6 diff --git a/share/menu-block.jsonc b/share/menu-block.jsonc index 1844fa7..a974dfc 100644 --- a/share/menu-block.jsonc +++ b/share/menu-block.jsonc @@ -20,6 +20,8 @@ "remove.security.sshd": {"when":"omarchy-mu-is-admin && systemctl is-enabled --quiet sshd"}, "remove.security.sudoless-docker": {"when":"omarchy-mu-is-admin && ! omarchy-sudo-docker --configured"}, "update.password.drive": {"when":"omarchy-mu-is-admin"}, + // The login password is also the account's disk key: plain passwd leaves it behind. + "update.password.user": {"action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-password"}, // Removing software drops packages for everyone. What lives in the user's // own home (themes, web apps, TUIs, the Windows VM, mise dev envs, Microsoft // and Xbox Cloud web apps, the SSH agent) stays theirs. @@ -48,11 +50,14 @@ "update.time": {"when":"omarchy-mu-is-admin"}, "update.config.plymouth": {"when":"omarchy-mu-is-admin"}, "update.hardware.trackpad": {"when":"omarchy-mu-is-admin"}, - // Accounts (administrators only). + // Everyone, once there is someone to switch to. + "system.switch-user": {"icon":"󰀙","label":"Switch User","when":"omarchy-mu-user-switch --available","action":"omarchy-mu-user-switch"}, + // Accounts (administrators only). The menu's search doesn't look at the parent's + // `when`, so each entry has its own. "setup.users": {"icon":"","label":"Users","when":"omarchy-mu-is-admin"}, - "setup.users.add": {"icon":"","label":"Add User","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-add"}, - "setup.users.remove": {"icon":"","label":"Remove User","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-remove"}, - "setup.users.admin": {"icon":"","label":"Administrator Rights","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-admin"}, - "setup.users.luks": {"icon":"","label":"Disk Unlock Password","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-luks-enroll"}, + "setup.users.add": {"icon":"","label":"Add User","when":"omarchy-mu-is-admin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-add"}, + "setup.users.remove": {"icon":"","label":"Remove User","when":"omarchy-mu-is-admin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-remove"}, + "setup.users.admin": {"icon":"","label":"Administrator Rights","when":"omarchy-mu-is-admin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-admin"}, + "setup.users.password": {"icon":"","label":"Change Password","when":"omarchy-mu-is-admin","action":"omarchy-launch-floating-terminal-with-presentation omarchy-mu-user-password"}, // This machine's per-user setup (omarchy-setup), when it is installed. "setup.omarchy-setup": {"icon":"","label":"Omarchy Setup","when":"command -v omarchy-setup-user","action":"omarchy-launch-floating-terminal-with-presentation omarchy-setup-user"}, diff --git a/shell/lock/LockActions.js b/shell/lock/LockActions.js index 55f67b4..7051248 100644 --- a/shell/lock/LockActions.js +++ b/shell/lock/LockActions.js @@ -41,6 +41,21 @@ function forFKey(offered, n) { return null } +// F5 asks for the login screen, which takes a moment to appear. Asking again +// meanwhile would start a second one, which SDDM can't show. +var SWITCH_USER_SETTLE_MS = 5000 + +function switchUserSettling(now, lastAskedMs) { + return lastAskedMs > 0 && now - lastAskedMs < SWITCH_USER_SETTLE_MS +} + +// The exit status of `omarchy-mu-lock-action session-active` that means the session +// is in the background. Anything else, a command that couldn't run included, must +// not leave someone at their own lock unable to open it. +function isBackgroundAnswer(exitCode) { + return exitCode === 1 +} + // A line from `omarchy-mu-lock-action watch-unlock` meaning logind was told to // unlock the session it watches. Exactly that line: the rest is gdbus talking. function isUnlockSignal(line) { @@ -53,6 +68,8 @@ if (typeof module !== "undefined") { parseCapabilities: parseCapabilities, available: available, forFKey: forFKey, + switchUserSettling: switchUserSettling, + isBackgroundAnswer: isBackgroundAnswer, isUnlockSignal: isUnlockSignal } } diff --git a/shell/lock/Service.qml b/shell/lock/Service.qml index f6d6dc4..8c8b570 100644 --- a/shell/lock/Service.qml +++ b/shell/lock/Service.qml @@ -69,6 +69,9 @@ Item { // user has given it their password there. Only then does the lock listen, so // logind's word never opens a lock nobody left through the login screen. property bool awaitingGreeterUnlock: false + property double lastSwitchUserMs: 0 + // PAM said yes and the lock is asking whether this session is on screen. + property bool unlockConfirming: false // A key that wakes the displays is only waking them, so it can't run anything. property bool displayBlanked: false property bool strandedLock: false @@ -226,22 +229,39 @@ Item { function runLockAction(action) { cancelLockAction() if (!lockRequested || lockActionProc.running) return + // Only from behind a lock the compositor confirmed, and only once. + if (action.id === "switchUser" && (!sessionLock.secure || LockActions.switchUserSettling(Date.now(), lastSwitchUserMs))) return enteredPassword = "" failureMessage = "" - // A session in the background has no business holding the reader: the next - // user needs it. Coming back to this one wakes it, which starts it again. if (action.id === "switchUser") { - pauseFingerprint() - if (fingerprintPam.active) fingerprintPam.abort() - settleFingerprintAttempt() + lastSwitchUserMs = Date.now() + releaseFingerprint() awaitingGreeterUnlock = true } lockActionProc.command = ["omarchy-mu-lock-action", action.id] lockActionProc.running = true } + // A session in the background has no business holding the reader: the next + // user needs it. Coming back to this one wakes it, which starts it again. + function releaseFingerprint() { + pauseFingerprint() + if (fingerprintPam.active) fingerprintPam.abort() + settleFingerprintAttempt() + } + + // An attempt started before leaving can finish after: a session opened behind + // the login screen would be open to whoever comes straight back to its console. + // The password stays "checking" until the answer, so nothing else starts. + function unlockIfOnScreen() { + if (unlockConfirming) return + unlockConfirming = true + unlockOnScreenCheck.running = true + } + function resetAuthenticationState() { cancelLockAction() + unlockConfirming = false awaitingGreeterUnlock = false enteredPassword = "" pendingPassword = "" @@ -325,6 +345,12 @@ Item { // The retry keeps whatever backoff was armed, counting the time spent blank, // so a failing reader still gets its idle window; after a sleep it recovers // at once, as the sleep watch does. + // For what happens on its own, also behind the login screen: a resume, a screen + // coming back. A key or a click only reaches a session on screen. + function resumeFingerprintIfOnScreen() { + if (fingerprintPaused && !fingerprintOnScreenCheck.running) fingerprintOnScreenCheck.running = true + } + function resumeFingerprint() { if (!fingerprintPaused) return fingerprintPaused = false @@ -513,7 +539,7 @@ Item { // A match after a run of misses is the recovery too; the unlock resets // the streak without settling, so log it here or it leaves no trace. if (fingerprintUnreachedStreak > 0) logEvent("fingerprint-recovered: streak=" + fingerprintUnreachedStreak) - finishUnlock() + unlockIfOnScreen() } else { settleFingerprintAttempt(result === PamResult.Error) } @@ -636,12 +662,15 @@ Item { onPamMessage: root.respondToPasswordPrompt() onCompleted: function(result) { - root.authenticatingPassword = false root.pendingPassword = "" + if (root.lockRequested && result === PamResult.Success) { + root.unlockIfOnScreen() + return + } + root.authenticatingPassword = false if (!root.lockRequested) return - if (result === PamResult.Success) root.finishUnlock() - else root.handlePasswordFailure() + root.handlePasswordFailure() } onError: function(error) { @@ -732,7 +761,7 @@ Item { if (slept && root.lockRequested && root.fingerprintPaused) { stop() root.fingerprintSleptWhilePaused = true - root.resumeFingerprint() + root.resumeFingerprintIfOnScreen() root.armBlankTimer() } else if (slept || !root.fingerprintPaused || --ticksLeft <= 0) { stop() @@ -871,6 +900,33 @@ Item { } } + // bash: a command that can't be found has to end in an exit status. + Process { + id: unlockOnScreenCheck + command: ["bash", "-c", "omarchy-mu-lock-action session-active"] + onExited: function(exitCode) { + if (!root.unlockConfirming) return + root.unlockConfirming = false + if (!root.lockRequested) return + if (!LockActions.isBackgroundAnswer(exitCode)) { + root.finishUnlock() + return + } + root.logEvent("unlock-refused: session in the background") + root.authenticatingPassword = false + root.enteredPassword = "" + root.releaseFingerprint() + } + } + + Process { + id: fingerprintOnScreenCheck + command: ["bash", "-c", "omarchy-mu-lock-action session-active"] + onExited: function(exitCode) { + if (!LockActions.isBackgroundAnswer(exitCode)) root.resumeFingerprint() + } + } + // A question nobody answered doesn't wait for the next Enter. Timer { id: lockActionTimeout @@ -954,7 +1010,7 @@ Item { function onScreensChanged() { var screens = root.realScreenCount() if (screens > root.knownScreenCount) { - root.resumeFingerprint() + root.resumeFingerprintIfOnScreen() if (root.lockRequested) root.armBlankTimer() } root.knownScreenCount = screens @@ -1011,6 +1067,18 @@ Item { return "ok" } + // For omarchy-mu-user-switch (System > Switch User). + function switchUser(): string { + if (!root.lockRequested || !sessionLock.secure) return "not-locked" + root.runLockAction({ id: "switchUser" }) + return "ok" + } + + function releaseReader(): string { + root.releaseFingerprint() + return "ok" + } + function isLocked(): string { return root.currentlyLocked() ? "true" : "false" } diff --git a/systemd/sddm.service.d/omarchy-mu-login-select.conf b/systemd/sddm.service.d/omarchy-mu-login-select.conf new file mode 100644 index 0000000..6643833 --- /dev/null +++ b/systemd/sddm.service.d/omarchy-mu-login-select.conf @@ -0,0 +1,7 @@ +# Decide at every SDDM start, not once at boot, whose desktop it opens. The first +# step takes any automatic login away and must succeed, or SDDM doesn't start into +# someone else's desktop; the second names the one account, or the one whose key +# slot unlocked the disk this boot, and may fail into the login screen. +[Service] +ExecStartPre=/usr/bin/omarchy-mu-login-select --clear +ExecStartPre=-/usr/bin/omarchy-mu-login-select diff --git a/systemd/system/omarchy-mu-sddm-sync.path b/systemd/system/omarchy-mu-sddm-sync.path index 5d3a335..4e92d18 100644 --- a/systemd/system/omarchy-mu-sddm-sync.path +++ b/systemd/system/omarchy-mu-sddm-sync.path @@ -1,9 +1,8 @@ [Unit] -Description=Watch the stock Omarchy greeter and /etc/shadow for the multi-user greeter (omarchy-multiuser) +Description=Watch the stock Omarchy greeter for the multi-user greeter (omarchy-multiuser) [Path] PathChanged=/usr/share/sddm/themes/omarchy -PathChanged=/etc/shadow [Install] WantedBy=multi-user.target diff --git a/systemd/system/omarchy-mu-sddm-sync.service b/systemd/system/omarchy-mu-sddm-sync.service index f5b78d8..f4db1ae 100644 --- a/systemd/system/omarchy-mu-sddm-sync.service +++ b/systemd/system/omarchy-mu-sddm-sync.service @@ -1,5 +1,5 @@ [Unit] -Description=Copy Appearance > Unlock colors and first-login accounts to the multi-user greeter (omarchy-multiuser) +Description=Copy Appearance > Unlock colors to the multi-user greeter (omarchy-multiuser) [Service] Type=oneshot diff --git a/tests/js/LockActions.test.js b/tests/js/LockActions.test.js index 85decb1..0a3cc77 100644 --- a/tests/js/LockActions.test.js +++ b/tests/js/LockActions.test.js @@ -15,6 +15,18 @@ test("only what the machine can do is offered", () => { assert.deepEqual(A.available({ reboot: "true" }), []) }) +test("F5 doesn't ask for the login screen twice in a row", () => { + assert.equal(A.switchUserSettling(1000, 0), false) + assert.equal(A.switchUserSettling(10000, 9000), true) + assert.equal(A.switchUserSettling(20000, 9000), false) +}) + +test("only a clear answer keeps an accepted password from opening the lock", () => { + assert.equal(A.isBackgroundAnswer(1), true) + assert.equal(A.isBackgroundAnswer(0), false) + assert.equal(A.isBackgroundAnswer(127), false) +}) + test("capabilities that can't be read offer nothing", () => { assert.deepEqual(A.parseCapabilities('{"reboot":true}'), { reboot: true }) assert.deepEqual(A.parseCapabilities(""), {}) diff --git a/tests/js/Password.test.js b/tests/js/Password.test.js index 6f37b85..68d0050 100644 --- a/tests/js/Password.test.js +++ b/tests/js/Password.test.js @@ -3,45 +3,18 @@ const test = require("node:test") const assert = require("node:assert/strict") const P = require("../../sddm/omarchy-multiuser/Password.js") -test("passwordChangeUsers as a list or a string", () => { - assert.deepEqual(P.parseUsers(["surubi", "coruja"]), ["surubi", "coruja"]) - assert.deepEqual(P.parseUsers("surubi"), ["surubi"]) - assert.deepEqual(P.parseUsers("surubi coruja"), ["surubi", "coruja"]) - assert.deepEqual(P.parseUsers("surubi, coruja,,surubi"), ["surubi", "coruja"]) - assert.deepEqual(P.parseUsers(""), []) - assert.deepEqual(P.parseUsers(undefined), []) +test("the last account first, then everyone else, once each", () => { + assert.deepEqual(P.candidates("bia", ["ana", "bia", "cau"]), ["bia", "ana", "cau"]) }) -test("who needs a new password", () => { - assert.equal(P.needsChange(["surubi"], "surubi"), true) - assert.equal(P.needsChange(["surubi"], "abutre"), false) - assert.equal(P.needsChange(["surubi"], ""), false) - assert.equal(P.needsChange(undefined, "surubi"), false) +test("no last account, or one SDDM doesn't list any more", () => { + assert.deepEqual(P.candidates("", ["ana", "bia"]), ["ana", "bia"]) + assert.deepEqual(P.candidates(undefined, ["ana"]), ["ana"]) + assert.deepEqual(P.candidates("velho", ["ana"]), ["velho", "ana"]) }) -test("adding an account reported by PAM", () => { - const users = ["surubi"] - assert.deepEqual(P.withUser(users, "coruja"), ["surubi", "coruja"]) - assert.deepEqual(P.withUser(users, "surubi"), ["surubi"]) - assert.notEqual(P.withUser(users, "surubi"), users) - assert.deepEqual(P.withUser(undefined, ""), []) -}) - -test("pam_unix's change notices", () => { - assert.equal(P.isChangeNotice("You are required to change your password immediately (administrator enforced)."), true) - assert.equal(P.isChangeNotice("You are required to change your password immediately (password expired)."), true) - assert.equal(P.isChangeNotice("Your password has expired; please change it now"), true) - assert.equal(P.isChangeNotice("Mude sua senha imediatamente (aplicado pela raiz)."), true) - assert.equal(P.isChangeNotice("Mude sua senha imediatamente (senha expirada)."), true) - assert.equal(P.isChangeNotice("Authentication failure"), false) - assert.equal(P.isChangeNotice("No password has been supplied."), false) - assert.equal(P.isChangeNotice("Nenhuma senha informada."), false) - assert.equal(P.isChangeNotice(""), false) -}) - -test("the two password fields", () => { - assert.equal(P.check("", ""), "empty") - assert.equal(P.check("abc", "abd"), "mismatch") - assert.equal(P.check("abc", ""), "mismatch") - assert.equal(P.check("abc", "abc"), "") +test("nobody to try", () => { + assert.deepEqual(P.candidates("", []), []) + assert.deepEqual(P.candidates("", undefined), []) + assert.deepEqual(P.candidates("", ["", null]), []) }) diff --git a/tests/js/Strings.test.js b/tests/js/Strings.test.js index 27d437c..fa250dc 100644 --- a/tests/js/Strings.test.js +++ b/tests/js/Strings.test.js @@ -14,9 +14,8 @@ test("language from locale names", () => { }) test("translations", () => { - assert.equal(S.t("pt_BR", "otherUser"), "Outro usuário…") - assert.equal(S.t("en_US", "otherUser"), "Other user…") - assert.equal(S.t("pt_BR", "username"), "Nome de usuário") - assert.equal(S.t("C", "username"), "Username") + assert.equal(S.t("pt_BR", "reboot"), "Reiniciar") + assert.equal(S.t("en_US", "reboot"), "Reboot") + assert.equal(S.t("C", "cancel"), "Cancel") assert.equal(S.t("pt_BR", "missing"), "missing") }) diff --git a/tests/js/UserList.test.js b/tests/js/UserList.test.js deleted file mode 100644 index 33769df..0000000 --- a/tests/js/UserList.test.js +++ /dev/null @@ -1,76 +0,0 @@ -// Run with: node --test tests/js/ -const test = require("node:test") -const assert = require("node:assert/strict") -const L = require("../../sddm/omarchy-multiuser/UserList.js") - -const users = [ - { name: "abutre", realName: "Laércio de Sousa" }, - { name: "fulana", realName: "" }, - { name: "beltrano", realName: " Beltrano " } -] - -test("displayName falls back to the username", () => { - assert.equal(L.displayName("Laércio de Sousa", "abutre"), "Laércio de Sousa") - assert.equal(L.displayName("", "fulana"), "fulana") - assert.equal(L.displayName(" ", "fulana"), "fulana") - assert.equal(L.displayName(undefined, "fulana"), "fulana") - assert.equal(L.displayName(" Beltrano ", "beltrano"), "Beltrano") -}) - -test("secondaryName only when it adds something", () => { - assert.equal(L.secondaryName("Laércio de Sousa", "abutre", true), "abutre") - assert.equal(L.secondaryName("", "fulana", true), "") - assert.equal(L.secondaryName("fulana", "fulana", true), "") - assert.equal(L.secondaryName("Laércio de Sousa", "abutre", false), "") -}) - -test("buildEntries lists users, then Other user", () => { - const e = L.buildEntries(users, true, true) - assert.equal(e.length, 4) - assert.deepEqual(e.map(x => x.label), ["Laércio de Sousa", "fulana", "Beltrano", ""]) - assert.equal(e[3].other, true) - assert.equal(e.slice(0, 3).every(x => x.other === false), true) -}) - -test("buildEntries without Other user", () => { - const e = L.buildEntries(users, false, true) - assert.equal(e.length, 3) - assert.equal(e.some(x => x.other), false) -}) - -test("buildEntries always offers Other user when nobody is listed", () => { - assert.deepEqual(L.buildEntries([], false, true), [{ other: true, name: "", label: "", secondary: "" }]) - assert.equal(L.buildEntries(undefined, false, true).length, 1) - assert.equal(L.buildEntries([{ name: "" }, null], false, true).length, 1) -}) - -test("initialIndex picks the last user, else the first row", () => { - const e = L.buildEntries(users, true, true) - assert.equal(L.initialIndex(e, "beltrano"), 2) - assert.equal(L.initialIndex(e, "nobody"), 0) - assert.equal(L.initialIndex(e, ""), 0) - assert.equal(L.initialIndex([], "abutre"), 0) -}) - -test("clampedStep stops at the ends", () => { - assert.equal(L.clampedStep(0, -1, 4), 0) - assert.equal(L.clampedStep(3, 1, 4), 3) - assert.equal(L.clampedStep(1, 1, 4), 2) - assert.equal(L.clampedStep(1, 5, 4), 3) - assert.equal(L.clampedStep(0, 1, 0), 0) -}) - -test("step wraps around", () => { - assert.equal(L.step(0, -1, 4), 3) - assert.equal(L.step(3, 1, 4), 0) - assert.equal(L.step(1, 1, 4), 2) - assert.equal(L.step(0, 1, 0), 0) -}) - -test("loginUser uses the row or the typed name", () => { - const e = L.buildEntries(users, true, true) - assert.equal(L.loginUser(e[0], "ignored"), "abutre") - assert.equal(L.loginUser(e[3], " ciclano "), "ciclano") - assert.equal(L.loginUser(e[3], ""), "") - assert.equal(L.loginUser(null, "x"), "") -}) diff --git a/tests/sh/lock-plugin.test.sh b/tests/sh/lock-plugin.test.sh index e9801f1..8c1433e 100755 --- a/tests/sh/lock-plugin.test.sh +++ b/tests/sh/lock-plugin.test.sh @@ -27,7 +27,7 @@ setup() { stub omarchy-system stub omarchy-toggle-enabled 'exit ${SUSPEND_OFF:-1}' stub omarchy-sleep-disabled 'exit ${SLEEP_DISABLED:-1}' - stub loginctl 'echo "${ACTIVE:-yes}"' + stub loginctl '[[ $1 == list-sessions ]] && { echo "${SESSIONS:-[]}"; exit 0; }; [[ $1 == activate ]] && exit ${ACTIVATE_STATUS:-0}; echo "${ACTIVE:-yes}"' cat >"$T/stubs/busctl" <>"$calls" @@ -194,6 +194,36 @@ test_capabilities_follow_the_machine() { assert_eq "$(CAN_POWEROFF=no omarchy-mu-lock-action capabilities | jq -c .powerOff)" false } +test_switching_waits_for_the_first_console() { + setup + held='[{"session":"1","user":"ana","seat":"seat0","class":"user","tty":"tty1"}]' + assert_eq "$(SESSIONS=$held omarchy-mu-lock-action capabilities | jq -c .switchUser)" false + # Only that entry: the rest of the lock screen stays. + assert_eq "$(SESSIONS=$held omarchy-mu-lock-action capabilities | jq -c .reboot)" true + on_its_own='[{"session":"3","user":"ana","seat":"seat0","class":"user","tty":"tty2"},{"session":"c1","user":"sddm","seat":"seat0","class":"greeter","tty":"tty1"},{"session":"4","user":"ana","seat":null,"class":"manager","tty":null}]' + assert_eq "$(SESSIONS=$on_its_own omarchy-mu-lock-action capabilities | jq -c .switchUser)" true +} + +test_switching_is_not_offered_when_the_sessions_cant_be_read() { + setup + assert_eq "$(SESSIONS='not json' omarchy-mu-lock-action capabilities | jq -c .switchUser)" false + stub loginctl 'exit 1' + assert_eq "$(omarchy-mu-lock-action capabilities | jq -c .switchUser)" false +} + +test_a_running_login_screen_is_gone_back_to() { + setup + SESSIONS='[{"session":"c1","user":"sddm","seat":"seat0","class":"greeter","tty":"tty1"}]' omarchy-mu-lock-action switchUser + assert_contains "$calls" "loginctl activate c1" + assert_not_contains "$calls" SwitchToGreeter +} + +test_a_login_screen_that_cant_be_gone_back_to_is_asked_for_again() { + setup + ACTIVATE_STATUS=1 SESSIONS='[{"session":"c1","user":"sddm","seat":"seat0","class":"greeter","tty":"tty1"}]' omarchy-mu-lock-action switchUser + assert_contains "$calls" SwitchToGreeter +} + test_actions_run_what_they_should() { setup omarchy-mu-lock-action switchUser diff --git a/tests/sh/luks-wrapper.test.sh b/tests/sh/luks-wrapper.test.sh new file mode 100755 index 0000000..32396bc --- /dev/null +++ b/tests/sh/luks-wrapper.test.sh @@ -0,0 +1,104 @@ +#!/bin/bash +# shellcheck disable=SC2031 # $T is set by run_tests in the subshell each test runs in +# shellcheck disable=SC2016 # the fake's code runs in the fake, not in this shell +# The initramfs cryptsetup wrapper, run by busybox ash as the initramfs runs it, in +# front of a fake real cryptsetup; and the hook's mkinitcpio drop-in. +# shellcheck source=lib.sh +source "$(dirname "$0")/lib.sh" + +busybox=/usr/lib/initcpio/busybox +[[ -x $busybox ]] || { echo "# luks-wrapper.test.sh: mkinitcpio's busybox not installed; skipped"; exit 0; } +wrapper=$REPO/initcpio/cryptsetup + +setup() { + export TEST_TMP=$T CRYPTSETUP_REAL=$T/real LUKS_SLOT_RECORD=$T/run/luks-slot + cat >"$T/real" <<'SH' +#!/bin/sh +echo "$*" >>"$TEST_TMP/calls" +case "$*" in + "luksUUID /dev/nvme0n1p2") echo uuid-root ;; + *--verbose*open*) + password=$(cat) + [ "$password" = "kidpass" ] || { echo "No key available with this passphrase." >&2; exit 2; } + echo "No usable token is available." + echo "Key slot 3 unlocked." + echo "Command successful." + echo "Something else cryptsetup said." + ;; +esac +SH + chmod +x "$T/real" +} + +unlock() { + printf '%s' "$1" | "$busybox" ash "$wrapper" open --type luks --key-file=- /dev/nvme0n1p2 root '>/dev/null' >"$T/stdout" 2>"$T/stderr" +} + +test_a_plymouth_unlock_runs_once_and_records_the_slot() { + setup + unlock kidpass || fail "a right password unlocks" + assert_eq "$(cat "$T/run/luks-slot")" "uuid-root 3" + assert_contains "$T/calls" 'open --type luks --key-file=- /dev/nvme0n1p2 root >/dev/null' + assert_eq "$(grep -c open "$T/calls")" 1 + assert_contains "$T/stdout" "Something else cryptsetup said" + assert_not_contains "$T/stdout" "Key slot" + assert_not_contains "$T/stdout" "Command successful" +} + +test_a_wrong_password_fails_as_it_would_have_and_records_nothing() { + setup + status=0 + unlock wrongpass || status=$? + assert_eq "$status" 2 + assert_no_file "$T/run/luks-slot" + assert_contains "$T/stderr" "No key available" +} + +test_other_calls_go_straight_through() { + setup + "$busybox" ash "$wrapper" isLuks /dev/nvme0n1p2 + assert_eq "$(cat "$T/calls")" "isLuks /dev/nvme0n1p2" + assert_no_file "$T/run/luks-slot" +} + +test_the_console_prompt_is_recorded_too() { + setup + printf 'kidpass' | "$busybox" ash "$wrapper" open --type luks /dev/nvme0n1p2 root >/dev/null 2>&1 || fail "unlock" + assert_eq "$(cat "$T/run/luks-slot")" "uuid-root 3" +} + +test_nowhere_to_keep_the_record_still_unlocks() { + setup + export LUKS_SLOT_RECORD=/proc/no-such-dir/luks-slot + printf 'kidpass' | "$busybox" ash "$wrapper" open --type luks --key-file=- /dev/nvme0n1p2 root >/dev/null 2>&1 || fail "unlock" +} + +test_the_wrapper_parses_and_the_build_step_checks_it() { + "$busybox" ash -n "$wrapper" || fail "doesn't parse" + assert_contains "$REPO/initcpio/install/omarchy-mu-luks-slot" 'busybox ash -n "$wrapper"' + bash -n "$REPO/initcpio/install/omarchy-mu-luks-slot" || fail "the hook doesn't parse" +} + +test_the_record_goes_where_login_select_looks() { + assert_contains "$wrapper" 'record=${LUKS_SLOT_RECORD:-/run/omarchy-multiuser/luks-slot}' + assert_contains "$REPO/lib/omarchy-multiuser/slots.sh" '$OMU_ROOT/run/omarchy-multiuser/luks-slot' +} + +hooks_for() { + OMU_SLOT_MAP_FILE=$1 bash -uc " + HOOKS=($2) + source '$REPO/etc/mkinitcpio.conf.d/zz-omarchy-mu-luks-slot.conf' + echo \"\${HOOKS[*]}\" + " +} + +test_the_hook_follows_encrypt_only_once_the_map_exists() { + line="base udev plymouth keyboard block encrypt filesystems fsck" + assert_eq "$(hooks_for "$T/absent" "$line")" "$line" + : >"$T/slots" + assert_eq "$(hooks_for "$T/slots" "$line")" "base udev plymouth keyboard block encrypt omarchy-mu-luks-slot filesystems fsck" + # A systemd initramfs has no encrypt hook to follow. + assert_eq "$(hooks_for "$T/slots" "base systemd sd-encrypt filesystems")" "base systemd sd-encrypt filesystems" +} + +run_tests diff --git a/tests/sh/sddm.test.sh b/tests/sh/sddm.test.sh index 82617e7..1152edd 100755 --- a/tests/sh/sddm.test.sh +++ b/tests/sh/sddm.test.sh @@ -39,34 +39,6 @@ test_sync_without_stock_theme_removes_override() { assert_no_file "$(themes)/omarchy-multiuser/theme.conf.user" } -test_sync_lists_first_login_accounts() { - setup_themes - # shellcheck disable=SC2016 # a literal shadow hash, not an expansion - printf '%s\n' 'abutre:$6$hash:20000:0:99999:7:::' 'surubi::0:0:99999:7:::' \ - 'coruja::0:0:99999:7:::' 'locked:!:0:0:99999:7:::' 'blank::20000:0:99999:7:::' >"$T/etc/shadow" - omarchy-mu-sddm-sync >/dev/null - conf="$(themes)/omarchy-multiuser/theme.conf.user" - assert_contains "$conf" "passwordChangeUsers=surubi coruja" -} - -test_sync_drops_accounts_once_they_chose() { - setup_themes - printf '%s\n' 'surubi::0:0:99999:7:::' >"$T/etc/shadow" - omarchy-mu-sddm-sync >/dev/null - # shellcheck disable=SC2016 # a literal shadow hash, not an expansion - printf '%s\n' 'surubi:$6$hash:20000:0:99999:7:::' >"$T/etc/shadow" - omarchy-mu-sddm-sync >/dev/null - assert_not_contains "$(themes)/omarchy-multiuser/theme.conf.user" "passwordChangeUsers" -} - -test_sync_keeps_first_login_accounts_without_colors() { - setup_themes - rm -rf "$(themes)/omarchy" - printf '%s\n' 'surubi::0:0:99999:7:::' >"$T/etc/shadow" - omarchy-mu-sddm-sync >/dev/null - assert_eq "$(cat "$(themes)/omarchy-multiuser/theme.conf.user")" $'[General]\npasswordChangeUsers=surubi' -} - test_guard_removes_autologin() { setup_themes cp "$REPO/etc/sddm.conf.d/zz-omarchy-multiuser.conf" "$T/etc/sddm.conf.d/" @@ -86,6 +58,58 @@ test_guard_reports_sddm_conf_autologin() { true } +test_guard_leaves_the_automatic_login_of_this_boot_alone() { + setup_themes + cp "$REPO/etc/sddm.conf.d/zz-omarchy-multiuser.conf" "$T/etc/sddm.conf.d/" + printf '[Autologin]\nUser=abutre\nSession=omarchy.desktop\nRelogin=false\n' >"$T/etc/sddm.conf.d/zzz-omarchy-mu-autologin.conf" + omarchy-mu-sddm-guard >/dev/null || fail "took login-select's choice for a problem" + assert_file "$T/etc/sddm.conf.d/zzz-omarchy-mu-autologin.conf" +} + +test_guard_puts_login_match_first_in_the_pam_stack_once() { + setup_themes + cp "$REPO/etc/sddm.conf.d/zz-omarchy-multiuser.conf" "$T/etc/sddm.conf.d/" + mkdir -p "$T/etc/pam.d" + printf '#%%PAM-1.0\n\nauth include system-login\n-auth optional pam_kwallet5.so\n\naccount include system-login\n' >"$T/etc/pam.d/sddm" + omarchy-mu-sddm-guard --check 2>/dev/null && fail "check passed without it" + omarchy-mu-sddm-guard >/dev/null || fail "guard failed" + assert_eq "$(grep -E '^-?auth' "$T/etc/pam.d/sddm" | head -1)" "auth [success=die default=ignore] pam_exec.so quiet expose_authtok /usr/bin/omarchy-mu-login-match" + assert_eq "$(grep -c omarchy-mu-login-match "$T/etc/pam.d/sddm")" 1 + cp "$T/etc/pam.d/sddm" "$T/once" + omarchy-mu-sddm-guard >/dev/null + cmp -s "$T/once" "$T/etc/pam.d/sddm" || fail "second run changed the stack" + omarchy-mu-sddm-guard --check || fail "check failed with it" +} + +test_removing_the_package_stops_the_guard_before_cleaning_up() { + install=$REPO/packaging/omarchy-multiuser.install + stop=$(grep -n 'disable --now omarchy-mu-sddm-guard.path' "$install" | cut -d: -f1) + clean=$(grep -n 'rm -f /etc/sddm.conf.d/zzz-omarchy-mu-autologin.conf' "$install" | cut -d: -f1) + [[ -n $stop && -n $clean && $stop -lt $clean ]] || fail "the guard would put the PAM line back" +} + +test_removing_the_package_leaves_no_migration_watcher_behind() { + wants=$T/wants + mkdir -p "$wants" + ln -s /dev/null "$wants/omarchy-mu-migrate-record@ana.path" + ln -s /dev/null "$wants/omarchy-mu-migrate-record@bob.path" + ln -s /dev/null "$wants/other.path" + # systemctl gets to ana's and fails on bob's, whose link has to go anyway. + # shellcheck disable=SC2329 # called by the install script + systemctl() { + echo "$*" >>"$T/calls" + [[ $3 == *@ana.path ]] && rm -f "$wants/$3" + [[ $3 == *@ana.path ]] + } + # shellcheck source=/dev/null # only defines functions + source "$REPO/packaging/omarchy-multiuser.install" + _disable_migration_watchers "$wants" + assert_eq "$(ls "$wants")" "other.path" + assert_contains "$T/calls" "disable --now omarchy-mu-migrate-record@ana.path" + assert_contains "$T/calls" "disable --now omarchy-mu-migrate-record@bob.path" + grep -q '^ _disable_migration_watchers$' "$REPO/packaging/omarchy-multiuser.install" || fail "pre_remove doesn't call it" +} + test_guard_reports_wrong_theme() { setup_themes printf '[Theme]\nCurrent=omarchy\n' >"$T/etc/sddm.conf.d/10-theme.conf" diff --git a/tests/sh/slots.test.sh b/tests/sh/slots.test.sh new file mode 100755 index 0000000..2b18354 --- /dev/null +++ b/tests/sh/slots.test.sh @@ -0,0 +1,389 @@ +#!/bin/bash +# shellcheck disable=SC2031 # $T is set by run_tests in the subshell each test runs in +# shellcheck disable=SC2016 # the stubs' code runs in the stubs, not in this shell +# omarchy-mu-user-helper, -login-select and -login-match against a fake tree, with a +# real LUKS header in a file: cryptsetup does all of this without root or a device. +# shellcheck source=lib.sh +source "$(dirname "$0")/lib.sh" +# shellcheck source=user-stubs.sh +source "$(dirname "$0")/user-stubs.sh" + +command -v cryptsetup >/dev/null || { echo "# slots.test.sh: cryptsetup not installed; skipped"; exit 0; } + +hash_of() { perl -e 'print crypt($ARGV[0], "\$6\$saltsalt\$")' "$1"; } + +# Passwords of the fake accounts. +OWNER=owner-pass BOB=bob-pass-1 + +setup() { + user_stubs + export OMU_REFUSAL_DELAY=0 OMU_LUKS_PBKDF="--pbkdf pbkdf2 --pbkdf-force-iterations 1000" + export OMU_REBUILD_BOOT=$T/stubs/rebuild OMU_LIFECYCLE_DISPATCH=$T/stubs/dispatch OMU_STATE_DIR=$T/state + mkdir -p "$T/state" "$T/etc/sddm.conf.d" + printf 'root:x:0:0::/root:/bin/bash\nowner:x:1000:1000:Owner:/home/owner:/bin/bash\nbob:x:1001:1001:Bob:/home/bob:/bin/bash\nsddm:x:900:900::/var/lib/sddm:/usr/bin/nologin\n' >"$T/etc/passwd" + printf 'wheel:x:998:owner\nomarchy-users:x:950:bob\n' >"$T/etc/group" + { + echo 'root:!:1::::::' + echo "owner:$(hash_of "$OWNER"):1::::::" + echo 'bob:!:1::::::' + } >"$T/etc/shadow" + # Takes the new password's real hash, as chpasswd does, one write for all lines. + cat >"$T/stubs/chpasswd" <<'STUB' +#!/bin/bash +[[ ! -e $T/chpasswd-fails ]] || exit 1 +while IFS=: read -r user password; do + hash=$(perl -e 'print crypt($ARGV[0], "\$6\$saltsalt\$")' "$password") + awk -F: -v OFS=: -v u="$user" -v h="$hash" '$1 == u { $2 = h } { print }' "$T/etc/shadow" >"$T/etc/shadow.new" + mv "$T/etc/shadow.new" "$T/etc/shadow" +done +STUB + printf '#!/bin/bash\necho rebuild >>"$T/calls"\n' >"$T/stubs/rebuild" + printf '#!/bin/bash\nexit 3\n' >"$T/stubs/dispatch" + chmod +x "$T/stubs/chpasswd" "$T/stubs/rebuild" "$T/stubs/dispatch" + # The real sleep: omarchy-mu-login-match's watchdog would go off at once. + rm -f "$T/stubs/omarchy-mu-user-helper" "$T/stubs/sleep" + export SUDO_USER=owner ME=owner + export OMU_SYSTEM_DRIVE=$T/disk + truncate -s 32M "$T/disk" + # shellcheck disable=SC2086 # options, split on purpose + printf '%s' "$OWNER" | cryptsetup luksFormat -q $OMU_LUKS_PBKDF --key-file - "$T/disk" || fail "no LUKS image" + UUID=$(cryptsetup luksUUID "$T/disk") + map=$T/etc/omarchy-multiuser/slots +} + +opens() { + printf '%s' "$1" | LC_ALL=C cryptsetup open --test-passphrase --verbose --token-type passphrase-only --key-file - "$T/disk" 2>&1 | + grep -o 'Key slot [0-9]*' | grep -o '[0-9]*' +} + +helper() { + printf '%s\n%s\n' "$1" "$2" | omarchy-mu-user-helper "${@:3}" +} + +give_bob_a_password() { + helper "$OWNER" "$BOB" password bob 2>"$T/err" || fail "bob's password: $(cat "$T/err")" +} + +test_a_person_gets_a_key_slot_of_their_own() { + setup + give_bob_a_password + assert_eq "$(opens "$BOB")" 1 + assert_eq "$(opens "$OWNER")" 0 + assert_contains "$map" "$UUID 1 1001 bob " + assert_contains "$map" "$UUID 0 1000 owner " + [[ $(stat -c %a "$map") == 600 ]] || fail "the map is readable by others" + assert_no_file "$T/state/password-journal" + grep -q "^bob:\$6" "$T/etc/shadow" || fail "bob has no password" +} + +test_the_boot_image_is_rebuilt_once_for_a_second_person() { + setup + give_bob_a_password + assert_eq "$(grep -c '^rebuild' "$T/calls")" 1 + helper "$BOB" bob-pass-2 password bob 2>/dev/null || true + helper "$OWNER" bob-pass-3 password bob 2>/dev/null || fail "changing again" + assert_eq "$(grep -c '^rebuild' "$T/calls")" 1 +} + +test_changing_a_password_replaces_the_old_key() { + setup + give_bob_a_password + helper "$OWNER" bob-pass-2 password bob 2>/dev/null || fail "change" + assert_eq "$(opens bob-pass-2)" 2 + assert_eq "$(opens "$BOB")" "" + assert_eq "$(grep -c " bob " "$map")" 1 + assert_contains "$map" "$UUID 2 1001 bob " +} + +test_a_short_or_taken_password_changes_nothing() { + setup + helper "$OWNER" short password bob 2>"$T/err" && fail "took a short password" + assert_contains "$T/err" "at least 6" + helper "$OWNER" "$OWNER" password bob 2>"$T/err" && fail "took the owner's password" + assert_contains "$T/err" "already unlocks this computer" + assert_eq "$(opens "$BOB")" "" + grep -q '^bob:!' "$T/etc/shadow" || fail "bob's password changed" +} + +test_a_password_left_only_on_the_disk_is_taken_too() { + setup + printf '%s\nold-disk-pass' "$OWNER" | bash -c 'IFS= read -r c; exec cryptsetup luksAddKey -q $OMU_LUKS_PBKDF --key-file <(printf "%s" "$c") "$T/disk" <(cat)' + printf 'old-disk-pass\n' | omarchy-mu-user-helper check-new 2>"$T/err" && fail "took a password the disk knows" + assert_contains "$T/err" "already unlocks this computer" + printf 'brand-new-pass\n' | omarchy-mu-user-helper check-new || fail "refused a free password" +} + +test_the_wrong_own_password_changes_nothing() { + setup + helper not-mine "$BOB" password bob 2>"$T/err" && fail "took a wrong password" + assert_contains "$T/err" "isn't owner's password" + assert_eq "$(opens "$BOB")" "" +} + +test_a_login_password_the_disk_doesnt_know_says_what_to_do() { + setup + awk -F: -v OFS=: -v h="$(hash_of other-login)" '$1 == "owner" { $2 = h } { print }' "$T/etc/shadow" >"$T/s" && mv "$T/s" "$T/etc/shadow" + helper other-login "$BOB" password bob 2>"$T/err" && fail "added a key with no key" + assert_contains "$T/err" "omarchy-drive-password" +} + +test_only_an_administrator_changes_someone_elses() { + setup + export SUDO_USER=bob + helper "$BOB" other-pass-1 password owner 2>"$T/err" && fail "bob changed the owner's" + assert_contains "$T/err" "Only an administrator" + assert_eq "$(opens "$OWNER")" 0 + printf 'x\n' | omarchy-mu-user-helper check-new 2>/dev/null && fail "bob asked whose password" + omarchy-mu-user-helper forget owner 2>/dev/null && fail "bob took the owner's key" + assert_eq "$(opens "$OWNER")" 0 +} + +test_nobody_outside_sudo_gets_anywhere() { + setup + unset SUDO_USER + helper "$OWNER" "$BOB" password bob 2>"$T/err" && fail "ran without a caller" + assert_contains "$T/err" "through sudo" +} + +test_a_limited_account_changes_its_own_three_times_an_hour() { + setup + give_bob_a_password + export SUDO_USER=bob + helper "$BOB" bob-pass-2 password-self 2>"$T/err" || fail "own password: $(cat "$T/err")" + assert_eq "$(opens bob-pass-2)" 2 + assert_eq "$(opens "$BOB")" "" + helper wrong-one bob-pass-3 password-self 2>/dev/null && fail "took a wrong current password" + helper wrong-two bob-pass-3 password-self 2>/dev/null && fail "took a wrong current password" + helper bob-pass-2 bob-pass-3 password-self 2>"$T/err" && fail "a fourth try" + assert_contains "$T/err" "three password changes" + [[ $(stat -c %a "$T/run/omarchy-multiuser/rate/1001") == 600 ]] || fail "the count is others' to read" +} + +test_a_stop_before_the_account_took_it_goes_back() { + setup + give_bob_a_password + : >"$T/chpasswd-fails" + helper "$OWNER" bob-pass-2 password bob 2>/dev/null && fail "said it changed" + assert_eq "$(opens bob-pass-2)" "" + assert_eq "$(opens "$BOB")" 1 + assert_no_file "$T/state/password-journal" +} + +test_a_stop_after_the_account_took_it_goes_forward() { + setup + give_bob_a_password + old_fp=$(grep ' bob ' "$map" | cut -d' ' -f5) + # As a power cut leaves it: the key added, shadow written, the phase not recorded. + printf '%s\nbob-pass-2' "$OWNER" | bash -c 'IFS= read -r c; exec cryptsetup luksAddKey -q $OMU_LUKS_PBKDF --key-slot 2 --key-file <(printf "%s" "$c") "$T/disk" <(cat)' + printf 'bob:bob-pass-2\n' | "$T/stubs/chpasswd" + printf 'user=bob\nuuid=%s\nslot=2\nold_slot=1\nold_fp=%s\nphase=key\n' "$UUID" "$old_fp" >"$T/state/password-journal" + omarchy-mu-user-helper finish || fail "finish" + assert_contains "$map" "$UUID 2 1001 bob " + assert_eq "$(opens "$BOB")" "" + assert_eq "$(opens bob-pass-2)" 2 + assert_no_file "$T/state/password-journal" +} + +test_a_journal_from_another_disk_stops_everything() { + setup + printf 'user=bob\nuuid=other-disk\nslot=2\nold_slot=-\nold_fp=x\nphase=key\n' >"$T/state/password-journal" + helper "$OWNER" "$BOB" password bob 2>"$T/err" && fail "changed over a stranger's journal" + assert_contains "$T/err" "another disk" + assert_eq "$(opens "$BOB")" "" +} + +test_forgetting_takes_the_key_with_nobodys_password() { + setup + give_bob_a_password + omarchy-mu-user-helper forget bob "$T/open" + timeout 20 omarchy-mu-user-helper forget bob <&8 2>"$T/err" || fail "exit $?: $(cat "$T/err")" + assert_eq "$(opens "$BOB")" "" + [[ ! -s $T/err ]] || fail "said: $(cat "$T/err")" +} + +test_forgetting_refuses_the_disks_last_key() { + setup + printf '%s %s %s %s %s\n' "$UUID" 0 1001 bob fp >"$T/map" ; mkdir -p "${map%/*}"; mv "$T/map" "$map" + omarchy-mu-user-helper forget bob "$T/err" && fail "locked the disk for good" + assert_contains "$T/err" "last one" + assert_eq "$(opens "$OWNER")" 0 +} + +test_an_old_recorded_slot_is_replaced_and_forgotten() { + setup + printf '%s\nold-bob-disk' "$OWNER" | bash -c 'IFS= read -r c; exec cryptsetup luksAddKey -q $OMU_LUKS_PBKDF --key-file <(printf "%s" "$c") "$T/disk" <(cat)' + mkdir -p "${map%/*}" + printf 'bob 1\n' >"$T/etc/omarchy-multiuser/luks-slots" + give_bob_a_password + assert_eq "$(opens old-bob-disk)" "" + assert_eq "$(opens "$BOB")" 2 + assert_not_contains "$T/etc/omarchy-multiuser/luks-slots" bob +} + +test_an_unencrypted_machine_only_has_passwords() { + setup + export OMU_SYSTEM_DRIVE= + give_bob_a_password + grep -q '^bob:\$6' "$T/etc/shadow" || fail "bob has no password" + assert_no_file "$map" + assert_not_contains "$T/calls" rebuild +} + +test_the_only_account_keeps_root_with_it() { + setup + sed -i '/^bob:/d' "$T/etc/passwd" "$T/etc/shadow" + sed -i "s|^root:!:|root:$(hash_of "$OWNER"):|" "$T/etc/shadow" + helper "$OWNER" new-owner-pass password-self 2>/dev/null || fail "change" + assert_eq "$(grep '^root:' "$T/etc/shadow" | cut -d: -f2)" "$(hash_of new-owner-pass)" +} + +test_a_locked_root_stays_locked() { + setup + give_bob_a_password + grep -q '^root:!' "$T/etc/shadow" || fail "unlocked root" +} + +# --- omarchy-mu-login-select ------------------------------------------------------ + +autologin_file() { echo "$T/etc/sddm.conf.d/zzz-omarchy-mu-autologin.conf"; } +record() { mkdir -p "$T/run/omarchy-multiuser"; printf '%s %s\n' "$1" "$2" >"$T/run/omarchy-multiuser/luks-slot"; } +select_login() { omarchy-mu-login-select --clear && omarchy-mu-login-select; } + +test_the_slot_that_opened_the_disk_opens_its_owners_desktop() { + setup + give_bob_a_password + record "$UUID" 1 + select_login || fail "select" + assert_contains "$(autologin_file)" "User=bob" + assert_contains "$(autologin_file)" "Relogin=false" +} + +test_the_record_is_used_once() { + setup + give_bob_a_password + record "$UUID" 1 + select_login + assert_file "$(autologin_file)" + select_login || fail "second start" + assert_no_file "$(autologin_file)" +} + +test_anything_unsure_shows_the_login_screen() { + setup + give_bob_a_password + for bad in "$UUID 9" "other-disk 1" "$UUID x"; do + read -r a b <<<"$bad"; record "$a" "$b" + select_login + assert_no_file "$(autologin_file)" + done + rm -f "$T/run/omarchy-multiuser/luks-slot" + select_login + assert_no_file "$(autologin_file)" +} + +test_a_password_changed_with_passwd_shows_the_login_screen() { + setup + give_bob_a_password + printf 'bob:changed-elsewhere\n' | "$T/stubs/chpasswd" + record "$UUID" 1 + select_login + assert_no_file "$(autologin_file)" +} + +test_an_unfinished_change_shows_the_login_screen() { + setup + give_bob_a_password + printf 'user=bob\nuuid=%s\nphase=key\n' "$UUID" >"$T/state/password-journal" + record "$UUID" 1 + select_login + assert_no_file "$(autologin_file)" +} + +test_a_broken_map_shows_the_login_screen() { + setup + give_bob_a_password + printf '%s 0 1000 bob fp\n' "$UUID" >>"$map" + record "$UUID" 1 + select_login + assert_no_file "$(autologin_file)" +} + +test_one_account_on_an_encrypted_disk_is_logged_in() { + setup + sed -i '/^bob:/d' "$T/etc/passwd" + select_login + assert_contains "$(autologin_file)" "User=owner" +} + +test_an_unencrypted_machine_is_never_logged_in() { + setup + sed -i '/^bob:/d' "$T/etc/passwd" + export OMU_SYSTEM_DRIVE= + select_login + assert_no_file "$(autologin_file)" +} + +test_clear_takes_every_automatic_login_away() { + setup + printf '[Autologin]\nUser=owner\n' >"$T/etc/sddm.conf.d/autologin.conf" + printf '[Autologin]\nUser=owner\n' >"$(autologin_file)" + omarchy-mu-login-select --clear || fail "clear" + assert_no_file "$T/etc/sddm.conf.d/autologin.conf" + assert_no_file "$(autologin_file)" +} + +test_sddm_conf_naming_someone_stops_sddm_with_two_people_only() { + setup + printf '[Autologin]\nUser=owner\n' >"$T/etc/sddm.conf" + omarchy-mu-login-select --clear 2>/dev/null && fail "started SDDM into someone's desktop" + sed -i '/^bob:/d' "$T/etc/passwd" + omarchy-mu-login-select --clear || fail "stopped SDDM on a one-person machine" +} + +# --- omarchy-mu-login-match ------------------------------------------------------- + +match_for() { printf '%s\0' "$2" | PAM_TYPE=auth PAM_USER=$1 omarchy-mu-login-match; } + +test_another_accounts_password_ends_the_attempt() { + setup + give_bob_a_password + printf '#!/bin/bash\nprintf "h\\nh\\n"\n' >"$T/stubs/faillock"; chmod +x "$T/stubs/faillock" + match_for owner "$BOB" || fail "tried bob's password as the owner" +} + +test_the_accounts_own_or_nobodys_password_goes_on_to_the_stack() { + setup + give_bob_a_password + printf '#!/bin/bash\nprintf "h\\nh\\n"\n' >"$T/stubs/faillock"; chmod +x "$T/stubs/faillock" + if match_for bob "$BOB"; then fail "ended bob's own login"; fi + if match_for bob nobodys-pass; then fail "ended a wrong password early"; fi +} + +test_a_locked_owners_password_takes_the_slow_refusal() { + setup + give_bob_a_password + printf '#!/bin/bash\nprintf "h\\nh\\nWhen Type Source Valid\\n"\n' >"$T/stubs/faillock"; chmod +x "$T/stubs/faillock" + if match_for owner "$BOB"; then fail "a fast refusal told a guesser about the lockout"; fi + printf '#!/bin/bash\nexit 1\n' >"$T/stubs/faillock" + if match_for owner "$BOB"; then fail "counted a faillock that can't say as no failures"; fi +} + +test_only_an_auth_step_with_a_real_name_counts() { + setup + give_bob_a_password + if printf '%s\0' "$BOB" | PAM_TYPE=session PAM_USER=owner omarchy-mu-login-match; then fail "another PAM step"; fi + if printf '%s\0' "$BOB" | PAM_TYPE=auth PAM_USER='../owner' omarchy-mu-login-match; then fail "a strange name"; fi +} + +run_tests diff --git a/tests/sh/user-add.test.sh b/tests/sh/user-add.test.sh index 12231b0..44fa5fd 100755 --- a/tests/sh/user-add.test.sh +++ b/tests/sh/user-add.test.sh @@ -19,106 +19,51 @@ setup() { shadow_of() { awk -F: -v u="$1" '$1 == u { print $2 ":" $3 }' "$T/etc/shadow"; } -test_a_new_account_chooses_its_password_at_the_login_screen() { +test_the_password_goes_in_after_everything_else() { setup omarchy-mu-user-add bob --full-name "Bob B" >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" - assert_eq "$(shadow_of bob)" ":0" - assert_contains "$T/calls" "passwd -d -e bob" - assert_contains "$T/out" "first login" - assert_contains "$T/usr/share/sddm/themes/omarchy-multiuser/theme.conf.user" "passwordChangeUsers=bob" + assert_eq "$(grep -E '^(useradd|runuser|omarchy-mu-user-helper) ' "$T/calls" | cut -d' ' -f1,2 | paste -sd,)" \ + "omarchy-mu-user-helper check-new,useradd --create-home,runuser -u,omarchy-mu-user-helper password" + assert_contains "$T/calls" "omarchy-mu-user-helper password bob" + # check-new's one password, then the caller's and the new one. + assert_eq "$(cat "$T/helper-stdin")" $'sekret-pw\nsekret-pw\nsekret-pw' } -test_the_account_opens_after_everything_else() { +test_a_password_someone_else_has_stops_before_anything_changes() { setup - omarchy-mu-user-add bob --full-name "Bob B" --luks >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" - assert_eq "$(grep -nE '^(runuser|omarchy-mu-luks-enroll|passwd) ' "$T/calls" | cut -d' ' -f1 | cut -d: -f2 | paste -sd' ')" \ - "runuser omarchy-mu-luks-enroll passwd" -} - -test_set_password_asks_for_it_now() { - setup - omarchy-mu-user-add bob --full-name "Bob B" --set-password >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" - assert_contains "$T/calls" "passwd bob" - assert_not_contains "$T/calls" "passwd -d" - assert_eq "$(shadow_of bob)" "!:20000" -} - -test_interactive_answer_keeps_the_old_way() { - setup - printf 'n\nn\nn\n' >"$T/gum-answers" - cat >"$T/stubs/gum" <<'STUB' -#!/bin/bash -if [[ $1 == input ]]; then - case $* in *username*) echo bob ;; *"Full name"*) echo "Bob B" ;; esac - exit 0 -fi -answer=$(head -1 "$T/gum-answers"); sed -i 1d "$T/gum-answers" -[[ $answer == y ]] -STUB - omarchy-mu-user-add >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" - assert_contains "$T/calls" "passwd bob" - assert_not_contains "$T/calls" "passwd -d" + echo check-new >"$T/helper-fails" + omarchy-mu-user-add bob --full-name "Bob B" >"$T/out" 2>&1 && fail "added bob" + assert_not_contains "$T/calls" useradd + assert_not_contains "$T/calls" usermod } -test_english_prompts_fall_back_to_asking_now() { +test_passwords_are_asked_until_they_match() { setup - printf 'LANG=en_US.UTF-8\n' >"$T/etc/locale.conf" + printf 'one-pass\ntwo-pass\ngood-pass\ngood-pass\nmine-pass\n' >"$T/gum-answers" omarchy-mu-user-add bob --full-name "Bob B" >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" - assert_contains "$T/out" "this machine's language" - assert_contains "$T/calls" "passwd bob" - assert_not_contains "$T/calls" "passwd -d" - assert_eq "$(shadow_of bob)" "!:20000" -} - -test_an_administrator_is_warned_about_first_come() { - setup - omarchy-mu-user-add bob --full-name "Bob B" --admin >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" - assert_contains "$T/out" "would get root" - assert_eq "$(shadow_of bob)" ":0" + assert_contains "$T/out" "don't match" + assert_eq "$(cat "$T/helper-stdin")" $'good-pass\nmine-pass\ngood-pass' } -test_first_login_never_replaces_a_password() { +test_a_password_that_fails_last_says_how_to_finish() { setup - omarchy-mu-accounts first-login owner 2>"$T/err" && fail "emptied a password" - assert_contains "$T/err" "already has a password" - assert_not_contains "$T/calls" "passwd" - assert_eq "$(shadow_of owner)" '$6$owner:1' + echo password >"$T/helper-fails" + omarchy-mu-user-add bob --full-name "Bob B" >"$T/out" 2>&1 && fail "said it worked" + assert_contains "$T/out" "omarchy-mu-user-password bob" } -test_first_login_refuses_system_accounts_and_strangers() { +test_interactive_asks_for_everything() { setup - omarchy-mu-accounts first-login root 2>"$T/err" && fail "opened root" - omarchy-mu-accounts first-login nobody 2>"$T/err" && fail "opened an unknown account" - assert_not_contains "$T/calls" "passwd" -} - -test_first_login_without_the_greeter_stays_locked() { - setup - printf 'bob:x:1001:1001::/home/bob:/bin/bash\n' >>"$T/etc/passwd" - printf 'bob:!:20000:0:99999:7:::\n' >>"$T/etc/shadow" - rm "$T/usr/share/sddm/themes/omarchy-multiuser/Main.qml" - omarchy-mu-accounts first-login bob 2>"$T/err" && fail "opened it with no greeter to ask" - assert_contains "$T/err" "isn't installed" - assert_eq "$(shadow_of bob)" "!:20000" -} - -test_first_login_locks_again_when_passwd_goes_wrong() { - setup - printf 'bob:x:1001:1001::/home/bob:/bin/bash\n' >>"$T/etc/passwd" - # Empty but not expired: nothing would ask for a password. - printf 'bob::20000:0:99999:7:::\n' >>"$T/etc/shadow" - : >"$T/passwd-fails" - omarchy-mu-accounts first-login bob 2>"$T/err" && fail "reported success" - assert_contains "$T/err" "stays locked" - assert_eq "$(shadow_of bob)" "!:20000" + printf 'bob\nBob B\n\nn\n' >"$T/gum-answers" + omarchy-mu-user-add >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" + assert_contains "$T/calls" "omarchy-mu-user-helper password bob" } -test_first_login_expires_an_empty_password() { +test_an_account_can_no_longer_wait_to_choose() { setup - printf 'bob:x:1001:1001::/home/bob:/bin/bash\n' >>"$T/etc/passwd" - printf 'bob::20000:0:99999:7:::\n' >>"$T/etc/shadow" - omarchy-mu-accounts first-login bob >/dev/null 2>&1 || fail "failed" - assert_eq "$(shadow_of bob)" ":0" + omarchy-mu-user-add bob --full-name "Bob B" --set-password 2>"$T/err" && fail "took an option that is gone" + omarchy-mu-accounts first-login bob 2>"$T/err" && fail "first-login is gone" + true } test_adds_an_account() { @@ -159,6 +104,21 @@ test_a_watcher_that_fails_only_warns() { assert_contains "$T/etc/passwd" "bob:x:" } +test_refuses_while_sddm_conf_logs_someone_in() { + setup + printf '[Autologin]\nUser=owner\n' >"$T/etc/sddm.conf" + omarchy-mu-user-add bob --full-name "Bob B" 2>"$T/err" && fail "added a second person to an automatic login" + assert_contains "$T/err" "logs someone in automatically" + assert_not_contains "$T/calls" useradd +} + +test_an_sddm_conf_without_automatic_login_is_fine() { + setup + printf '[Autologin]\nUser=\n\n[Other]\nUser=owner\n' >"$T/etc/sddm.conf" + omarchy-mu-user-add bob --full-name "Bob B" >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" + assert_contains "$T/calls" useradd +} + test_refuses_a_kept_home() { setup mkdir "$T/home/bob" diff --git a/tests/sh/user-remove.test.sh b/tests/sh/user-remove.test.sh index 9e86683..cb8480a 100755 --- a/tests/sh/user-remove.test.sh +++ b/tests/sh/user-remove.test.sh @@ -20,10 +20,62 @@ call_line() { grep -nF -- "$1" "$T/calls" | head -1 | cut -d: -f1; } assert_nothing_changed() { in_passwd bob || fail "bob was removed" assert_not_contains "$T/calls" userdel - assert_not_contains "$T/calls" omarchy-mu-luks-enroll + assert_not_contains "$T/calls" "omarchy-mu-user-helper forget" assert_not_contains "$T/calls" fprintd-delete } +test_a_disk_password_that_stays_keeps_the_account() { + setup + echo forget >"$T/helper-fails" + echo y >"$T/gum-answers" + omarchy-mu-user-remove bob --keep-home >"$T/out" 2>&1 && fail "said it removed bob" + assert_contains "$T/out" "still opens the disk" + in_passwd bob || fail "bob is gone, so nothing says whose keyslot that is" + assert_not_contains "$T/calls" userdel +} + +on_first_console() { + printf '[{"session":"1","user":"%s","seat":"seat0","class":"user","tty":"tty1"}]\n' "$1" >"$T/sessions" + mkdir -p "$T/sys/class/tty/tty0" + echo "$2" >"$T/sys/class/tty/tty0/active" + echo bob >>"$T/running" + printf 'y\ny\n' >"$T/gum-answers" +} + +test_a_desktop_on_the_first_console_leaves_the_login_screen() { + setup + on_first_console bob tty3 + omarchy-mu-user-remove bob --keep-home >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" + assert_contains "$T/calls" "SwitchToGreeter" + (( $(call_line "loginctl terminate-user bob") < $(call_line SwitchToGreeter) )) || fail "asked before the desktop ended" + assert_contains "$T/out" "Ctrl+Alt+F3" + assert_not_contains "$T/out" "didn't come back" +} + +test_there_is_no_console_to_come_back_to_from_the_first_one() { + setup + on_first_console bob tty1 + omarchy-mu-user-remove bob --keep-home >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" + assert_contains "$T/calls" "SwitchToGreeter" + assert_not_contains "$T/out" "Ctrl+Alt" +} + +test_a_login_screen_that_cant_come_back_only_warns() { + setup + on_first_console bob tty3 + : >"$T/busctl-fails" + omarchy-mu-user-remove bob --keep-home >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" + assert_contains "$T/out" "didn't come back" + assert_contains "$T/out" "Removed bob." +} + +test_someone_elses_desktop_on_the_first_console_is_left_alone() { + setup + on_first_console carol tty3 + omarchy-mu-user-remove bob --keep-home >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" + assert_not_contains "$T/calls" SwitchToGreeter +} + test_removes_account_and_what_it_leaves_behind() { setup printf 'bob ALL=(ALL) ALL\n' >"$T/etc/sudoers.d/10_bob" @@ -33,7 +85,7 @@ test_removes_account_and_what_it_leaves_behind() { assert_contains "$T/out" "Removed bob." assert_not_contains "$T/out" "mail spool" assert_no_file "$T/etc/sudoers.d/10_bob" - assert_contains "$T/calls" "omarchy-mu-luks-enroll --locked --remove bob" + assert_contains "$T/calls" "omarchy-mu-user-helper forget bob" assert_contains "$T/calls" "fprintd-delete bob" assert_contains "$T/calls" "loginctl disable-linger bob" assert_contains "$T/calls" "omarchy-mu-apply-lock --quiet" @@ -139,7 +191,7 @@ test_running_programs_are_ended_before_anything_changes() { omarchy-mu-user-remove bob --keep-home >"$T/out" 2>&1 || fail "exit $?: $(cat "$T/out")" assert_contains "$T/calls" "has programs running" terminate=$(call_line "loginctl terminate-user bob") - luks=$(call_line "omarchy-mu-luks-enroll") + luks=$(call_line "omarchy-mu-user-helper forget") [[ -n $terminate && $terminate -lt $luks ]] || fail "the keyslot went before the sign-out" (( $(call_line "loginctl disable-linger bob") < terminate )) || fail "linger outlived the sign-out" } diff --git a/tests/sh/user-stubs.sh b/tests/sh/user-stubs.sh index 4796025..a4edce8 100644 --- a/tests/sh/user-stubs.sh +++ b/tests/sh/user-stubs.sh @@ -6,13 +6,18 @@ # # $T/running accounts with programs running (pgrep); signing them out # empties it, except for those also in $T/unkillable -# $T/gum-answers gum confirm's answers, one per call: y, n or c (cancel) +# $T/gum-answers gum's answers, one per call: y, n or c (cancel) to confirm, +# the text to input, which is sekret-pw with none left # $T/sudo-l what sudo -l -U prints, instead of "not allowed" # $T/userdel-fails account: nothing happens; home: the account goes, its # home stays +# $T/sessions what loginctl lists, as JSON; signing out empties it +# $T/busctl-fails asking SDDM for its login screen fails; otherwise that adds +# a greeter to the first console user_stubs() { mkdir -p "$T/stubs" "$T/etc/sudoers.d" "$T/etc/systemd/system/multi-user.target.wants" "$T/run/lock" "$T/home" : >"$T/run/lock/omarchy-mu-accounts.lock" + : >"$T/run/lock/omarchy-mu-slots.lock" : >"$T/etc/shadow" : >"$T/calls" cat >"$T/stubs/getent" <<'STUB' @@ -94,6 +99,8 @@ cat >/dev/null STUB cat >"$T/stubs/sudo" <<'STUB' #!/bin/bash +[[ $1 != -v ]] || exit 0 +[[ $1 != -n ]] || shift if [[ $1 == -l ]]; then if [[ -f $T/sudo-l ]]; then cat "$T/sudo-l"; else echo "User $3 is not allowed to run sudo on this host."; fi exit 0 @@ -111,11 +118,22 @@ grep -qx "${*: -1}" "$T/unkillable" 2>/dev/null || sed -i "/^${*: -1}$/d" "$T/ru STUB cat >"$T/stubs/loginctl" <<'STUB' #!/bin/bash +if [[ $1 == list-sessions ]]; then + cat "$T/sessions" 2>/dev/null || echo '[]' + exit 0 +fi echo "loginctl $*" >>"$T/calls" if [[ $1 == terminate-user ]] && ! grep -qx "$2" "$T/unkillable" 2>/dev/null; then sed -i "/^$2$/d" "$T/running" 2>/dev/null + rm -f "$T/sessions" fi exit 0 +STUB + cat >"$T/stubs/busctl" <<'STUB' +#!/bin/bash +echo "busctl $*" >>"$T/calls" +[[ ! -e $T/busctl-fails ]] || exit 1 +echo '[{"session":"c1","user":"sddm","seat":"seat0","class":"greeter","tty":"tty1"}]' >"$T/sessions" STUB # Enabling a watcher is its WantedBy symlink. cat >"$T/stubs/systemctl" <<'STUB' @@ -132,30 +150,26 @@ STUB #!/bin/bash echo "gum $*" >>"$T/calls" answer=$(head -1 "$T/gum-answers"); sed -i 1d "$T/gum-answers" +if [[ $1 == input ]]; then + echo "${answer:-sekret-pw}" + exit 0 +fi case $answer in y) exit 0 ;; c) exit 130 ;; *) exit 1 ;; esac STUB - cat >"$T/stubs/passwd" <<'STUB' -#!/bin/bash -echo "passwd $*" >>"$T/calls" -[[ ! -e $T/passwd-fails ]] || exit 1 -[[ $1 == -d && $2 == -e ]] || exit 0 -sed -i -E "s/^($3):[^:]*:[^:]*:/\1::0:/" "$T/etc/shadow" -STUB - # PAM's catalog, by the language the caller asks for. - cat >"$T/stubs/gettext" <<'STUB' + # Reads the passwords like the real one; $T/helper-fails names an action that fails. + cat >"$T/stubs/omarchy-mu-user-helper" <<'STUB' #!/bin/bash -case ${LC_ALL:-} in - pt*) printf 'Nova senha: ' ;; - *) printf '%s' "${*: -1}" ;; -esac +echo "omarchy-mu-user-helper $*" >>"$T/calls" +[[ $1 == forget ]] || cat >>"$T/helper-stdin" +[[ $(cat "$T/helper-fails" 2>/dev/null) != "$1" ]] STUB # Nothing to do for the commands that have their own tests, or need hardware. local cmd - for cmd in runuser fprintd-delete omarchy-mu-fido2-authfile omarchy-mu-luks-enroll omarchy-mu-apply-lock; do + for cmd in runuser fprintd-delete omarchy-mu-fido2-authfile omarchy-mu-apply-lock; do # shellcheck disable=SC2016 # $* and $T belong to the stub printf '#!/bin/bash\necho "%s $*" >>"$T/calls"\n' "$cmd" >"$T/stubs/$cmd" done diff --git a/tests/sh/user-switch.test.sh b/tests/sh/user-switch.test.sh new file mode 100755 index 0000000..8b7f33a --- /dev/null +++ b/tests/sh/user-switch.test.sh @@ -0,0 +1,102 @@ +#!/bin/bash +# shellcheck disable=SC2031 # $T is set by run_tests in the subshell each test runs in +# shellcheck disable=SC2016 # the stubs' code runs in the stubs, not in this shell +# shellcheck source=lib.sh +source "$(dirname "$0")/lib.sh" + +setup() { + mkdir -p "$T/stubs" + calls=$T/calls + : >"$calls" + stub() { + printf '#!/bin/bash\necho "%s $*" >>"%s"\n%s\n' "$1" "$calls" "${2:-}" >"$T/stubs/$1" + chmod +x "$T/stubs/$1" + } + stub id 'echo ana' + stub getent 'printf "ana:x:1000:1000:Ana Lima:/home/ana:/bin/bash\nbia:x:1001:1001:Bia Reis,,,:/home/bia:/bin/bash\ncau:x:1002:1002::/home/cau:/bin/bash\nnobody:x:65534:65534::/:/usr/bin/nologin\n" | { [[ $# -gt 1 ]] && grep "^$2:" || cat; }' + stub omarchy-system-lock + stub omarchy-hyprland-session-locked 'exit ${NOT_LOCKED:-0}' + stub sleep + stub omarchy-notification-send + stub omarchy-menu-select 'printf "%b" "${CHOICE:-}"; exit ${MENU_STATUS:-0}' + stub omarchy-shell '[[ $2 == switchUser ]] && echo "${IPC:-ok}"; exit 0' + stub omarchy-mu-lock-action + export SESSIONS='[{"session":"2","user":"ana","seat":"seat0","class":"user","tty":"tty2"},{"session":"5","user":"bia","seat":null,"class":"manager","tty":null},{"session":"6","user":"bia","seat":"seat0","class":"user","tty":"tty3"}]' + stub loginctl '[[ $1 == list-sessions ]] && echo "$SESSIONS"; exit 0' + export PATH=$T/stubs:$PATH +} + +first_console='[{"session":"2","user":"ana","seat":"seat0","class":"user","tty":"tty1"}]' + +test_someone_signed_in_is_opened_after_locking() { + setup + omarchy-mu-user-switch bia + assert_contains "$calls" "omarchy-shell lock releaseReader" + assert_contains "$calls" "loginctl activate 6" + [[ $(grep -n omarchy-system-lock "$calls" | cut -d: -f1) -lt $(grep -n 'loginctl activate' "$calls" | cut -d: -f1) ]] || + fail "activated before locking" +} + +test_someone_not_signed_in_gets_the_login_screen_through_the_lock() { + setup + omarchy-mu-user-switch cau + assert_contains "$calls" "omarchy-shell lock switchUser" + assert_not_contains "$calls" "omarchy-mu-lock-action" + assert_not_contains "$calls" "loginctl activate" +} + +test_omarchys_own_lock_screen_still_reaches_the_login_screen() { + setup + IPC=unknown omarchy-mu-user-switch cau + assert_contains "$calls" "omarchy-mu-lock-action switchUser" +} + +test_an_automatic_login_is_offered_a_logout_and_nothing_locks() { + setup + SESSIONS=$first_console omarchy-mu-user-switch cau + assert_contains "$calls" "--exec omarchy-system logout" + assert_not_contains "$calls" omarchy-system-lock + assert_not_contains "$calls" switchUser +} + +test_an_automatic_login_still_reaches_someone_signed_in() { + setup + SESSIONS='[{"session":"2","user":"ana","seat":"seat0","class":"user","tty":"tty1"},{"session":"6","user":"bia","seat":"seat0","class":"user","tty":"tty3"}]' omarchy-mu-user-switch bia + assert_contains "$calls" "loginctl activate 6" +} + +test_a_desktop_that_did_not_lock_switches_nothing() { + setup + if NOT_LOCKED=1 omarchy-mu-user-switch bia 2>/dev/null; then fail "switched"; fi + assert_not_contains "$calls" "loginctl activate" +} + +test_only_someone_else_with_an_account() { + setup + if omarchy-mu-user-switch ana 2>/dev/null; then fail "switched to myself"; fi + if omarchy-mu-user-switch nobody 2>/dev/null; then fail "switched to a system account"; fi + assert_not_contains "$calls" omarchy-system-lock +} + +test_the_menu_lists_full_names_and_returns_the_account() { + setup + CHOICE='Bia Reis\tbia' omarchy-mu-user-switch + assert_contains "$calls" "Bia Reis" + assert_contains "$calls" "loginctl activate 6" +} + +test_cancelling_the_menu_does_nothing() { + setup + MENU_STATUS=1 omarchy-mu-user-switch || fail "cancelling is no failure" + CHOICE='' omarchy-mu-user-switch || fail "an empty answer is no failure" + assert_not_contains "$calls" omarchy-system-lock +} + +test_available_only_with_someone_else() { + setup + omarchy-mu-user-switch --available || fail "there are others" + stub getent 'printf "ana:x:1000:1000:Ana:/home/ana:/bin/bash\n"' + if omarchy-mu-user-switch --available; then fail "nobody else"; fi +} + +run_tests diff --git a/tmpfiles.d/omarchy-multiuser.conf b/tmpfiles.d/omarchy-multiuser.conf index 6cdc116..2b4a6a4 100644 --- a/tmpfiles.d/omarchy-multiuser.conf +++ b/tmpfiles.d/omarchy-multiuser.conf @@ -3,3 +3,5 @@ # create them under their own name and keep the others out. f /run/lock/omarchy-mu-accounts.lock 0640 root wheel - f /run/lock/omarchy-mu-update.lock 0640 root wheel - +# Root's alone: omarchy-mu-user-helper holds it, for limited accounts too. +f /run/lock/omarchy-mu-slots.lock 0600 root root -