From dec92adb08006bfe54fe4ca2d973c781d4aa088a Mon Sep 17 00:00:00 2001 From: fabolous005 Date: Fri, 4 Dec 2026 06:57:53 +0100 Subject: [PATCH] EAC Linux v2 on Gentoo with OpenRC: ebuilds, host config, tools, docs --- .gitignore | 1 + AGENTS.md | 273 ++++++++++++++++++ README.md | 97 +++++++ docs/progress.md | 60 ++++ docs/troubleshooting.md | 66 +++++ host/portage/package.use/intel-microcode | 1 + host/udev/61-dri-igpu.rules | 1 + overlay/metadata/layout.conf | 3 + overlay/profiles/repo_name | 1 + .../eac-openrc-compat-0.1-r1.ebuild | 48 +++ .../eac-openrc-compat/files/README.md | 80 +++++ .../files/easyanticheat_eos.confd | 5 + .../eac-openrc-compat/files/socket-activate | 63 ++++ .../files/socket-activate.initd | 32 ++ .../eac-openrc-compat/files/systemctl | 65 +++++ .../eac-openrc-compat/files/systemd-run | 69 +++++ .../eac-openrc-compat/files/systemd-run-agent | 67 +++++ .../cachyos-eac-kernel-bin/Manifest | 4 + .../cachyos-eac-kernel-bin-7.3.5_p2-r2.ebuild | 87 ++++++ .../cachyos-eac-kernel-bin/files/README.md | 73 +++++ .../cachyos-eac-kernel-bin/files/eac-boot | 126 ++++++++ tools/README.md | 45 +++ tools/eac-catch | 75 +++++ tools/efi-sig-list.py | 62 ++++ tools/exec-snoop | 23 ++ tools/exec-trace | 60 ++++ tools/systemctl-trace | 11 + tools/systemd1-trace | 58 ++++ tools/systemd1-trace.conf | 10 + 29 files changed, 1566 insertions(+) create mode 100644 .gitignore create mode 100644 AGENTS.md create mode 100644 README.md create mode 100644 docs/progress.md create mode 100644 docs/troubleshooting.md create mode 100644 host/portage/package.use/intel-microcode create mode 100644 host/udev/61-dri-igpu.rules create mode 100644 overlay/metadata/layout.conf create mode 100644 overlay/profiles/repo_name create mode 100644 overlay/sys-apps/eac-openrc-compat/eac-openrc-compat-0.1-r1.ebuild create mode 100644 overlay/sys-apps/eac-openrc-compat/files/README.md create mode 100644 overlay/sys-apps/eac-openrc-compat/files/easyanticheat_eos.confd create mode 100755 overlay/sys-apps/eac-openrc-compat/files/socket-activate create mode 100644 overlay/sys-apps/eac-openrc-compat/files/socket-activate.initd create mode 100755 overlay/sys-apps/eac-openrc-compat/files/systemctl create mode 100755 overlay/sys-apps/eac-openrc-compat/files/systemd-run create mode 100755 overlay/sys-apps/eac-openrc-compat/files/systemd-run-agent create mode 100644 overlay/sys-kernel/cachyos-eac-kernel-bin/Manifest create mode 100755 overlay/sys-kernel/cachyos-eac-kernel-bin/cachyos-eac-kernel-bin-7.3.5_p2-r2.ebuild create mode 100644 overlay/sys-kernel/cachyos-eac-kernel-bin/files/README.md create mode 100755 overlay/sys-kernel/cachyos-eac-kernel-bin/files/eac-boot create mode 100644 tools/README.md create mode 100755 tools/eac-catch create mode 100755 tools/efi-sig-list.py create mode 100755 tools/exec-snoop create mode 100755 tools/exec-trace create mode 100755 tools/systemctl-trace create mode 100755 tools/systemd1-trace create mode 100644 tools/systemd1-trace.conf diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..c18dd8d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +__pycache__/ diff --git a/AGENTS.md b/AGENTS.md new file mode 100644 index 0000000..a901300 --- /dev/null +++ b/AGENTS.md @@ -0,0 +1,273 @@ +# Installing the EAC setup (runbook for agents) + +This runbook installs everything in this repository on the author's desktop, +"lucifer". It is written for that machine; the values below are its values. +For systemd systems see [the last section](#systemd-systems). + +Read [README.md](README.md) first. When a step fails, look the message up in +[docs/troubleshooting.md](docs/troubleshooting.md). + +## Values for this machine + +| Item | Value | +| --- | --- | +| Host | `lucifer`, reached as `ssh -o BatchMode=yes fabian@192.168.2.169` | +| Root | `doas -n` (no sudo) | +| System | Gentoo, OpenRC, elogind, polkit, Hyprland 0.57 with Lua config in `~/.config/hypr/` | +| User | `fabian`, uid 1000 | +| Overlay | `febuild` at `/var/db/repos/febuild` (canonical, root-owned git); `overlay/` here is a snapshot | +| ESP | `/efi` (vfat) | +| Secure Boot keys | sbctl, keys in `/var/lib/sbctl/keys/`, PK/KEK/db enrolled | +| Normal kernel | `sys-kernel/cachyos-kernel`, EFI stub in `/efi/EFI/Gentoo/`, signed with the sbctl db key by `USE=secureboot` | +| EAC firmware entry | `Boot0201`, label `CachyOS EAC` | +| iGPU | PCI `0000:00:02.0`: `xe` on the normal kernel, `i915` on the EAC kernel | +| Windows | second disk, BitLocker | +| This repository | `~/coding/misc/eac-gentoo-openrc` on lucifer; commands with `tools/` or `host/` paths run from there | + +## Rules + +- Run read-only checks before each phase and show the user what will change. + The user decides whether you run `emerge` or they do. +- Never re-sign, strip or `sbctl sign` anything from CachyOS. Never use + `sbctl enroll-keys --append`. +- Never change firmware settings or write PK/KEK. Only the user toggles Secure + Boot, in the firmware setup. +- Never type a password. The polkit dialog on the first game launch is for the + user. +- Write probe scripts to a file and run them with + `ssh ... bash -s < probe.sh > out.txt`; read `out.txt` afterwards. +- Stop at an unexpected result and report it. Do not work around a failed check. + +Steps marked **(user)** need the person at the machine. + +## 0. Preflight (read-only) + +```sh +cat /sys/class/tpm/tpm0/tpm_version_major # 2 +ls /sys/kernel/iommu_groups | wc -l # > 0 +doas -n sbctl status # Installed, Setup Mode disabled +rc-service elogind status; pgrep -x polkitd +df -h /efi # >= 200 MB free +efibootmgr # note BootOrder and Boot0201 +emerge -p sys-kernel/cachyos-eac-kernel-bin sys-apps/eac-openrc-compat sys-auth/hyprpolkitagent +``` + +`emerge -p` must resolve both packages from `febuild`. If `febuild` lacks them, +add `overlay/` from this repository as a repository in +`/etc/portage/repos.conf/eac-gentoo-openrc.conf` (`location` = absolute path of +`overlay/`). Missing keywords: `~amd64` in `package.accept_keywords`. + +## 1. Packages + +```sh +doas -n install -m644 host/portage/package.use/intel-microcode /etc/portage/package.use/ +doas -n emerge sys-firmware/intel-microcode sys-kernel/cachyos-eac-kernel-bin \ + sys-apps/eac-openrc-compat sys-auth/hyprpolkitagent +``` + +On lucifer the USE flag already sits in `/etc/portage/package.use/sys-fimware`; +skip the copy there. `intel-microcode` with `dist-kernel` reinstalls the normal +kernel, which is harmless. + +Check: + +```sh +ls /lib/modules/*-cachyos-eac/vmlinuz /usr/lib/cachyos-eac/systemd-bootx64.efi.signed +eac-boot esp # /efi +qfile /usr/bin/systemctl /usr/bin/systemd-run /usr/lib64/libsystemd.so.0 +ldd /usr/libexec/hyprpolkitagent | grep 'not found' # empty +``` + +Libraries reported "not found" for hyprpolkitagent mean a live (`9999`) Hyprland +library changed its SONAME: rebuild the packages that link the old one +(`emerge -1`), see troubleshooting. + +## 2. Secure Boot db + +Back up first, then check that the enrolled KEK is sbctl's, so the db can be +written without Setup Mode: + +```sh +V=/sys/firmware/efi/efivars; B=/root/secureboot-backup-$(date +%Y%m%d) +doas -n mkdir -p $B +for n in PK-8be4df61-93ca-11d2-aa0d-00e098032b8c KEK-8be4df61-93ca-11d2-aa0d-00e098032b8c \ + db-d719b2cb-3d3a-4596-a3bc-dad00e67656f dbx-d719b2cb-3d3a-4596-a3bc-dad00e67656f; do + doas -n sh -c "cat $V/$n > $B/$n" # cp fails on efivarfs +done +doas -n openssl x509 -in /var/lib/sbctl/keys/KEK/KEK.pem -outform DER | sha256sum | cut -c1-12 +doas -n python3 tools/efi-sig-list.py $V/KEK-8be4df61-93ca-11d2-aa0d-00e098032b8c +``` + +The KEK fingerprint must appear in the script's list. Then: + +```sh +doas -n eac-boot enroll +doas -n python3 tools/efi-sig-list.py $V/db-d719b2cb-3d3a-4596-a3bc-dad00e67656f +``` + +Expected: `7 entries, 7 unique`: Database Key (sbctl), Windows Production PCA +2011, Windows UEFI CA 2023, Microsoft Corporation UEFI CA 2011, Microsoft UEFI +CA 2023, Microsoft Option ROM UEFI CA 2023, CachyOS EAC CA. +`sbctl list-enrolled-keys` prints issuers, so two Microsoft names appear twice +there; that is correct. + +## 3. Normal kernel signature + +```sh +for f in /efi/EFI/Gentoo/*.efi; do doas -n sbverify --list "$f"; done +``` + +Each image needs exactly one signature, issued by the sbctl `Database Key`. +Without it the normal boot stops once Secure Boot is on. Fix by re-emerging the +kernel (secureboot.eclass falls back to `/var/lib/sbctl/keys/db/db.key`). + +## 4. EAC boot entry + +```sh +doas -n eac-boot setup 0201 +efibootmgr | grep -E '^Boot(Order|0201)' +doas -n ls /efi/EFI/cachyos-eac /efi/$(cat /etc/machine-id)/linux-cachyos-eac +eac-boot cmdline +``` + +Expected: `Boot0201* CachyOS EAC` with loader +`\EFI\cachyos-eac\systemd-bootx64.efi`, and `0201` last in BootOrder. +`setup 0201` replaces whatever entry has that number. From now on every update +of the kernel package runs `eac-boot update` itself. + +## 5. Enable Secure Boot (user) + +1. **(user)** Have the BitLocker recovery key ready (aka.ms/myrecoverykey). +2. **(user)** Reboot into the firmware setup and enable Secure Boot. Change + nothing else. +3. Back in Gentoo: `doas -n sbctl status` shows Secure Boot enabled. +4. **(user)** Check that Windows boots. + +## 6. Desktop session + +GPU card numbers differ between the two kernels, so Hyprland must not name +`/dev/dri/cardN`: + +```sh +doas -n install -m644 host/udev/61-dri-igpu.rules /etc/udev/rules.d/ +doas -n udevadm control --reload +doas -n udevadm trigger --subsystem-match=drm --action=change +ls -l /dev/dri/igpu +``` + +In `~/.config/hypr/env.lua`: `hl.env("AQ_DRM_DEVICES", "/dev/dri/igpu")`. + +In `~/.config/hypr/autocmds.lua`, inside `hl.on("hyprland.start", function () ... end)`: + +```lua +hl.exec_cmd("/usr/libexec/hyprpolkitagent") +hl.exec_cmd("/usr/libexec/eac-openrc-compat/systemd-run-agent") +``` + +Start both in the running session without a relogin: + +```sh +hyprctl -i 0 dispatch 'hl.dsp.exec_cmd("/usr/libexec/hyprpolkitagent")' +hyprctl -i 0 dispatch 'hl.dsp.exec_cmd("/usr/libexec/eac-openrc-compat/systemd-run-agent")' +ls -l /run/user/1000/systemd-run-agent.sock +systemd-run --user --wait --pipe cat /proc/self/sessionid # must equal the next line +cat /proc/$(pgrep -x Hyprland)/sessionid +``` + +Polkit check: +`systemd-run --user --wait --pipe pkexec --disable-internal-agent /usr/bin/true`. +**(user)** A password dialog must appear; cancel it. +"No authentication agent found" means hyprpolkitagent is not running. +`pkttyagent` does not work for this. + +## 7. Boot the EAC entry + +```sh +doas -n eac-boot boot # reboots; the ssh session drops +``` + +After the reboot: + +```sh +uname -r # 7.3.5-2-cachyos-eac (or the current version) +doas -n eac-status # every line [ OK ] +cat /proc/sys/kernel/tainted # 0 +``` + +The next normal reboot returns to Gentoo. + +## 8. First game launch (user) + +1. **(user)** Start the Epic Games Launcher (AppImage) and Fortnite. +2. **(user)** Answer "Easy Anti-Cheat service installation required. Install + now?" with Yes and enter the password in the polkit dialog. + +Meanwhile watch `~/.cache/com.epicgames.easyanticheat/service.log` and syslog +(`doas -n grep -E 'systemctl-compat|systemd-run-agent|socket-activate' /var/log/everything/current`). + +Expected: + +``` +Running install with pkexec. +Writing /usr/local/bin/easyanticheat_eos.new. +Running systemctl daemon-reload. +Authorizing user 1000. +Running systemctl start easyanticheat_eos.socket. +Operation succeeded. +``` + +and `/var/lib/easyanticheat_eos/authorizedusers/1000` exists. + +## 9. Start the service at boot + +EAC only runs `systemctl start`; on systemd its `sockets.target.d` drop-in +starts the socket at boot, which OpenRC does not read. Add it to the runlevel: + +```sh +doas -n rc-update add socket-activate.easyanticheat_eos default +rc-service socket-activate.easyanticheat_eos status # started +``` + +## 10. Check a protected game + +After the next launch, `/var/log/socket-activate.easyanticheat_eos.log` shows +`Running service, version ...`, and +`.../AppData/Local/FortniteGame/Saved/Logs/FortniteGame.log` in the Proton +prefix shows `[AntiCheatClient] [BeginSession-...]` when joining a match. + +## Updates + +- **Kernel:** CachyOS removes old versions from its mirror. Bump the ebuild as + described in its README, commit to `febuild`, copy the package into + `overlay/`. `pkg_postinst` runs `eac-boot update`. +- **EAC setup:** EAC updates its service itself. The compatibility layer was + written against setup 0.1.7. If a later setup fails, capture its calls with + `tools/` and compare them with the mapping in the eac-openrc-compat README. + +## Removal + +```sh +pkexec /usr/local/bin/easyanticheat_eos uninstall standalone +doas -n rc-update del socket-activate.easyanticheat_eos default +doas -n efibootmgr -b 0201 -B +doas -n emerge -C sys-apps/eac-openrc-compat sys-kernel/cachyos-eac-kernel-bin +``` + +Then remove `/efi/EFI/cachyos-eac`, `/efi//linux-cachyos-eac` and +`/efi/loader/entries/cachyos-eac.conf`. The unmerge also removed the CA from +`/var/lib/sbctl/keys/custom/db/`; to drop it from the firmware db too, run +`doas -n sbctl enroll-keys --partial db --microsoft --ignore-immutable`. + +## systemd systems + +The compatibility layer exists only because this machine runs OpenRC. On a +systemd system it may work without it (untested): + +- **Gentoo with systemd:** install only `cachyos-eac-kernel-bin` + (`eac-openrc-compat` blocks `sys-apps/systemd`). Follow steps 0-5, 7 and 8, + with any polkit agent in the desktop session. Skip the `systemd-run-agent` + lines in step 6 and all of step 9. +- **Other distributions:** use the distribution's signed kernel if Epic trusts + its key, or CachyOS's own packages and instructions + (wiki.cachyos.org/configuration/easy_anti_cheat). `eac-boot` and the ebuild + are Gentoo-specific. diff --git a/README.md b/README.md new file mode 100644 index 0000000..f682866 --- /dev/null +++ b/README.md @@ -0,0 +1,97 @@ +# Fortnite on Gentoo with OpenRC (EAC Linux v2) + +Easy Anti-Cheat Linux v2 needs two things Gentoo with OpenRC does not have: + +1. **A boot chain signed by a key Epic trusts.** Gentoo has none, so a separate + boot entry runs CachyOS's signed EAC kernel through CachyOS's signed + systemd-boot, with Secure Boot, TPM measurement and `lockdown=integrity`. +2. **systemd for EAC's anti-cheat service.** On the first protected launch, EAC + installs a socket-activated systemd service with `systemd-run`, `pkexec` and + `systemctl`. A small compatibility layer maps those calls to OpenRC. + +This repository holds the two ebuilds, the host configuration, the debugging +tools used to work out the service install, and the documentation. + +**Status (2026-12-03): working** on the author's desktop (Gentoo, OpenRC, +elogind, Hyprland, Intel Raptor Lake + AMD eGPU). EAC accepted the boot, the +service installed itself, and Fortnite ran creative islands with active +anti-cheat sessions. Battle Royale matchmaking is untested. + +## How the pieces fit + +``` +firmware: Secure Boot on, db = own sbctl key + Microsoft certs + CachyOS EAC CA + -> firmware entry "CachyOS EAC": CachyOS-signed systemd-boot (measures into the TPM) + -> CachyOS-signed linux-cachyos-eac + host-built dracut initramfs + cmdline + lockdown=integrity lsm=...,bpf iommu.passthrough=0 intel_iommu=on + module.sig_enforce=1 sysctl.kernel.kexec_load_disabled=1 + -> Hyprland session: hyprpolkitagent + systemd-run-agent (autostarted) + -> Epic Games Launcher -> Proton -> Fortnite + EAC bootstrapper + first launch: EAC setup -> systemd-run --user -> pkexec -> install -> systemctl start + every launch: game connects to @easyanticheat_eos -> service starts, stops after the game +``` + +The normal Gentoo boot stays the default. The EAC entry is last in BootOrder +and is started once with `eac-boot boot` or from the firmware's boot menu. + +## Contents + +| Path | What it is | +| --- | --- | +| [`AGENTS.md`](AGENTS.md) | installation runbook for agents, for the author's machine | +| [`docs/troubleshooting.md`](docs/troubleshooting.md) | error messages and their causes, log locations, debugging tools | +| [`docs/progress.md`](docs/progress.md) | how it got here, decisions, open items | +| `overlay/` | Portage overlay (`repo_name` `eac-gentoo-openrc`) with both packages; snapshot of the author's `febuild` overlay | +| `overlay/sys-kernel/cachyos-eac-kernel-bin/` | CachyOS's EAC kernel, signed systemd-boot, EAC CA and `eac-status`, repackaged byte for byte, plus the `eac-boot` tool. [README](overlay/sys-kernel/cachyos-eac-kernel-bin/files/README.md) | +| `overlay/sys-apps/eac-openrc-compat/` | the systemd compatibility layer for EAC's service on OpenRC. [README](overlay/sys-apps/eac-openrc-compat/files/README.md) | +| `host/udev/61-dri-igpu.rules` | stable `/dev/dri/igpu` name for the iGPU at PCI `0000:00:02.0`; goes to `/etc/udev/rules.d/` | +| `host/portage/package.use/intel-microcode` | `initramfs` USE flag, so dracut puts early microcode into the EAC initramfs; goes to `/etc/portage/package.use/` | +| `tools/` | debugging tools, not installed by anything. [README](tools/README.md) | + +## The two packages + +**`sys-kernel/cachyos-eac-kernel-bin`** installs, unchanged, from +`mirror.cachyos.org/repo/x86_64/cachyos/`: `linux-cachyos-eac` (kernel and +signed modules to `/lib/modules/-cachyos-eac/`), +`systemd-boot-cachyos-signed`, `cachyos-eac-signing-key` and `eac-status` from +`cachyos-settings`. Nothing is stripped or re-signed: a second signature fails +EAC. `eac-boot` enrolls the db, puts kernel, dracut initramfs and systemd-boot on +the ESP, creates the firmware entry and boots it once. + +**`sys-apps/eac-openrc-compat`** provides exactly what EAC's setup +(`EasyAntiCheat_EOS_Setup` 0.1.7) calls: + +| Installed file | Replaces | +| --- | --- | +| `/usr/lib64/libsystemd.so.0` -> `libelogind.so.0` | libsystemd (the setup uses only `sd_listen_fds`, `sd_is_socket_unix`, `sd_notify`) | +| `/usr/bin/systemd-run` + `/usr/libexec/eac-openrc-compat/systemd-run-agent` | `systemd-run --user`: the agent runs commands in the graphical session, outside Proton's no_new_privs sandbox, so `pkexec` works | +| `/usr/bin/systemctl` | `systemctl` for `NAME.socket`/`NAME.service` when the OpenRC service `socket-activate.NAME` exists; other units fail as on a non-systemd host | +| `/usr/libexec/eac-openrc-compat/socket-activate`, `/etc/init.d/socket-activate`, `socket-activate.easyanticheat_eos` | systemd socket activation of `@easyanticheat_eos` | + +It does not pretend that systemd booted the machine: `/run/systemd/system` +stays absent and `sd_booted()` returns 0. + +## systemd distributions + +On a systemd system the compatibility layer is not needed, and it blocks +`sys-apps/systemd`. EAC's setup uses the real `systemd-run`, `systemctl` and +socket activation there. A Gentoo systemd install should work with only +`cachyos-eac-kernel-bin` and a polkit agent in the desktop session (untested). +Other distributions use their own signed kernel or CachyOS's packages directly; +see [AGENTS.md](AGENTS.md#systemd-systems). + +## Safety + +- Never re-sign, strip or `sbctl sign` the CachyOS kernel or systemd-boot. +- Never use `sbctl enroll-keys --append`: it enrolls every key a second time. +- In the firmware, only toggle Secure Boot. "Reset to Setup Mode", "Restore + Factory Keys" and "Clear All Keys" erase the custom db. +- A BitLocker Windows install asks for its recovery key after db or Secure Boot + changes. + +## Maintenance + +The author's `febuild` overlay is canonical for the packages. After changing an +ebuild there, copy the package directory into `overlay/` and commit both. +CachyOS deletes old packages from its mirror; bumping is described in the +[kernel package README](overlay/sys-kernel/cachyos-eac-kernel-bin/files/README.md#bumping). diff --git a/docs/progress.md b/docs/progress.md new file mode 100644 index 0000000..114fd50 --- /dev/null +++ b/docs/progress.md @@ -0,0 +1,60 @@ +# Progress, decisions and open items + +## Timeline (2026) + +- **11-24..26:** first design: EFI-stub boot of the CachyOS kernel with a + hand-made initramfs. Dropped: EAC wants a CachyOS-signed boot manager that + measures into the TPM (systemd-boot). EFI stub, GRUB, Limine, rEFInd and a + self-signed systemd-boot do not pass. +- **11-26/27:** `cachyos-eac-kernel-bin` written and installed. The first emerge + failed in `pkg_postinst` (`depmod -b "${EROOT}"`; `EROOT` is empty under EAPI + 8), fixed with `"${EROOT:-/}"`. Secure Boot db rebuilt: the CachyOS wiki's + `sbctl enroll-keys --append` had enrolled every certificate twice (14 -> 7). + `eac-boot setup 0201`, Secure Boot enabled. +- **11-28:** EAC boot works, `eac-status` passes. Hyprland did not start: on the + EAC kernel the iGPU is driven by i915 and becomes `card1`, the eGPU `card0`, + while `AQ_DRM_DEVICES` named `card0`. Fixed with a udev symlink. Early + microcode added to the initramfs (Gentoo's dracut defaults to + `early_microcode=no`), which cleared the kernel taint. +- **12-02:** Epic released EAC Linux v2 and Fortnite on Linux (beta). +- **12-03:** EAC service install on OpenRC, one failure at a time: + 1. `failed with 127`: the setup could not load `libsystemd.so.0`. + 2. `failed with 13`: `execvp systemd-run` failed. + 3. `failed with 2`: `pkexec auth failed`. `pkttyagent` cannot serve it, and + hyprpolkitagent crashed on a stale live-ebuild SONAME (hyprtoolkit). + 4. 15:44: install succeeded with `sys-apps/eac-openrc-compat`; Fortnite + reached the lobby and ran creative islands with EAC sessions active. + +## Decisions + +- **Repackage, never rebuild.** EAC only trusts signatures from keys on Epic's + list; a locally built kernel would carry the user's key. CachyOS's kernel, + modules and systemd-boot are installed byte for byte (`RESTRICT="mirror + strip"`, no installkernel, no secureboot eclass). +- **Separate firmware entry.** CachyOS's systemd-boot lives in + `EFI/cachyos-eac/` with its own entry at the end of BootOrder; Epic allows a + separate boot entry for protected games. The normal boot is unchanged. +- **Keep the user's db key.** The normal kernel is signed with it; Epic's rule + covers only the keys that verify the protected boot session. +- **dracut** for the initramfs: the CachyOS kernel has storage and filesystem + drivers as modules. +- **Compatibility layer, not systemd.** Only what the setup calls is provided; + everything else answers like a non-systemd host, so other software is not + misled into thinking systemd runs. +- **`systemd-run --user` through a session agent.** Proton sets no_new_privs, + which pkexec refuses. The agent starts commands from the Hyprland session, + outside that process tree and in the same elogind session as the polkit + agent. An `openrc --user` service would run in a background session where + polkit finds no agent. +- **Captured, not redistributed.** The EAC setup binary is Epic's; this + repository only documents what it calls. + +## Open items + +- `socket-activate.easyanticheat_eos` must be added to the default runlevel by + hand after the first install (AGENTS.md step 9). The `systemctl` shim could + map EAC's `sockets.target.d` drop-in to `rc-update add` on `daemon-reload`. +- Battle Royale matchmaking untested. +- The layer matches EAC setup 0.1.7; a later setup may call something new. +- CachyOS is not on Epic's published key list from October; Epic accepted the + CachyOS EAC CA in practice (12-02/03). diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md new file mode 100644 index 0000000..606972e --- /dev/null +++ b/docs/troubleshooting.md @@ -0,0 +1,66 @@ +# Troubleshooting + +## Logs + +| Log | Path | +| --- | --- | +| EAC bootstrapper (UTC times) | `~/.local/share/com.epicgames.eglv2/compat/compatdata/Fortnite/pfx/drive_c/users/steamuser/AppData/Roaming/EasyAntiCheat/prod-fn//anticheatlauncher.log` | +| EAC setup (Linux side) | `~/.cache/com.epicgames.easyanticheat/service.log` | +| EAC service | `/var/log/socket-activate.easyanticheat_eos.log` | +| Compatibility layer | syslog tags `systemctl-compat`, `systemd-run-agent`, `socket-activate.easyanticheat_eos` (`/var/log/everything/current`) | +| Fortnite | `.../pfx/drive_c/users/steamuser/AppData/Local/FortniteGame/Saved/Logs/` | +| Hyprland | `$XDG_RUNTIME_DIR/hypr/*/hyprland.log`, gone after a reboot | + +`Roaming/EasyAntiCheat/service.log` in the Proton prefix is from the Windows +installer and does not matter here. + +## EAC service installation + +The bootstrapper reports `Launcher finished with: 209, 'Easy Anti-Cheat service +installation failed with N'`. The setup's `service.log` says why: + +| N | `service.log` | Cause | Fix | +| --- | --- | --- | --- | +| 127 | no new lines | the setup cannot load `libsystemd.so.0` | `sys-apps/eac-openrc-compat` (links it to libelogind) | +| 13 | `execvp systemd-run failed with No such file or directory` | no `systemd-run` | `sys-apps/eac-openrc-compat` | +| 13 | `systemd-run exited with code 1` | `systemd-run-agent` not running in the session | start it (AGENTS.md step 6) | +| 2 | `Running install with pkexec.` then `pkexec auth failed.` in the same second | no polkit agent registered for the session | run hyprpolkitagent; `pkttyagent` registers only for its own parent shell and cannot serve the setup | +| 2 | `pkexec request dismissed.` | the dialog was cancelled | launch again | + +Polkit check from the session without a terminal: +`systemd-run --user --wait --pipe pkexec --disable-internal-agent /usr/bin/true`. +"No authentication agent found" means no agent; with an agent a dialog appears. + +## Service + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Works once, fails after a reboot | `socket-activate.easyanticheat_eos` not in the runlevel | `rc-update add socket-activate.easyanticheat_eos default` | +| Service log prints the setup's usage text and exits 1 | `EAC_MODE_SERVICE=1` missing | check `socket_env` in `/etc/conf.d/socket-activate.easyanticheat_eos` | +| `systemd did not pass exactly the socket '@easyanticheat_eos'` | started without socket activation | start it only through the OpenRC service | +| `User 1000 not found in /var/lib/easyanticheat_eos/authorizedusers` | user not authorized | `pkexec /usr/local/bin/easyanticheat_eos authorizeuser --uid=1000` | +| `/usr/local/bin/easyanticheat_eos is not installed` from the OpenRC service | EAC has not installed itself yet | launch the game once | + +## Boot and session + +| Symptom | Cause | Fix | +| --- | --- | --- | +| Secure Boot violation on the EAC entry | CA not in db, or a file was re-signed | `eac-boot enroll`; re-emerge the kernel package | +| `eac-status`: two signatures | something re-signed the kernel or systemd-boot | re-emerge `cachyos-eac-kernel-bin`, `eac-boot update` | +| Root filesystem not found | initramfs built for another kernel | `eac-boot update` | +| Hyprland does not start in the EAC boot | `AQ_DRM_DEVICES` names `/dev/dri/cardN`; card numbers differ per kernel | `host/udev/61-dri-igpu.rules` and `/dev/dri/igpu` | +| `/proc/sys/kernel/tainted` not 0, `Running old microcode` | no early microcode in the initramfs | `sys-firmware/intel-microcode[initramfs]`, `eac-boot update`, reboot | +| `module verification failed` | an out-of-tree module (bcachefs, kvmfr) | not available in the EAC boot | +| hyprpolkitagent: `libaquamarine.so.N`, `libhyprtoolkit.so.N: cannot open shared object file` | a live Hyprland library changed its SONAME | find the stale package with `readelf -d` over `ldd`'s libraries, `emerge -1` it and its users | +| Entry missing from the F12 menu | entry not in BootOrder | `eac-boot setup 0201` | + +Lockdown also blocks MSR writes (undervolting), `/dev/mem` and hibernation in +the EAC boot. + +## Capturing what a new EAC setup does + +If an EAC update changes what the setup calls, record the next first launch +with the tools in `../tools/` (see its README): `exec-snoop` for every exec +attempt with its arguments, `eac-catch` to keep the setup binary before EAC +deletes it, then `strings` on the binary for the commands and unit files it +contains. diff --git a/host/portage/package.use/intel-microcode b/host/portage/package.use/intel-microcode new file mode 100644 index 0000000..82f049b --- /dev/null +++ b/host/portage/package.use/intel-microcode @@ -0,0 +1 @@ +sys-firmware/intel-microcode initramfs diff --git a/host/udev/61-dri-igpu.rules b/host/udev/61-dri-igpu.rules new file mode 100644 index 0000000..b031220 --- /dev/null +++ b/host/udev/61-dri-igpu.rules @@ -0,0 +1 @@ +SUBSYSTEM=="drm", KERNEL=="card*", KERNELS=="0000:00:02.0", SUBSYSTEMS=="pci", SYMLINK+="dri/igpu" diff --git a/overlay/metadata/layout.conf b/overlay/metadata/layout.conf new file mode 100644 index 0000000..20fcfea --- /dev/null +++ b/overlay/metadata/layout.conf @@ -0,0 +1,3 @@ +masters = gentoo +thin-manifests = true +sign-manifests = false diff --git a/overlay/profiles/repo_name b/overlay/profiles/repo_name new file mode 100644 index 0000000..3690173 --- /dev/null +++ b/overlay/profiles/repo_name @@ -0,0 +1 @@ +eac-gentoo-openrc diff --git a/overlay/sys-apps/eac-openrc-compat/eac-openrc-compat-0.1-r1.ebuild b/overlay/sys-apps/eac-openrc-compat/eac-openrc-compat-0.1-r1.ebuild new file mode 100644 index 0000000..26a9e5e --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/eac-openrc-compat-0.1-r1.ebuild @@ -0,0 +1,48 @@ +# Copyright 2026 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=8 + +PYTHON_COMPAT=( python3_{13..14} ) + +inherit python-single-r1 + +DESCRIPTION="systemctl, systemd-run and socket activation for the EAC Linux v2 service on OpenRC" +HOMEPAGE="https://easy.ac" +S="${WORKDIR}" + +LICENSE="MIT" +SLOT="0" +KEYWORDS="~amd64" +REQUIRED_USE="${PYTHON_REQUIRED_USE}" + +RDEPEND=" + ${PYTHON_DEPS} + !sys-apps/systemd + sys-apps/openrc + sys-apps/util-linux + sys-auth/elogind + sys-auth/polkit +" + +src_install() { + dobin "${FILESDIR}"/systemctl "${FILESDIR}"/systemd-run + exeinto /usr/libexec/${PN} + doexe "${FILESDIR}"/systemd-run-agent "${FILESDIR}"/socket-activate + python_fix_shebang "${ED}"/usr/bin/systemd-run "${ED}"/usr/libexec/${PN} + + newinitd "${FILESDIR}"/socket-activate.initd socket-activate + dosym socket-activate /etc/init.d/socket-activate.easyanticheat_eos + newconfd "${FILESDIR}"/easyanticheat_eos.confd socket-activate.easyanticheat_eos + + # EAC's helper links libsystemd.so.0; elogind exports the same LIBSYSTEMD_* symbol versions. + dosym libelogind.so.0 /usr/$(get_libdir)/libsystemd.so.0 + + dodoc "${FILESDIR}"/README.md +} + +pkg_postinst() { + elog "Start ${EPREFIX}/usr/libexec/${PN}/systemd-run-agent from your compositor's autostart," + elog "and run a session-wide polkit authentication agent there (not pkttyagent)." + elog "Details: ${EROOT}/usr/share/doc/${PF}/README.md*" +} diff --git a/overlay/sys-apps/eac-openrc-compat/files/README.md b/overlay/sys-apps/eac-openrc-compat/files/README.md new file mode 100644 index 0000000..439596b --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/README.md @@ -0,0 +1,80 @@ +# eac-openrc-compat + +Lets the Easy Anti-Cheat Linux v2 setup install and run its service on an +OpenRC host. It provides only what the setup (`EasyAntiCheat_EOS_Setup`, 0.1.7) +calls; nothing here talks to systemd or pretends a systemd boot to other +software (`/run/systemd/system` stays absent, `sd_booted()` returns 0). + +## What the EAC setup does + +On the first protected launch the game writes the setup to +`/tmp/EasyAntiCheat_EOS_Setup.XXXXXX/` and runs `verify-and-install `: + +1. Proton has set no_new_privs, so the setup re-runs itself with + `systemd-run --user --wait --pipe --collect --quiet --setenv=... ...`. +2. Outside Proton it runs `pkexec install ` (polkit prompt). +3. As root it writes `/usr/local/bin/easyanticheat_eos`, + `/usr/lib/systemd/system/easyanticheat_eos.{socket,service}`, + `/var/lib/easyanticheat_eos/` (state, `authorizedusers/`), then runs + `systemctl --version` (needs systemd >= 249), `daemon-reload`, + `enable --quiet easyanticheat_eos.socket` and `start`. +4. The game connects to the abstract socket `@easyanticheat_eos`; the service + starts with that socket (`LISTEN_FDS`) and `EAC_MODE_SERVICE=1`, and stops + when the game exits. + +Logs: `~/.cache/com.epicgames.easyanticheat/service.log` (setup), +`/var/log/socket-activate.easyanticheat_eos.log` (service), syslog tags +`systemctl-compat` and `systemd-run-agent`. + +## Files + +| File | Role | +| --- | --- | +| `/usr/lib64/libsystemd.so.0` | link to elogind's library, which exports the same `LIBSYSTEMD_*` symbols the setup uses (`sd_listen_fds`, `sd_is_socket_unix`, `sd_notify`) | +| `/usr/bin/systemd-run` | the `--user` form only, forwarded to `systemd-run-agent`; anything else fails as on a host without a user manager | +| `/usr/libexec/eac-openrc-compat/systemd-run-agent` | runs those commands in the graphical session, with the session's environment, outside the caller's process tree | +| `/usr/bin/systemctl` | units `NAME.socket`/`NAME.service` map to the OpenRC service `socket-activate.NAME` when it exists; other units fail as on a host not booted with systemd | +| `/usr/libexec/eac-openrc-compat/socket-activate` | `socket-activate [-n] {stream\|seqpacket} ADDRESS COMMAND [ARGS...]`: listens on ADDRESS (`@NAME` = abstract) and starts COMMAND with the socket as fd 3 for each burst of connections, like `Accept=no` | +| `/etc/init.d/socket-activate` | OpenRC service family; instances are links `socket-activate.NAME` | +| `/etc/conf.d/socket-activate.easyanticheat_eos` | the EAC instance | + +## Instance settings (`/etc/conf.d/socket-activate.NAME`) + +| Variable | Meaning | +| --- | --- | +| `socket_type` | `stream` (default) or `seqpacket` | +| `socket_address` | `@NAME` for an abstract socket, else a path | +| `socket_nonblocking` | `yes`: O_NONBLOCK on the socket (systemd `NonBlocking=yes`) | +| `socket_command` | the service binary and its arguments | +| `socket_env` | space-separated `KEY=VALUE` pairs for the service | + +## systemctl mapping + +| systemctl | OpenRC | +| --- | --- | +| `--version` | prints `systemd 257` | +| `daemon-reload`, `reset-failed` | nothing | +| `start` | `rc-service -N socket-activate.NAME start` | +| `stop NAME.service` | restarts the listener, which ends the running service; the socket keeps listening | +| `stop NAME.socket`, `stop NAME.*` | `rc-service -s ... stop` | +| `restart` | `rc-service ... restart` | +| `enable [--now]`, `disable [--now]` | `rc-update add/del ... default` | +| `is-enabled` | `enabled`/`disabled` from the default runlevel; `static` for a `.service` | +| `is-active`, `status` | `rc-service ... status` | + +## Setup + +1. Start the agent in the graphical session, e.g. Hyprland: + `hl.exec_cmd("/usr/libexec/eac-openrc-compat/systemd-run-agent")`. +2. Run a session-wide polkit authentication agent in that session + (hyprpolkitagent, polkit-gnome, lxqt-policykit, ...). `pkttyagent` does not + work: without `--process` it registers only for its parent shell, so polkit + finds no agent for the setup and pkexec fails at once ("pkexec auth failed" + in the setup's log). Check with + `systemd-run --user --wait --pipe pkexec --disable-internal-agent /usr/bin/true`: + "No authentication agent found" means none is registered for the session. +3. Launch the game and accept the service installation. The setup enables + `socket-activate.easyanticheat_eos` in the default runlevel itself. + +Remove EAC's files again with `pkexec /usr/local/bin/easyanticheat_eos +uninstall standalone`, then `rc-update del socket-activate.easyanticheat_eos`. diff --git a/overlay/sys-apps/eac-openrc-compat/files/easyanticheat_eos.confd b/overlay/sys-apps/eac-openrc-compat/files/easyanticheat_eos.confd new file mode 100644 index 0000000..1f8ee67 --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/easyanticheat_eos.confd @@ -0,0 +1,5 @@ +socket_type="seqpacket" +socket_address="@easyanticheat_eos" +socket_nonblocking="yes" +socket_command="/usr/local/bin/easyanticheat_eos" +socket_env="EAC_MODE_SERVICE=1" diff --git a/overlay/sys-apps/eac-openrc-compat/files/socket-activate b/overlay/sys-apps/eac-openrc-compat/files/socket-activate new file mode 100755 index 0000000..45fd6f6 --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/socket-activate @@ -0,0 +1,63 @@ +#!/usr/bin/python3 -I +"""Socket activation without systemd, like a .socket unit with Accept=no. + +Usage: socket-activate [-n] {stream|seqpacket} ADDRESS COMMAND [ARGS...] +ADDRESS is @NAME for an abstract Unix socket, else a filesystem path. When a client connects, +COMMAND starts with the listening socket as fd 3, LISTEN_FDS=1 and LISTEN_PID; after it exits +the next connection starts it again. -n sets O_NONBLOCK on the socket (NonBlocking=yes). +SIGTERM is passed on to a running COMMAND. +""" +import os +import select +import signal +import socket +import sys +import time + +args = sys.argv[1:] +nonblocking = args[:1] == ["-n"] +if nonblocking: + args = args[1:] +kind, address, cmd = args[0], args[1], args[2:] +sock = socket.socket(socket.AF_UNIX, {"stream": socket.SOCK_STREAM, "seqpacket": socket.SOCK_SEQPACKET}[kind]) +if address.startswith("@"): + sock.bind("\0" + address[1:]) +else: + if os.path.exists(address): + os.unlink(address) + sock.bind(address) +sock.listen(128) +sock.setblocking(not nonblocking) +child = 0 + + +def stop(signum, _): + if child: + os.kill(child, signal.SIGTERM) + os.waitpid(child, 0) + sys.exit(0) + + +signal.signal(signal.SIGTERM, stop) +signal.signal(signal.SIGINT, stop) +print(f"listening on {address}", file=sys.stderr, flush=True) +while True: + select.select([sock], [], []) + child = os.fork() + if child == 0: + os.dup2(sock.fileno(), 3) + os.set_inheritable(3, True) + os.environ.update(LISTEN_FDS="1", LISTEN_PID=str(os.getpid())) + os.environ.pop("LISTEN_FDNAMES", None) + try: + os.execvp(cmd[0], cmd) + finally: + os._exit(127) + started = time.monotonic() + print(f"started {cmd[0]} as pid {child}", file=sys.stderr, flush=True) + _, status = os.waitpid(child, 0) + child = 0 + print(f"{cmd[0]} exited with {os.waitstatus_to_exitcode(status)}", file=sys.stderr, flush=True) + # ponytail: fixed 1 s pause after a quick exit instead of systemd's StartLimitBurst accounting + if time.monotonic() - started < 1: + time.sleep(1) diff --git a/overlay/sys-apps/eac-openrc-compat/files/socket-activate.initd b/overlay/sys-apps/eac-openrc-compat/files/socket-activate.initd new file mode 100644 index 0000000..b14961d --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/socket-activate.initd @@ -0,0 +1,32 @@ +#!/sbin/openrc-run +# Instances: socket-activate.NAME -> socket-activate, settings in conf.d/socket-activate.NAME. + +description="Starts a service when a client connects to its socket (systemd socket activation)" +supervisor=supervise-daemon +command=/usr/libexec/eac-openrc-compat/socket-activate +command_args="${socket_type:-stream} ${socket_address} ${socket_command}" +[ "${socket_nonblocking}" = yes ] && command_args="-n ${command_args}" +output_log="/var/log/${RC_SVCNAME}.log" +error_log="/var/log/${RC_SVCNAME}.log" +retry="TERM/15/KILL/5" +respawn_max=5 +respawn_period=60 + +depend() { + need localmount + after bootmisc +} + +start_pre() { + if [ "${RC_SVCNAME}" = socket-activate ]; then + eerror "Start an instance: socket-activate.NAME" + return 1 + fi + if [ ! -x "${socket_command%% *}" ]; then + eerror "${socket_command%% *} is not installed" + return 1 + fi + for kv in ${socket_env}; do + export "${kv}" + done +} diff --git a/overlay/sys-apps/eac-openrc-compat/files/systemctl b/overlay/sys-apps/eac-openrc-compat/files/systemctl new file mode 100755 index 0000000..8fa45a7 --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/systemctl @@ -0,0 +1,65 @@ +#!/bin/bash +# systemctl for OpenRC hosts (eac-openrc-compat). A unit NAME.socket or NAME.service is handled +# when the OpenRC service socket-activate.NAME exists; everything else fails as on a host that +# was not booted with systemd. Every call is logged to syslog. + +logger -t systemctl-compat -- "uid=$EUID: $*" 2>/dev/null + +nosystemd() { + echo "System has not been booted with systemd as init system (PID 1). Can't operate." >&2 + echo "Failed to connect to system scope bus via local transport: Host is down" >&2 + exit 1 +} + +cmd= now= quiet= units=() +for a; do + case $a in + --version) echo "systemd 257 (257-eac-openrc-compat)"; exit 0 ;; + --now) now=1 ;; + -q|--quiet) quiet=1 ;; + --system|--no-block|--no-pager|--no-reload|--no-ask-password|--full|-l) ;; + -*) nosystemd ;; + *) if [[ -z $cmd ]]; then cmd=$a; else units+=("$a"); fi ;; + esac +done + +case $cmd in + daemon-reload|daemon-reexec) exit 0 ;; + '') nosystemd ;; +esac + +svc= kinds=() +for u in "${units[@]}"; do + [[ $u == *.* ]] || u+=.service + s=socket-activate.${u%.*} + [[ -e /etc/init.d/$s && ( -z $svc || $svc == "$s" ) ]] || nosystemd + svc=$s + kinds+=("${u##*.}") +done +[[ -n $svc ]] || nosystemd +only_service=1 +for k in "${kinds[@]}"; do [[ $k == service ]] || only_service=; done + +out() { [[ -n $quiet ]] || echo "$@"; } +rc() { if [[ -n $quiet ]]; then rc-service "$@" >/dev/null; else rc-service "$@"; fi; } + +case $cmd in + start) rc -N "$svc" start ;; + restart|try-restart|reload-or-restart) rc "$svc" restart ;; + # Stopping only the service keeps the socket listening: restart the listener, which ends its child. + stop) if [[ -n $only_service ]]; then rc -s "$svc" restart; else rc -s "$svc" stop; fi ;; + reset-failed) exit 0 ;; + enable) + rc-update add "$svc" default >/dev/null || exit + [[ -z $now ]] || rc -N "$svc" start ;; + disable) + rc-update del "$svc" default >/dev/null 2>&1 + [[ -z $now ]] || rc -s "$svc" stop ;; + is-enabled) + if [[ -n $only_service ]]; then out static; exit 0; fi + if rc-update show default | grep -qwF "$svc"; then out enabled; else out disabled; exit 1; fi ;; + is-active) + if rc-service "$svc" status >/dev/null 2>&1; then out active; else out inactive; exit 3; fi ;; + status) rc-service "$svc" status ;; + *) echo "systemctl (eac-openrc-compat): '$cmd' is not supported." >&2; exit 1 ;; +esac diff --git a/overlay/sys-apps/eac-openrc-compat/files/systemd-run b/overlay/sys-apps/eac-openrc-compat/files/systemd-run new file mode 100755 index 0000000..8eb0202 --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/systemd-run @@ -0,0 +1,69 @@ +#!/usr/bin/python3 -I +"""systemd-run for OpenRC hosts: the `--user` form, forwarded to systemd-run-agent. + +The agent runs in the graphical session and takes the place of the systemd user manager: the +command runs with the agent's environment plus --setenv values, outside the caller's process +tree, so a caller's no_new_privs (Proton) does not apply to it. + +Supported: --user, --wait, --pipe/-P, --setenv/-E, --same-dir/-d, --working-directory; accepted +and ignored: --collect/-G, --quiet/-q, --unit/-u, --description, --property/-p. Anything else +fails as systemd-run does on a host without a user manager. +""" +import json +import os +import socket +import sys + +VALUE = {"-E", "--setenv", "-u", "--unit", "--description", "-p", "--property", "--working-directory"} +IGNORED = {"-G", "--collect", "-q", "--quiet", "-u", "--unit", "--description", "-p", "--property"} + + +def fail(msg): + print(msg, file=sys.stderr) + sys.exit(1) + + +args = sys.argv[1:] +user = wait = pipe = False +env, cwd, i = {}, None, 0 +while i < len(args) and args[i].startswith("-"): + arg = args[i] + i += 1 + if arg == "--": + break + opt, eq, val = arg.partition("=") + if opt in VALUE and not eq: + if i == len(args): + fail(f"Option '{opt}' requires an argument.") + val, i = args[i], i + 1 + if opt == "--user": + user = True + elif opt == "--wait": + wait = True + elif opt in ("-P", "--pipe"): + pipe = True + elif opt in ("-E", "--setenv"): + key, has, value = val.partition("=") + env[key] = value if has else os.environ.get(key, "") + elif opt in ("-d", "--same-dir"): + cwd = os.getcwd() + elif opt == "--working-directory": + cwd = val + elif opt not in IGNORED: + fail(f"systemd-run (eac-openrc-compat): unsupported option '{arg}'.") +cmd = args[i:] +if not user: + fail("System has not been booted with systemd as init system (PID 1). Can't operate.") +if not cmd: + fail("Command line to execute required.") + +runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" +sock = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) +try: + sock.connect(os.path.join(runtime, "systemd-run-agent.sock")) +except OSError as e: + fail(f"Failed to connect to user scope bus: systemd-run-agent is not running ({e.strerror}).") +request = json.dumps({"argv": cmd, "env": env, "cwd": cwd, "wait": wait}).encode() +socket.send_fds(sock, [request], [0, 1, 2] if pipe else []) +reply = sock.recv(65536) +sys.exit(json.loads(reply)["status"] if reply else 1) diff --git a/overlay/sys-apps/eac-openrc-compat/files/systemd-run-agent b/overlay/sys-apps/eac-openrc-compat/files/systemd-run-agent new file mode 100755 index 0000000..897d3da --- /dev/null +++ b/overlay/sys-apps/eac-openrc-compat/files/systemd-run-agent @@ -0,0 +1,67 @@ +#!/usr/bin/python3 -I +"""Runs commands for systemd-run (eac-openrc-compat) in the graphical session. + +Start it once per session, from the compositor's autostart. Each request comes from the +systemd-run in /usr/bin over $XDG_RUNTIME_DIR/systemd-run-agent.sock; only the agent's own user +may connect. The command gets the agent's environment plus the request's --setenv values and, with +--pipe, the caller's stdin/stdout/stderr. Every run is logged to syslog. +""" +import json +import os +import socket +import struct +import subprocess +import syslog +import threading + +runtime = os.environ.get("XDG_RUNTIME_DIR") or f"/run/user/{os.getuid()}" +path = os.path.join(runtime, "systemd-run-agent.sock") +syslog.openlog("systemd-run-agent") + + +def exit_status(code): + return code if code >= 0 else 128 - code + + +def serve(conn): + with conn: + uid = struct.unpack("3i", conn.getsockopt(socket.SOL_SOCKET, socket.SO_PEERCRED, 12))[1] + if uid != os.getuid(): + return + data, fds, _, _ = socket.recv_fds(conn, 1 << 20, 3) + if not data: + return + req = json.loads(data) + stdio = fds if len(fds) == 3 else [subprocess.DEVNULL, None, None] + try: + proc = subprocess.Popen(req["argv"], stdin=stdio[0], stdout=stdio[1], stderr=stdio[2], + env=dict(os.environ, **req["env"]), start_new_session=True, + cwd=req["cwd"] or os.path.expanduser("~")) + except OSError as e: + syslog.syslog(f"{req['argv'][0]}: {e.strerror}") + conn.send(json.dumps({"status": 127}).encode()) + return + finally: + for fd in fds: + os.close(fd) + syslog.syslog(f"pid {proc.pid}: {' '.join(req['argv'])}") + if not req["wait"]: + conn.send(json.dumps({"status": 0}).encode()) + status = exit_status(proc.wait()) + syslog.syslog(f"pid {proc.pid} exited with {status}") + if req["wait"]: + conn.send(json.dumps({"status": status}).encode()) + + +probe = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) +if probe.connect_ex(path) == 0: + raise SystemExit("systemd-run-agent is already running") +if os.path.exists(path): + os.unlink(path) +server = socket.socket(socket.AF_UNIX, socket.SOCK_SEQPACKET) +server.bind(path) +server.listen(16) +syslog.syslog(f"listening on {path}") +while True: + conn, _ = server.accept() + threading.Thread(target=serve, args=(conn,), daemon=True).start() diff --git a/overlay/sys-kernel/cachyos-eac-kernel-bin/Manifest b/overlay/sys-kernel/cachyos-eac-kernel-bin/Manifest new file mode 100644 index 0000000..ab624ec --- /dev/null +++ b/overlay/sys-kernel/cachyos-eac-kernel-bin/Manifest @@ -0,0 +1,4 @@ +DIST cachyos-eac-signing-key-1-2-any.pkg.tar.zst 25931 BLAKE2B 7a333eb9b1988b334fcf7f14a7ef089fd81ae71f09a0954290ff63e8ff443c65ee21f1f3a8355d449aa1c92cdc4d8522bc24bc58c68962e0209f0e31493078b7 SHA512 061964faa8bb41b489a77bfa3b38ab56484d4e34578ecbfe8d184f3ee84acf0de5ffb59423f06fe02a55f4fc85ab08b368e32843186432f36a19426197ee993e +DIST cachyos-settings-1.4.5-1-any.pkg.tar.zst 34054 BLAKE2B 1dd6b77c8367c2813fa8b946cba19f0ebba4f9597d629e46b3cbfffbc86cb92ea08ec0ad058a92422818e2cdbf919276e97b8edd211a5132d679e71d0653131d SHA512 d6cbfac39f3b4648e8a3bca5eda3311db8600d9118ab2a6099d3a5da11168d285963797ff1cbb6a8f9b35b2d7f3c8970502c276454c5ab40214de7894f229c0b +DIST linux-cachyos-eac-7.3.5-2-x86_64.pkg.tar.zst 160513377 BLAKE2B bc19c6888b913c0175131dd5cb67029e36ad5016b13679b7f3d3c2ffd5f40c5a1f2ebf51916595baa530e6e48c92e693966ba759fe9b4e35b7a89e367e806575 SHA512 8819db16f28301f9a1908e2a53383fa512e93f1b799485c0e9650562e9fd6be4988a9d90a9a3581a06c159990aef694d8264594927fbea071cb835f99fb6c794 +DIST systemd-boot-cachyos-signed-262.2_1-1-x86_64.pkg.tar.zst 103982 BLAKE2B 132ec57dd05133a24f306f33728f61cb283bf3fb26d1b0e6fad6e8b10cabb2eefdf695a9bbcdaf4ca7dcfd07193582c9fb874401e85adfb2161cfe5eed0b1dda SHA512 7d56f609e5b7d17d8560c047041a7b347a040f5632ad99e136ebd78b5098b5f9083c2c39dc13ef420c853c23f50a6aa2a54dceb9ad69c38fc99fdbce4a2b2534 diff --git a/overlay/sys-kernel/cachyos-eac-kernel-bin/cachyos-eac-kernel-bin-7.3.5_p2-r2.ebuild b/overlay/sys-kernel/cachyos-eac-kernel-bin/cachyos-eac-kernel-bin-7.3.5_p2-r2.ebuild new file mode 100755 index 0000000..b7d335d --- /dev/null +++ b/overlay/sys-kernel/cachyos-eac-kernel-bin/cachyos-eac-kernel-bin-7.3.5_p2-r2.ebuild @@ -0,0 +1,87 @@ +# Copyright 2026 Gentoo Authors +# Distributed under the terms of the GNU General Public License v2 + +EAPI=8 + +MY_PV=${PV/_p/-} +MY_KV=${MY_PV}-cachyos-eac +SDBOOT_PV=262.2_1-1 +KEY_PV=1-2 +SETTINGS_PV=1.4.5-1 +MIRROR=https://mirror.cachyos.org/repo/x86_64/cachyos + +DESCRIPTION="CachyOS-signed kernel and systemd-boot for Easy Anti-Cheat Linux v2" +HOMEPAGE="https://wiki.cachyos.org/configuration/easy_anti_cheat/" +SRC_URI=" + ${MIRROR}/linux-cachyos-eac-${MY_PV}-x86_64.pkg.tar.zst + ${MIRROR}/systemd-boot-cachyos-signed-${SDBOOT_PV}-x86_64.pkg.tar.zst + ${MIRROR}/cachyos-eac-signing-key-${KEY_PV}-any.pkg.tar.zst + ${MIRROR}/cachyos-settings-1%3A${SETTINGS_PV}-any.pkg.tar.zst + -> cachyos-settings-${SETTINGS_PV}-any.pkg.tar.zst +" +S=${WORKDIR} + +LICENSE="GPL-2 LGPL-2.1+ GPL-3+ GPL-1" +SLOT="0" +KEYWORDS="~amd64" +# Stripping or re-signing anything here breaks the CachyOS signatures EAC checks. +RESTRICT="mirror strip" + +RDEPEND=" + app-crypt/sbctl + app-crypt/sbsigntools + app-crypt/tpm2-tools + dev-libs/openssl + sys-apps/kmod[zstd] + sys-boot/efibootmgr + sys-kernel/dracut +" +BDEPEND="app-arch/zstd" + +src_unpack() { + local f + for f in ${A}; do + tar -xf "${DISTDIR}/${f}" || die "unpacking ${f} failed" + done +} + +src_prepare() { + default + sed -i 's#esp=$(bootctl --print-esp-path 2>/dev/null || echo /boot)#esp=$(eac-boot esp)#' \ + usr/bin/eac-status || die + grep -q 'esp=$(eac-boot esp)' usr/bin/eac-status || die "eac-status: ESP patch did not apply" +} + +src_install() { + dodir /lib/modules + cp -a "usr/lib/modules/${MY_KV}" "${ED}/lib/modules/" || die + fowners -R root:root "/lib/modules/${MY_KV}" + + insinto /usr/lib/cachyos-eac + doins usr/lib/systemd/boot/efi/systemd-bootx64.efi.signed + + insinto /usr/share/cachyos-eac + doins usr/share/cachyos-eac/cachyos-eac-ca.{crt,der} + insinto /var/lib/sbctl/keys/custom/db + doins var/lib/sbctl/keys/custom/db/cachyos-eac-ca.der + + dosbin usr/bin/eac-status "${FILESDIR}"/eac-boot + dodoc "${FILESDIR}"/README.md +} + +pkg_postinst() { + depmod -b "${EROOT:-/}" "${MY_KV}" || die + + if [[ -z ${ROOT} && -d $(eac-boot esp 2>/dev/null)/EFI/cachyos-eac ]]; then + eac-boot update || ewarn "eac-boot update failed, run it by hand" + else + elog "First-time setup: eac-boot enroll, eac-boot setup, then enable Secure Boot." + elog "Boot it with eac-boot boot and check it with eac-status." + elog "Details: README in ${EROOT}/usr/share/doc/${PF}/" + fi +} + +pkg_postrm() { + # depmod output is not owned by the package + [[ -d ${EROOT}/lib/modules/${MY_KV}/kernel ]] || rm -rf "${EROOT}/lib/modules/${MY_KV}" +} diff --git a/overlay/sys-kernel/cachyos-eac-kernel-bin/files/README.md b/overlay/sys-kernel/cachyos-eac-kernel-bin/files/README.md new file mode 100644 index 0000000..62c544a --- /dev/null +++ b/overlay/sys-kernel/cachyos-eac-kernel-bin/files/README.md @@ -0,0 +1,73 @@ +# cachyos-eac-kernel-bin + +Repackages the CachyOS Easy Anti-Cheat Linux v2 boot chain unchanged: + +| From CachyOS | Installed to | +|---|---| +| `linux-cachyos-eac` (kernel + signed modules) | `/lib/modules/-cachyos-eac/` (kernel at `vmlinuz`) | +| `systemd-boot-cachyos-signed` | `/usr/lib/cachyos-eac/systemd-bootx64.efi.signed` | +| `cachyos-eac-signing-key` (CachyOS EAC CA) | `/usr/share/cachyos-eac/`, `/var/lib/sbctl/keys/custom/db/` | +| `eac-status` from `cachyos-settings` | `/usr/sbin/eac-status` (ESP lookup patched to `eac-boot esp`) | + +The kernel is not handled by installkernel or uefi-mkconfig, and nothing is +re-signed. A second signature, or a kernel started without the CachyOS-signed +systemd-boot, fails the EAC checks. + +## eac-boot + +| Command | Does | +|---|---| +| `eac-boot enroll` | rewrites the Secure Boot db as: your sbctl db key, the Microsoft certificates, the CachyOS EAC CA | +| `eac-boot setup [bootnum]` | `update`, then creates the `CachyOS EAC` firmware entry and puts it at the end of BootOrder; `bootnum` (4 hex digits) replaces the entry with that number | +| `eac-boot update` | dracut initramfs, kernel and systemd-boot to the ESP, writes the loader entry | +| `eac-boot boot` | sets BootNext to the EAC entry and reboots | +| `eac-boot cmdline` | prints the EAC entry's kernel command line | +| `eac-boot esp` | prints the ESP mount point | + +ESP layout (same as CachyOS with Limine, which `eac-status` checks): + +``` +//linux-cachyos-eac/{vmlinuz,initramfs} +/EFI/cachyos-eac/systemd-bootx64.efi +/loader/loader.conf +/loader/entries/cachyos-eac.conf +``` + +Settings: + +- `EAC_ESP`: ESP mount point. Default: the first vfat mount of `/efi`, `/boot/efi`, `/boot`. +- `/etc/kernel/cmdline`: base kernel command line. Default: `/proc/cmdline`. + The EAC options are appended. + +After the first `setup`, every package update runs `eac-boot update` from +`pkg_postinst`. + +## One-time setup + +1. `eac-boot enroll`: the db needs your own `Database Key`, the Microsoft + certificates and `CachyOS EAC CA`. It is written with your sbctl KEK, so + Setup Mode is not needed. Do not use `sbctl enroll-keys --append`: it adds + every key again, and the firmware keeps the duplicates. + `sbctl list-enrolled-keys` prints the issuer of each certificate, so some + names appear twice in a correct db. +2. Your normal kernels must be signed with the sbctl db key. With `USE=secureboot` + and no `SECUREBOOT_SIGN_KEY`, secureboot.eclass already uses + `/var/lib/sbctl/keys/db/db.key`. Check with `sbverify --list /EFI/Gentoo/.efi`. +3. `eac-boot setup [bootnum]`. The entry goes to the end of BootOrder: + firmware boot menus (F12) only list BootOrder entries, and at the end it + never boots by default. `eac-boot boot` starts it once through BootNext. +4. Have the BitLocker recovery key of the Windows disk ready, then enable Secure Boot in the firmware. +5. `eac-boot boot`, then `eac-status` inside the EAC boot. Every check has to be `[ OK ]`. + +The next normal reboot starts the default entry again. + +## Not available in the EAC boot + +- Modules not built by CachyOS: bcachefs, kvmfr and anything built by linux-mod-r1. +- Lockdown integrity blocks MSR writes, `/dev/mem` and hibernation. + +## Bumping + +CachyOS removes old packages from the mirror. Rename the ebuild to the new kernel +`_p`, update `SDBOOT_PV`, `KEY_PV` and `SETTINGS_PV` from +, then run `ebuild manifest`. diff --git a/overlay/sys-kernel/cachyos-eac-kernel-bin/files/eac-boot b/overlay/sys-kernel/cachyos-eac-kernel-bin/files/eac-boot new file mode 100755 index 0000000..79022a3 --- /dev/null +++ b/overlay/sys-kernel/cachyos-eac-kernel-bin/files/eac-boot @@ -0,0 +1,126 @@ +#!/usr/bin/env bash +# Boot chain for linux-cachyos-eac: CachyOS-signed systemd-boot on the ESP, +# started once through its own firmware entry (BootNext). +set -euo pipefail + +EAC_OPTS="lockdown=integrity lsm=landlock,lockdown,yama,integrity,bpf iommu.passthrough=0 intel_iommu=on module.sig_enforce=1 sysctl.kernel.kexec_load_disabled=1" +LABEL="CachyOS EAC" +SDBOOT=/usr/lib/cachyos-eac/systemd-bootx64.efi.signed + +die() { echo "eac-boot: $*" >&2; exit 1; } + +esp() { + local d + for d in ${EAC_ESP:-} /efi /boot/efi /boot; do + [[ $(findmnt -no FSTYPE --mountpoint "$d" 2>/dev/null) == vfat ]] && { echo "$d"; return; } + done + die "no mounted vfat ESP found, set EAC_ESP" +} + +kver() { + local k + k=$(ls -d /lib/modules/*-cachyos-eac 2>/dev/null | sort -V | tail -n1) || true + [[ -f $k/vmlinuz ]] || die "no linux-cachyos-eac kernel in /lib/modules" + echo "${k##*/}" +} + +# Base command line from /etc/kernel/cmdline or the running system, plus the EAC options. +cmdline() { + local src=/proc/cmdline opt out=() + [[ -f /etc/kernel/cmdline ]] && src=/etc/kernel/cmdline + for opt in $(<"$src"); do + case $opt in BOOT_IMAGE=*|initrd=*) continue ;; esac + [[ " $EAC_OPTS " == *" $opt "* ]] && continue + out+=("$opt") + done + echo "${out[*]} $EAC_OPTS" +} + +bootnum() { + efibootmgr | sed -n "s/^Boot\([0-9A-F]\{4\}\)\*\{0,1\} $LABEL\t.*/\1/p" | head -n1 +} + +update() { + local esp kv mid dir + esp=$(esp) + kv=$(kver) + mid=$( "$esp/loader/entries/cachyos-eac.conf" + printf 'default cachyos-eac.conf\ntimeout 0\n' > "$esp/loader/loader.conf" + echo "eac-boot: $kv installed to $dir" +} + +# The whole db is rewritten: sbctl --append adds every key again, and firmware keeps duplicates. +enroll() { + sbctl enroll-keys --partial db --microsoft --custom --ignore-immutable +} + +# With a boot number, the entry is created there and replaces the entry that has it. +setup() { + local want=${1^^} have + [[ -z $want || $want =~ ^[0-9A-F]{4}$ ]] || die "boot number must be 4 hex digits: $1" + update + have=$(bootnum) + if [[ -n $have && ( -z $want || $have == "$want" ) ]]; then + echo "eac-boot: firmware entry Boot$have \"$LABEL\" exists" + else + create "$have" "$want" + fi + bootorder_last +} + +# Firmware boot menus only list BootOrder entries; at the end it never boots by default. +bootorder_last() { + local n order + n=$(bootnum) + order=$(efibootmgr | sed -n 's/^BootOrder: //p') + [[ ,$order, == *,$n,* ]] && return + efibootmgr --bootorder "${order:+$order,}$n" >/dev/null + echo "eac-boot: added Boot$n to the end of BootOrder" +} + +create() { + local have=$1 want=$2 old esp src + [[ -n $have ]] && efibootmgr -b "$have" -B >/dev/null + if [[ -n $want ]]; then + old=$(efibootmgr | sed -n "s/^Boot$want\*\{0,1\} \([^ ]*\).*/\1/p") + if [[ -n $old ]]; then + efibootmgr -b "$want" -B >/dev/null + echo "eac-boot: removed Boot$want \"$old\"" + fi + fi + esp=$(esp) + src=$(findmnt -no SOURCE --mountpoint "$esp") + efibootmgr --create-only ${want:+--bootnum "$want"} --disk "/dev/$(lsblk -no PKNAME "$src")" \ + --part "$(<"/sys/class/block/${src##*/}/partition")" \ + --label "$LABEL" --loader '\EFI\cachyos-eac\systemd-bootx64.efi' >/dev/null + echo "eac-boot: created firmware entry Boot$(bootnum) \"$LABEL\"" +} + +boot() { + local n + n=$(bootnum) + [[ -n $n ]] || die "no \"$LABEL\" firmware entry, run: eac-boot setup" + efibootmgr --bootnext "$n" >/dev/null + reboot +} + +case ${1:-} in + esp|cmdline) "$1"; exit ;; +esac +[[ $(id -u) == 0 ]] || die "run as root" +case ${1:-} in + enroll|update|boot) "$1" ;; + setup) setup "${2:-}" ;; + *) echo "usage: eac-boot {enroll|setup [bootnum]|update|boot|cmdline|esp}" >&2; exit 2 ;; +esac diff --git a/tools/README.md b/tools/README.md new file mode 100644 index 0000000..42c5c02 --- /dev/null +++ b/tools/README.md @@ -0,0 +1,45 @@ +# Debugging tools + +Used to find out what EAC's setup asks of systemd. Nothing here is installed by +the packages; run them from this directory. + +| File | Does | +| --- | --- | +| `exec-snoop [seconds]` | as root: prints every `execve`/`execveat` attempt with path and `argv[0..5]`, failed ones included (tracefs event probes; works under `lockdown=integrity`) | +| `exec-trace [seconds]` | as root: JSON lines for every exec on the system (pid, parent, uid, command) and the exit status of each exec'd process (kernel proc connector) | +| `eac-catch [seconds] [prefix] [dir]` | as the game's user: hardlinks every file created below `/tmp/EasyAntiCheat_EOS_Setup.*` into `/tmp/.eac-catch/` before EAC deletes it | +| `efi-sig-list.py FILE...` | lists the certificates in efivarfs dumps or `.esl` files (sha256 prefix, subject, issuer) and counts duplicates | +| `systemctl-trace` | logs argv, uid and parent to `$SYSTEMD_TRACE_DIR/systemd-trace..log` (default `/tmp`) and exits with `$SYSTEMD_TRACE_RC` (default 0) | +| `systemd1-trace [--session]` | owns `org.freedesktop.systemd1` on the system (or session) bus, prints every method call as a JSON line with the caller, replies `NotSupported` | +| `systemd1-trace.conf` | D-Bus policy that lets root own `org.freedesktop.systemd1` on the system bus | + +## Capturing a first launch + +With `sys-apps/eac-openrc-compat` installed, its `systemctl` and +`systemd-run-agent` already log every call to syslog. For a new EAC setup +version, run as root and as the user, then launch the game: + +```sh +doas ./exec-snoop 1800 > /tmp/eac-snoop.log & +./eac-catch 1800 & +``` + +Afterwards: `grep -v pactl /tmp/eac-snoop.log`, the setup's +`~/.cache/com.epicgames.easyanticheat/service.log`, and +`strings /tmp/.eac-catch/*/EasyAntiCheat_EOS_Setup` for its commands, unit +files and `--help` text. + +## Without the compatibility layer + +`systemctl-trace` and `systemd1-trace` were for the first captures, before the +layer existed. Link `systemctl-trace` as `/usr/bin/systemctl` only when +`eac-openrc-compat` is not installed (it owns that path): + +```sh +doas install -m644 systemd1-trace.conf /etc/dbus-1/system.d/ +doas ln -s "$PWD/systemctl-trace" /usr/bin/systemctl +doas ./systemd1-trace > /tmp/systemd1-system.jsonl +``` + +Remove both files afterwards. Never create `/run/systemd/system` for longer than +a capture: other programs then assume systemd runs. diff --git a/tools/eac-catch b/tools/eac-catch new file mode 100755 index 0000000..63e2a92 --- /dev/null +++ b/tools/eac-catch @@ -0,0 +1,75 @@ +#!/usr/bin/env python3 +"""Hardlink every file created below /*, so it survives its creator deleting it. + +Usage: eac-catch [seconds] [prefix] [watch-dir] +Defaults: 1800, EasyAntiCheat_EOS_Setup., /tmp. Copies land in /.eac-catch/ (a hardlink +must stay on the same filesystem). Run it as the user who starts the game. +""" +import ctypes +import os +import select +import struct +import sys +import time + +secs = float(sys.argv[1]) if len(sys.argv) > 1 else 1800 +prefix = sys.argv[2] if len(sys.argv) > 2 else "EasyAntiCheat_EOS_Setup." +top = sys.argv[3] if len(sys.argv) > 3 else "/tmp" +stash = os.path.join(top, ".eac-catch") +IN_CLOSE_WRITE, IN_MOVED_TO, IN_CREATE, IN_ISDIR = 0x8, 0x80, 0x100, 0x40000000 + +libc = ctypes.CDLL(None, use_errno=True) +fd = libc.inotify_init1(os.O_CLOEXEC) +dirs = {} + + +def log(*args): + print(time.strftime("%T"), *args, flush=True) + + +def grab(path): + dst = os.path.join(stash, os.path.relpath(path, top)) + os.makedirs(os.path.dirname(dst), exist_ok=True) + try: + os.link(path, dst) + log("caught", path) + except FileExistsError: + pass + except OSError as e: + log("missed", path, e.strerror) + + +def watch(path): + wd = libc.inotify_add_watch(fd, path.encode(), IN_CREATE | IN_MOVED_TO | IN_CLOSE_WRITE) + if wd < 0: + log("cannot watch", path, os.strerror(ctypes.get_errno())) + return + dirs[wd] = path + if path == top: + return + log("watching", path) + # Entries created before the watch existed. + for entry in os.scandir(path): + watch(entry.path) if entry.is_dir(follow_symlinks=False) else grab(entry.path) + + +watch(top) +deadline = time.monotonic() + secs +while (left := deadline - time.monotonic()) > 0: + if not select.select([fd], [], [], left)[0]: + break + buf, i = os.read(fd, 65536), 0 + while i < len(buf): + wd, mask, _, n = struct.unpack_from("iIII", buf, i) + name = buf[i + 16:i + 16 + n].rstrip(b"\0").decode(errors="replace") + i += 16 + n + parent = dirs.get(wd) + if parent is None or not name: + continue + path = os.path.join(parent, name) + if parent == top and not name.startswith(prefix): + continue + try: + watch(path) if mask & IN_ISDIR else grab(path) + except FileNotFoundError: + log("gone before it was caught", path) diff --git a/tools/efi-sig-list.py b/tools/efi-sig-list.py new file mode 100755 index 0000000..e4caf83 --- /dev/null +++ b/tools/efi-sig-list.py @@ -0,0 +1,62 @@ +#!/usr/bin/env python3 +"""List the entries of UEFI signature lists and count duplicates. + +Usage: efi-sig-list.py FILE... + FILE = an efivarfs dump (/sys/firmware/efi/efivars/{PK,KEK,db,dbx}- or a + `cat` copy; the 4-byte attribute prefix is skipped) or a plain `.esl` file + (e.g. from `sbctl enroll-keys --export esl`). +Prints per entry: sha256 prefix, subject CN, issuer CN; then entries vs unique. +No arguments runs a self-check. +""" +import hashlib +import struct +import subprocess +import sys + +X509 = bytes.fromhex("a159c0a5e494a74a87b5ab155c2bf072") +SHA256 = bytes.fromhex("2616c4c14c509240aca941f936934328") + + +def cn(der, field): + out = subprocess.run(["openssl", "x509", "-inform", "DER", "-noout", f"-{field}", "-nameopt", "multiline"], + input=der, capture_output=True).stdout.decode() + return next((l.split("=", 1)[1].strip() for l in out.splitlines() if "commonName" in l), "?") + + +def entries(b): + i = 0 + while i + 28 <= len(b): + stype = b[i:i + 16] + lsize, hsize, ssize = struct.unpack_from(" log +set -eu +secs=${1:-600} +T=/sys/kernel/tracing +I=$T/instances/exec-snoop +A='a0=+0(+u0($argv)):ustring a1=+0(+u8($argv)):ustring a2=+0(+u16($argv)):ustring' +A+=' a3=+0(+u24($argv)):ustring a4=+0(+u32($argv)):ustring a5=+0(+u40($argv)):ustring' + +cleanup() { + [[ -d $I ]] && { echo 0 > "$I/events/exec_snoop/enable"; rmdir "$I"; } + for e in execve execveat; do echo "-:exec_snoop/$e" >> $T/dynamic_events 2>/dev/null || true; done +} +cleanup +trap cleanup EXIT + +echo "e:exec_snoop/execve syscalls.sys_enter_execve file=+0(\$filename):ustring $A" >> $T/dynamic_events +echo "e:exec_snoop/execveat syscalls.sys_enter_execveat file=+0(\$filename):ustring $A" >> $T/dynamic_events +mkdir "$I" +echo 1 > "$I/events/exec_snoop/enable" +timeout "$secs" cat "$I/trace_pipe" || true diff --git a/tools/exec-trace b/tools/exec-trace new file mode 100755 index 0000000..6c4e38a --- /dev/null +++ b/tools/exec-trace @@ -0,0 +1,60 @@ +#!/usr/bin/env python3 +"""Log every exec, and the exit of every exec'd process, as JSON lines (kernel proc connector). + +Needs root. Nothing is attached to the traced processes. Usage: exec-trace [seconds] +""" +import json +import os +import socket +import struct +import sys +import time + +NETLINK_CONNECTOR, CN_IDX_PROC, CN_VAL_PROC = 11, 1, 1 +PROC_CN_MCAST_LISTEN, PROC_EVENT_EXEC, PROC_EVENT_EXIT = 1, 0x2, 0x80000000 + + +def read(pid, name): + try: + with open(f"/proc/{pid}/{name}", "rb") as f: + return f.read() + except OSError: + return b"" + + +def cmdline(pid): + return read(pid, "cmdline").replace(b"\0", b" ").decode(errors="replace").strip() + + +def emit(**fields): + print(json.dumps({"time": time.strftime("%T"), **fields}), flush=True) + + +sock = socket.socket(socket.AF_NETLINK, socket.SOCK_DGRAM, NETLINK_CONNECTOR) +sock.bind((os.getpid(), CN_IDX_PROC)) +op = struct.pack("=I", PROC_CN_MCAST_LISTEN) +cn = struct.pack("=4I2H", CN_IDX_PROC, CN_VAL_PROC, 0, 0, len(op), 0) + op +sock.send(struct.pack("=IHHII", 16 + len(cn), 3, 0, 0, os.getpid()) + cn) + +deadline = time.monotonic() + float(sys.argv[1]) if len(sys.argv) > 1 else None +seen = {} +while deadline is None or time.monotonic() < deadline: + sock.settimeout(None if deadline is None else max(0.1, deadline - time.monotonic())) + try: + data = sock.recv(65536) + except socket.timeout: + break + what = struct.unpack_from("=I", data, 36)[0] + if what == PROC_EVENT_EXEC: + tgid = struct.unpack_from("=ii", data, 52)[1] + status = dict(l.split(":\t", 1) for l in read(tgid, "status").decode(errors="replace").splitlines() if ":\t" in l) + ppid = status.get("PPid", "").strip() + seen[tgid] = cmdline(tgid) + emit(event="exec", pid=tgid, ppid=ppid, uid=status.get("Uid", "").split()[:2], + exe=os.path.realpath(f"/proc/{tgid}/exe") if os.path.exists(f"/proc/{tgid}/exe") else "", + cmd=seen[tgid], parent=cmdline(ppid)[:200] if ppid.isdigit() else "") + elif what == PROC_EVENT_EXIT: + pid, tgid, code, sig = struct.unpack_from("=iiII", data, 52) + if pid == tgid and tgid in seen: + emit(event="exit", pid=tgid, cmd=seen.pop(tgid)[:120], + status=(code >> 8) if code & 0x7f == 0 else f"signal {code & 0x7f}") diff --git a/tools/systemctl-trace b/tools/systemctl-trace new file mode 100755 index 0000000..133bb13 --- /dev/null +++ b/tools/systemctl-trace @@ -0,0 +1,11 @@ +#!/usr/bin/env bash +# Logs every call and succeeds, so the caller moves on to its next step. +log=${SYSTEMD_TRACE_DIR:-/tmp}/systemd-trace.$(id -u).log +{ + printf '%s systemctl pid=%s uid=%s parent=%s\n' "$(date +%T.%N)" "$$" "$(id -u)" \ + "$(tr '\0' ' ' >"$log" +exit "${SYSTEMD_TRACE_RC:-0}" diff --git a/tools/systemd1-trace b/tools/systemd1-trace new file mode 100755 index 0000000..15cd0e0 --- /dev/null +++ b/tools/systemd1-trace @@ -0,0 +1,58 @@ +#!/usr/bin/env python3 +"""Own org.freedesktop.systemd1 and log every method call as a JSON line. + +Each call gets an org.freedesktop.DBus.Error.NotSupported reply, so the log shows +the first call of every attempt. Reply with real values here once the calls are known. +""" +import json +import sys +import time + +import dbus +import dbus.lowlevel +from dbus.mainloop.glib import DBusGMainLoop +from gi.repository import GLib + +NAME = "org.freedesktop.systemd1" + +DBusGMainLoop(set_as_default=True) +bus = dbus.SessionBus() if "--session" in sys.argv[1:] else dbus.SystemBus() +commands = {} + + +def command(sender): + if sender not in commands: + try: + pid = bus.call_blocking("org.freedesktop.DBus", "/org/freedesktop/DBus", + "org.freedesktop.DBus", "GetConnectionUnixProcessID", + "s", (sender,)) + with open(f"/proc/{pid}/cmdline", "rb") as f: + commands[sender] = f"{pid} " + f.read().replace(b"\0", b" ").decode().strip() + except (dbus.DBusException, OSError) as e: + commands[sender] = f"? ({e})" + return commands[sender] + + +def on_message(conn, msg): + if msg.get_type() != dbus.lowlevel.MESSAGE_TYPE_METHOD_CALL or msg.get_destination() != NAME: + return dbus.lowlevel.HANDLER_RESULT_NOT_YET_HANDLED + print(json.dumps({ + "time": time.strftime("%T"), + "sender": msg.get_sender(), + "command": command(msg.get_sender()), + "path": msg.get_path(), + "method": f"{msg.get_interface()}.{msg.get_member()}", + "signature": msg.get_signature(), + "args": msg.get_args_list(), + }, default=str), flush=True) + if not msg.get_no_reply(): + conn.send_message(dbus.lowlevel.ErrorMessage( + msg, "org.freedesktop.DBus.Error.NotSupported", "systemd1-trace: logged only")) + return dbus.lowlevel.HANDLER_RESULT_HANDLED + + +bus.add_message_filter(on_message) +if bus.request_name(NAME, dbus.bus.NAME_FLAG_DO_NOT_QUEUE) != dbus.bus.REQUEST_NAME_REPLY_PRIMARY_OWNER: + sys.exit(f"{NAME} is already owned") +print(f"owning {NAME}", file=sys.stderr, flush=True) +GLib.MainLoop().run() diff --git a/tools/systemd1-trace.conf b/tools/systemd1-trace.conf new file mode 100644 index 0000000..9988383 --- /dev/null +++ b/tools/systemd1-trace.conf @@ -0,0 +1,10 @@ + + + + + + + + +