diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 22aeb8f29..badb4df62 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -66,6 +66,14 @@ on: Example: "org.gnome.Calculator,io.github.kolunmi.Bazaar" type: string default: "" + selinux_enforcing: + description: > + Boot the guest with the candidate's own SELinux mode instead of + selinux=0, label the harness files, verify enforcing after boot and + run the AVC denial gate (#1024). Defaults to false until a hosted + run qualifies the path and the rollout plan in #1021 turns it on. + type: boolean + default: false migration-target: description: > Migration target image ref for cross-registry migration scenarios. @@ -249,6 +257,9 @@ jobs: scripts/install-kde-webdriver.sh scripts/e2e_summary.py scripts/image_slug.py + scripts/selinux_collect_avc.sh + scripts/selinux_qualify.py + selinux_allowlist.yaml sparse-checkout-cone-mode: false # smoke-a/smoke-b and common-a/common-b are parallel halves of their @@ -380,6 +391,7 @@ jobs: - name: Install OCI image and configure disk env: SUITE_DIR: ${{ steps.shard.outputs.suite_dir }} + SELINUX_ENFORCING: ${{ inputs.selinux_enforcing && 'true' || 'false' }} run: | # The NVIDIA release candidate used 92% of a 32 GiB disk in run # 30926761425. A 40 GiB disk leaves roughly 26% free at that same @@ -545,8 +557,41 @@ jobs: # # systemd.journald.forward_to_console=1 — forward full journal to serial for # diagnostics when SSH fails (output captured in vm-serial.log artifact). - KERNEL_ARGS="root=UUID=${ROOT_UUID} rw ostree=${OSTREE_PATH} systemd.firstboot=no selinux=0 console=ttyS0,115200 systemd.journald.forward_to_console=1 systemd.mask=brew-setup.service systemd.mask=NetworkManager-wait-online.service systemd.mask=firewalld.service systemd.mask=wpa_supplicant.service systemd.mask=flatpak-preinstall.service systemd.mask=podman-auto-update.service systemd.mask=podman-auto-update.timer systemd.mask=malcontent-webd.service systemd.mask=malcontent-webd-update.service systemd.mask=malcontent-control.service systemd.mask=speech-dispatcherd.service systemd.mask=avahi-daemon.service systemd.mask=avahi-daemon.socket systemd.mask=cups.service systemd.mask=cups.path systemd.mask=cups.socket systemd.mask=cups.browsed.service systemd.mask=blueman-mechanism.service systemd.mask=gnome-remote-desktop.service systemd.mask=bazzite-hardware-setup.service systemd.mask=greenboot-healthcheck.service systemd.mask=greenboot-set-rollback-trigger.service systemd.mask=systemd-udev-settle.service systemd.wants=sshd.service" + KERNEL_ARGS="root=UUID=${ROOT_UUID} rw ostree=${OSTREE_PATH} systemd.firstboot=no console=ttyS0,115200 systemd.journald.forward_to_console=1 systemd.mask=brew-setup.service systemd.mask=NetworkManager-wait-online.service systemd.mask=firewalld.service systemd.mask=wpa_supplicant.service systemd.mask=flatpak-preinstall.service systemd.mask=podman-auto-update.service systemd.mask=podman-auto-update.timer systemd.mask=malcontent-webd.service systemd.mask=malcontent-webd-update.service systemd.mask=malcontent-control.service systemd.mask=speech-dispatcherd.service systemd.mask=avahi-daemon.service systemd.mask=avahi-daemon.socket systemd.mask=cups.service systemd.mask=cups.path systemd.mask=cups.socket systemd.mask=cups.browsed.service systemd.mask=blueman-mechanism.service systemd.mask=gnome-remote-desktop.service systemd.mask=bazzite-hardware-setup.service systemd.mask=greenboot-healthcheck.service systemd.mask=greenboot-set-rollback-trigger.service systemd.mask=systemd-udev-settle.service systemd.wants=sshd.service" + # Enforcing mode is opt-in (inputs.selinux_enforcing) until a hosted + # run qualifies it; otherwise the guest keeps SELinux off as before. + if [[ "${SELINUX_ENFORCING}" != "true" ]]; then + KERNEL_ARGS="${KERNEL_ARGS} selinux=0" + fi echo "KERNEL_ARGS=${KERNEL_ARGS}" >> "$GITHUB_ENV" + # SELinux: the guest boots with the candidate's own mode, which must + # be enforcing whenever the image ships a policy store (#1024). + # bootc labels everything it installs, but files written below on + # this non-SELinux runner carry no label and would be unlabeled_t in + # the guest. Record what is already unlabeled first: that is + # candidate-owned and is left alone so its defects stay visible. + if [[ "${SELINUX_ENFORCING}" == "true" ]]; then + SELINUX_INFO=$(sudo python3 -I scripts/selinux_qualify.py expected-mode "${D}") + else + SELINUX_INFO="off none" + fi + SELINUX_EXPECTED="${SELINUX_INFO% *}" + SELINUX_POLICY="${SELINUX_INFO#* }" + echo "SELinux: expected=${SELINUX_EXPECTED} policy=${SELINUX_POLICY}" + echo "SELINUX_EXPECTED=${SELINUX_EXPECTED}" >> "$GITHUB_ENV" + SELINUX_DIR="$(pwd)/results/selinux" + STATEROOT="/mnt/root/ostree/deploy/default" + mkdir -p "${SELINUX_DIR}" + if [[ "${SELINUX_EXPECTED}" == enforcing ]]; then + for DEP in $(sudo find "${STATEROOT}/deploy" -maxdepth 1 -mindepth 1 -type d 2>/dev/null); do + sudo python3 -I scripts/selinux_qualify.py unlabeled --root "${DEP}" "${DEP}/etc" \ + > "${SELINUX_DIR}/baseline-unlabeled-$(basename "${DEP}").txt" + done + sudo python3 -I scripts/selinux_qualify.py unlabeled --root "${STATEROOT}" "${VAR}" \ + > "${SELINUX_DIR}/baseline-unlabeled-var.txt" + echo "Unlabeled before harness changes (candidate-owned, not relabeled):" + wc -l "${SELINUX_DIR}"/baseline-unlabeled-*.txt + fi # Apply user + sshd config to ALL deployments in this stateroot. # bootc may deploy with a different checksum than what `ls|head-1` @@ -711,6 +756,42 @@ jobs: sudo chmod 644 "${DEP}/etc/ssh/ci-authorized-keys" done + # Label exactly the files the harness added, using the candidate's own + # setfiles and file_contexts so the result matches what the guest + # policy expects. -m: this runner's mounts carry no seclabel flag. + if [[ "${SELINUX_EXPECTED}" == enforcing ]]; then + label_harness_files() { # ROOT FILE_CONTEXTS BASELINE LIST SCAN_PATH + sudo python3 -I scripts/selinux_qualify.py unlabeled --root "$1" --exclude "$3" "$5" > "$4" + if [[ -s "$4" ]]; then + sudo podman run --rm --privileged --network none \ + --security-opt label=disable \ + -v /mnt/root:/mnt/root \ + -v "${SELINUX_DIR}:${SELINUX_DIR}:ro" \ + "${IMAGE}" setfiles -m -F -r "$1" -f "$4" "$2" + fi + LEFT=$(sudo python3 -I scripts/selinux_qualify.py unlabeled --root "$1" --exclude "$3" "$5") + if [[ -n "${LEFT}" ]]; then + echo "::error::harness files still unlabeled after setfiles:" + echo "${LEFT}" + exit 1 + fi + } + for DEP in $(sudo find "${STATEROOT}/deploy" -maxdepth 1 -mindepth 1 -type d 2>/dev/null); do + NAME=$(basename "${DEP}") + label_harness_files "${DEP}" \ + "${DEP}/etc/selinux/${SELINUX_POLICY}/contexts/files/file_contexts" \ + "${SELINUX_DIR}/baseline-unlabeled-${NAME}.txt" \ + "${SELINUX_DIR}/harness-labeled-${NAME}.txt" \ + "${DEP}/etc" + done + label_harness_files "${STATEROOT}" \ + "${D}/etc/selinux/${SELINUX_POLICY}/contexts/files/file_contexts" \ + "${SELINUX_DIR}/baseline-unlabeled-var.txt" \ + "${SELINUX_DIR}/harness-labeled-var.txt" \ + "${VAR}" + echo "Harness files labeled with the candidate policy:" + wc -l "${SELINUX_DIR}"/harness-labeled-*.txt + fi # Pre-boot diagnostics: confirm key files and sshd drop-in are correct. echo "=== ci-authorized-keys ===" for DEP in $(sudo find /mnt/root/ostree/deploy/default/deploy \ @@ -766,7 +847,7 @@ jobs: [[ -S /tmp/qemu-monitor.sock ]] && echo "QEMU monitor socket ready." \ || echo "WARNING: QEMU monitor socket not found after 5s" - # selinux=0 + pre-generated host keys + masked slow services = SSH ready in ~90s + # Pre-generated host keys + masked slow services = SSH ready in ~90s - name: Wait for SSH run: | SSH_COMMON="-i /tmp/vm_key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ControlMaster=auto -o ControlPersist=600 -o ControlPath=/tmp/ssh-ctrl-%C -o ConnectTimeout=3" @@ -789,6 +870,22 @@ jobs: grep -i "dbus\|broker\|ostree-system\|composefs\|FAILED\|Error" "$(pwd)/vm-serial.log" 2>/dev/null | tail -40 || echo "(none found)" exit 1 + # Fail early if the guest is not enforcing: every later result would be + # a qualification of the wrong security posture. + - name: Verify SELinux enforcing + if: env.SELINUX_EXPECTED != 'off' + run: | + SSH_COMMON="-i /tmp/vm_key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ControlMaster=auto -o ControlPersist=600 -o ControlPath=/tmp/ssh-ctrl-%C -o ConnectTimeout=3" + SSH="ssh ${SSH_COMMON} -p 2222 bluefin-test@127.0.0.1" + mkdir -p results/selinux + OBSERVED=$($SSH "getenforce 2>/dev/null" || true) + echo "image=${BASE_IMAGE} booted=${IMAGE} expected=${SELINUX_EXPECTED:-enforcing} after-boot=${OBSERVED:-none}" \ + | tee results/selinux/mode.txt + $SSH "sestatus 2>&1; id -Z; ls -Z /etc/group /etc/ssh/ci-authorized-keys /etc/ssh/sshd_config.d/00-ci-auth.conf /etc/sudoers.d/zz-bluefin-test ~/.ssh/authorized_keys 2>&1" \ + > results/selinux/contexts-boot.txt 2>&1 || true + cat results/selinux/contexts-boot.txt + python3 scripts/selinux_qualify.py check-mode "${SELINUX_EXPECTED:-enforcing}" "${OBSERVED}" + - name: Pre-stage target image via bootc switch if: ${{ inputs.target-image != '' && contains(inputs.suites, 'lifecycle') && env.SUITE == 'lifecycle' }} run: | @@ -1511,6 +1608,45 @@ jobs: echo "behave_rc=${BEHAVE_RC}" >> "$GITHUB_OUTPUT" + # Runs after the suite, so it also covers the state after any lifecycle + # reboot. A canary denial then proves the collection path reaches the + # verdict; without it a clean gate could mean "no logs" rather than + # "no denials". + - name: SELinux denial gate + if: always() && steps.run.conclusion != 'skipped' && env.SELINUX_EXPECTED == 'enforcing' + run: | + # Fresh connection: the VM may have rebooted during the suite. + SSH="ssh -i /tmp/vm_key -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o BatchMode=yes -o ControlMaster=no -o ConnectTimeout=10 -p 2222 bluefin-test@127.0.0.1" + D=results/selinux + mkdir -p "${D}" + DEADLINE=$((SECONDS + 300)) + until $SSH true 2>/dev/null; do + [[ $SECONDS -lt $DEADLINE ]] || { echo "::error::VM unreachable for the SELinux gate"; exit 1; } + sleep 5 + done + OBSERVED=$($SSH "getenforce 2>/dev/null" || true) + echo "after-run=${OBSERVED:-none}" | tee -a "${D}/mode.txt" + RC=0 + python3 scripts/selinux_qualify.py check-mode enforcing "${OBSERVED}" || RC=1 + $SSH 'sudo bash -s' < scripts/selinux_collect_avc.sh > "${D}/avc-scenario.log" + python3 scripts/selinux_qualify.py gate "${D}/avc-scenario.log" \ + --allowlist selinux_allowlist.yaml --json "${D}/avc-verdict.json" || RC=1 + # Canary: start a transient unit in httpd_t, which may not run + # /usr/bin/cat or read shadow_t. Output goes nowhere. + $SSH "sudo timeout 60 systemd-run --quiet --wait --collect -p StandardOutput=null -p StandardError=null -p SELinuxContext=system_u:system_r:httpd_t:s0 /usr/bin/cat /etc/shadow" || true + sleep 3 + $SSH 'sudo bash -s' < scripts/selinux_collect_avc.sh > "${D}/avc-after-canary.log" + python3 scripts/selinux_qualify.py canary "${D}/avc-scenario.log" "${D}/avc-after-canary.log" \ + --allowlist selinux_allowlist.yaml --json "${D}/canary.json" || RC=1 + { + echo "### SELinux qualification: $([[ ${RC} -eq 0 ]] && echo passed || echo FAILED)" + echo '```' + cat "${D}/mode.txt" + python3 scripts/selinux_qualify.py gate "${D}/avc-scenario.log" --allowlist selinux_allowlist.yaml 2>&1 | sed -E 's/^::[a-z]+:://' || true + echo '```' + } >> "$GITHUB_STEP_SUMMARY" + exit "${RC}" + - name: Capture post-upgrade desktop screenshot if: always() && env.SUITE == 'lifecycle' continue-on-error: true diff --git a/.github/workflows/manual.yml b/.github/workflows/manual.yml index b53e5e1ee..895859d94 100644 --- a/.github/workflows/manual.yml +++ b/.github/workflows/manual.yml @@ -20,6 +20,10 @@ on: description: "Enable @zstd_chunked scenarios in the lifecycle suite" required: false default: "false" + selinux_enforcing: + description: "Boot the guest SELinux enforcing and run the AVC denial gate (#1024)" + required: false + default: "false" test_ref: description: "Git ref for tests/ checkout (default: dispatched branch; set to override)" required: false @@ -36,6 +40,7 @@ jobs: image: ${{ github.event.inputs.image }} suites: ${{ github.event.inputs.suites }} chunked_enabled: ${{ github.event.inputs.chunked_enabled == 'true' }} + selinux_enforcing: ${{ github.event.inputs.selinux_enforcing == 'true' }} # workflow_dispatch sees the branch selected in the Actions UI. Keep # branch resolution here; github.ref_name inside e2e.yml resolves to main. test_ref: ${{ github.event.inputs.test_ref || github.ref_name }} diff --git a/docs/skills/ci-ops/e2e-workflow/SKILL.md b/docs/skills/ci-ops/e2e-workflow/SKILL.md index f80bda562..b65414790 100644 --- a/docs/skills/ci-ops/e2e-workflow/SKILL.md +++ b/docs/skills/ci-ops/e2e-workflow/SKILL.md @@ -200,12 +200,12 @@ another script runs. Why this fails silently: [troubleshooting.md](references/tr - Mounts the raw disk, finds `ROOT_UUID` (partition 3), ostree deployment hash, and `KVER` - Copies `vmlinuz` + `initramfs.img` from deployment `usr/lib/modules//` (or boot partition fallback) - Creates `boot.N` symlinks needed by `ostree-system-generator` (including canonical `boot.N` alias for versioned `boot.N.M` dirs produced by newer bootc) - - Sets `KERNEL_ARGS` env (includes `root=UUID=...`, masked services, serial console, `selinux=0`) + - Sets `KERNEL_ARGS` env (includes `root=UUID=...`, masked services, serial console; `selinux=0` unless `selinux_enforcing: true`, which boots the candidate's own SELinux mode, see `references/selinux-enforcing.md`) - Iterates all deployment directories and writes: `bluefin-test` user (UID 1001, added to `wheel` like a real first-run admin account — common's `org.ublue.privileged.user.setup` polkit rule grants wheel only), GDM autologin, sshd drop-in `00-ci-auth.conf`, dconf `local.d/00-ci-testing` override, `tmpfiles.d/ci-user.conf`, masked service symlinks - Pre-installs `unsafe-mode@bluefin-test` gnome-shell extension files into var home (pre-boot, so gnome-shell finds it during `_loadExtensions()`) - Injects SSH authorized key into `/var/home/bluefin-test/.ssh/` and each deployment's `/etc/ssh/ci-authorized-keys` 10. **Boot VM** — `qemu-system-x86_64` with KVM, 4 GB RAM, 4 vCPUs, `-vga none` + `virtio-gpu-pci` (one display adapter; q35's default std VGA made mutter light a second monitor, so desktop screenshots came out 2560x800), forwarded SSH on port 2222; daemonized; QEMU monitor socket at `/tmp/qemu-monitor.sock` (chmod 666) -11. **Wait for SSH** — polls port 2222 up to **15 minutes** (900 s) +11. **Wait for SSH** — polls port 2222 up to **15 minutes** (900 s); then, with `selinux_enforcing: true`, **Verify SELinux enforcing** — fails unless `getenforce` is `Enforcing` when the image ships a policy store; records `sestatus`/`id -Z`/`ls -Z` to `results/selinux/` 12. **Pre-stage target image via bootc switch** — lifecycle suite only, when `inputs.target-image` is set; SSHes into VM and runs `sudo bootc switch ''` to stage the upgrade target before the test run 13. **Dump VM serial log** — always runs (`if: always()`); primary debug tool when SSH never comes up 14. **Wait for GNOME session** — polls `/run/user/1001/wayland-0` up to 3 minutes @@ -215,7 +215,7 @@ another script runs. Why this fails silently: [troubleshooting.md](references/tr 18. **Load runner container into VM** — non-common suites; ensures `bluefin-test` has `/etc/subuid`/`/etc/subgid`, runs `podman system migrate`, pipes `ghcr.io//testsuite:runner` via `podman save | ssh podman load`; patches `openssh-clients` into the runner image if missing 19. **Install Python test stack** — non-common suites; loads `uinput` kernel module, sets device permissions, copies SSH private key into VM for `@plain_ssh` scenarios, queries GNOME session environment into `/tmp/session.env`, enables `unsafe-mode@bluefin-test` extension, sets `toolkit-accessibility true`, disables idle locking for the disposable test user, re-queries AT-SPI bus address after enabling accessibility, terminates any pre-started `gnome-control-center` 20. **Install gnome-ponytail-daemon** — non-common suites; builds `gnome-ponytail-daemon` (tag `0.0.11`) and `grim` from source inside a `debian:bookworm` container on the runner (without libei, uses Mutter D-Bus fallback for input events; wayland-protocols 1.37 built from source for grim); SCPs binaries into `~/.local/libexec/` and `~/.local/bin/`; registers D-Bus service file and pre-starts the daemon -21. **Run behave suite** — `common`/`lifecycle`/`installer`: runner-side `python3 tests/shared/behave_retry.py` with `VM_IP/VM_USER/SSH_KEY/SSH_PORT` env vars (this fixed list is the whole environment those suites get — a scenario gated on any other variable can never run; see [installer-suite.md](references/installer-suite.md)). The migration lane additionally receives `MIGRATION_TARGET` and `EXTRA_TAGS` from the two `migration-target`/`extra-tags` inputs below; `EXTRA_TAGS` is appended to `BEHAVE_TAG_ARGS` as `--tags ` so a dispatch can scope the lifecycle run to just `@migration`. GUI suites: SCP `tests/` + `tests/shared` + `tests/__init__.py` to VM, then `podman run ... ghcr.io//testsuite:runner "python3 .../behave_retry.py ... --format json.pretty"` inside VM; always `--tags ~quarantine`; retries controlled by `BEHAVE_RETRIES=2` +21. **Run behave suite** — `common`/`lifecycle`/`installer`: runner-side `python3 tests/shared/behave_retry.py` with `VM_IP/VM_USER/SSH_KEY/SSH_PORT` env vars (this fixed list is the whole environment those suites get — a scenario gated on any other variable can never run; see [installer-suite.md](references/installer-suite.md)). The migration lane additionally receives `MIGRATION_TARGET` and `EXTRA_TAGS` from the two `migration-target`/`extra-tags` inputs below; `EXTRA_TAGS` is appended to `BEHAVE_TAG_ARGS` as `--tags ` so a dispatch can scope the lifecycle run to just `@migration`. GUI suites: SCP `tests/` + `tests/shared` + `tests/__init__.py` to VM, then `podman run ... ghcr.io//testsuite:runner "python3 .../behave_retry.py ... --format json.pretty"` inside VM; always `--tags ~quarantine`; retries controlled by `BEHAVE_RETRIES=2`; then **SELinux denial gate** — `always()` after the suite; re-checks enforcing, collects AVCs via `scripts/selinux_collect_avc.sh`, fails on denials not in `selinux_allowlist.yaml`, then runs the `httpd_t` canary (see [selinux-enforcing.md](references/selinux-enforcing.md)) 22. **Capture post-upgrade desktop screenshot** — lifecycle suite only; SSHes with `ControlMaster=no`, waits up to 60 s for Wayland socket, captures via `gdbus org.gnome.Shell.Eval` 23. **Capture post-migration screenshot and status** — lifecycle suite only; QEMU framebuffer capture via `qemu_screendump.py` + SSH for `bootc status`, `fastfetch`, `os-release` into `results/migration-status.txt` 24. **Capture Flatpak screenshots** — when `inputs.screenshot_flatpaks != ''`; runs `screenshot_cli.py` inside the runner container @@ -495,5 +495,6 @@ Load these when you hit the specific topic: - [Installer suite assertions, and why an env-var gate made one unreachable.](references/installer-suite.md) - [Migration inputs `migration-target` / `extra-tags` and the startup_failure they cause when missing.](references/migration-inputs.md) - [GNOME OS guest lane for the developer extension-validation service and its mandatory gate.](references/gnome-extensions-validation.md) +- [SELinux enforcing in the e2e guest (opt-in): labeling, mode checks, AVC gate, canary.](references/selinux-enforcing.md) - [GNOME OS image provenance (2-week tag expiry), verified guest inventory, and the extensions pre-boot preflight](references/gnomeos-guest-provenance.md) - [Which units the fast e2e lane masks, why, and which still need a startup-qualification lane.](references/startup-service-inventory.md) diff --git a/docs/skills/ci-ops/e2e-workflow/references/selinux-enforcing.md b/docs/skills/ci-ops/e2e-workflow/references/selinux-enforcing.md new file mode 100644 index 000000000..5e3892536 --- /dev/null +++ b/docs/skills/ci-ops/e2e-workflow/references/selinux-enforcing.md @@ -0,0 +1,86 @@ +--- +name: selinux-enforcing +description: "How the e2e QEMU guest is qualified with SELinux enforcing: labeling, mode checks, AVC gate, canary." +metadata: + type: reference + audience: agents + maturity: experimental +--- +# SELinux enforcing in the e2e guest + +The lane is opt-in: callers pass `selinux_enforcing: true` (`manual.yml` +exposes the same input). With the default `false` the guest keeps +`selinux=0` and every step below is skipped, until a hosted run qualifies the +lane and the rollout plan in #1021 flips the default. + +When enabled, `e2e.yml` boots the candidate with its own SELinux mode. There +is no `selinux=0`, `enforcing=0` or `enforcing=1` on the kernel command line: +the first two hide policy regressions, the last hides a candidate that ships +permissive. Helpers live in `scripts/selinux_qualify.py` and +`scripts/selinux_collect_avc.sh` (both in the sparse checkout). Evidence is +written to `results/selinux/` and uploaded with the results artifact. + +## Contract + +| Stage | Step | Fails when | +|-------|------|------------| +| Expected mode | install step, `expected-mode` | never; any deployment with `etc/selinux//contexts/files/file_contexts` expects `enforcing`, otherwise `unsupported` (freedesktop-sdk images) | +| Labeling | install step, before unmount | a harness-created file is still unlabeled after `setfiles` | +| After boot | **Verify SELinux enforcing** | `getenforce` is not `Enforcing` (or is `Enforcing` on an `unsupported` image) | +| After suite | **SELinux denial gate** | still not enforcing (covers lifecycle reboots); any enforced AVC not in `selinux_allowlist.yaml`; the canary is not seen | + +`permissive=1` denials (permissive domains in the candidate policy) are +printed as warnings and recorded, not failed: the operation was not blocked. + +## Labeling harness files + +The runner has no SELinux, so the files the install step writes under each +deployment's `etc` and under `var` (`passwd` and `group` edits via `sed -i`, +sshd drop-in, host keys, sudoers, GDM/SDDM config, masked-unit symlinks, the +`bluefin-test` home) have no `security.selinux` xattr and would be +`unlabeled_t` in the guest. Only those two trees are scanned and relabeled. +The fallback `boot.N` symlinks under `/ostree/boot.*` stay unlabeled; they are +read only by `ostree`/`bootc`, which run unconfined. + +1. Before any injection, record paths under each deployment's `etc/` and the + stateroot `var/` that are already unlabeled (`baseline-unlabeled-*.txt`). + These are candidate-owned and are **not** relabeled, so a candidate + labeling defect stays a product failure. +2. After injection, list unlabeled paths not in the baseline + (`harness-labeled-*.txt`) and label them with the **candidate's** own + `setfiles` and `file_contexts`, run in a privileged container of the + image: `setfiles -m -F -r -f `. `-r` strips + the deployment or stateroot prefix so `.../default/var/home/...` matches + `/var/home/...`. `-m` is required because the runner's mounts carry no + `seclabel` option. +3. Re-scan; anything still unlabeled fails the step. + +Never fix a denial by relabeling the whole tree, `-F` over candidate files, +`chcon` to a broad type, `setenforce 0`, or a permissive domain. + +## AVC collection and canary + +`selinux_collect_avc.sh` runs in the guest as root and prints AVC/USER_AVC +records from `ausearch` (when auditd has a log) and the whole journal (all +kept boots). `selinux_qualify.py` de-duplicates by audit serial. + +After the scenario log is judged, the gate starts a transient unit in +`httpd_t` that runs `/usr/bin/cat /etc/shadow` with output discarded. The +policy forbids that (entrypoint or read), so a new `httpd_t` denial must +appear and must fail the gate. If it does not, collection is broken and the +step fails: a clean gate would prove nothing. + +## Allowlist + +`selinux_allowlist.yaml` entries match on SELinux **type** of +`source_context` and `target_context`, the exact permission set, `comm`, and +`tclass` when given. `reason` is required; link `upstream_bug` when there is +one. Prefer filing the denial against the owning image repo over adding an +entry. An entry broad enough to match the canary defeats the canary. + +## Known gaps + +- Not yet proven on a hosted run; dispatch `manual.yml` with `smoke` and a + `lifecycle` suite before relying on it. +- The security suite (`tests/security`) has its own SELinux scenarios; its + reachability is tracked separately (#704). diff --git a/docs/skills/ci-ops/e2e-workflow/references/troubleshooting.md b/docs/skills/ci-ops/e2e-workflow/references/troubleshooting.md index 48bbce168..343c8cffb 100644 --- a/docs/skills/ci-ops/e2e-workflow/references/troubleshooting.md +++ b/docs/skills/ci-ops/e2e-workflow/references/troubleshooting.md @@ -79,7 +79,7 @@ still belong only in a fresh disposable guest without publishing credentials. Check the serial log artifact. Common causes: - ostree deployment missing: `bootc install` exited before writing layers (check for `ERROR: ostree deployment missing` in the install step) - Kernel args wrong: `root=UUID=…` mismatch — verify `ROOT_UUID` in the install step output -- `selinux=0` is set, so SELinux policy isn't the cause +- SELinux denial: the guest boots enforcing. Check `results/selinux/` in the results artifact and the serial log for `avc: denied`; an unlabeled harness file means the install step's labeling missed it. See [selinux-enforcing.md](selinux-enforcing.md) ### GNOME session did not start diff --git a/docs/skills/test-authoring/uefi-boot/SKILL.md b/docs/skills/test-authoring/uefi-boot/SKILL.md index aa2e06e5a..50b0ee003 100644 --- a/docs/skills/test-authoring/uefi-boot/SKILL.md +++ b/docs/skills/test-authoring/uefi-boot/SKILL.md @@ -105,7 +105,7 @@ This is the core mechanism that migration tests validate. - **Boot time is longer** — OVMF firmware initialization adds ~10-15s over direct kernel boot. The SSH wait deadline should be 600s for initial boot (vs 900s for direct boot, which needs extra time for different reasons). - **--bootloader flag requires bootc >= 0.1.13** — older images fail. Always probe `--help` before using. - **Service masking via kernel args is lost** — with direct boot, services are masked via `systemd.mask=...` in `-append`. With UEFI boot, masking must be done on-disk (symlink to `/dev/null` in the deployment's `/etc/systemd/system/`) — which `e2e.yml` already does. -- **selinux=0 kernel arg is lost** — must be set in BLS entries or on-disk config instead. For migration tests with SELinux enforcing (Epic E04), this is actually correct behavior. +- **SELinux stays enforcing** — `e2e.yml` no longer passes `selinux=0`, so direct and UEFI boot both run enforcing. Do not re-add the bypass in BLS entries or on-disk config; harness files are labeled before unmount instead. See [selinux-enforcing.md](../../ci-ops/e2e-workflow/references/selinux-enforcing.md). ## GRUB 2 vs systemd-boot Unified Virtualization Strategy diff --git a/scripts/selinux_collect_avc.sh b/scripts/selinux_collect_avc.sh new file mode 100755 index 000000000..5f9e54eb1 --- /dev/null +++ b/scripts/selinux_collect_avc.sh @@ -0,0 +1,17 @@ +#!/usr/bin/env bash +# Print every SELinux AVC record the e2e guest has logged, across all boots. +# +# Runs inside the guest as root (piped over SSH: `sudo bash -s < this`). +# The VM is disposable and fresh, so "all records" is exactly the +# qualification run, including any lifecycle reboot. Records reach +# different sinks depending on whether auditd runs, so read all of them; +# scripts/selinux_qualify.py de-duplicates by audit serial. +set -uo pipefail + +if command -v ausearch >/dev/null 2>&1 && [[ -s /var/log/audit/audit.log ]]; then + ausearch -m AVC,USER_AVC --raw 2>/dev/null || true +fi +# Without auditd, kernel AVCs land in the journal via kmsg and userspace +# USER_AVCs (dbus-broker, systemd) via syslog/audit transports. Read every +# boot the journal kept; `-k` would limit this to the current boot. +journalctl --no-pager -o cat 2>/dev/null | grep -F 'avc:' || true diff --git a/scripts/selinux_qualify.py b/scripts/selinux_qualify.py new file mode 100755 index 000000000..cac4ee344 --- /dev/null +++ b/scripts/selinux_qualify.py @@ -0,0 +1,331 @@ +#!/usr/bin/env python3 +"""SELinux qualification helpers for the e2e QEMU guest. + +The e2e workflow boots the candidate image with SELinux enforcing. These +helpers keep that honest: + +``expected-mode DEPLOY`` + Decide from the installed deployment whether enforcing is expected. + Any deployment that ships an SELinux policy store must run enforcing; + images without one (e.g. freedesktop-sdk based) report ``unsupported``. + +``unlabeled --root R [--exclude FILE] PATH...`` + List paths under PATH that carry no ``security.selinux`` xattr. Taken + once before the harness injects files (baseline: candidate-owned) and + once after, so only harness-created files get relabeled. + +``check-mode EXPECTED OBSERVED`` + Fail unless ``getenforce`` output matches the expected mode. + +``gate LOG --allowlist YAML --json OUT`` + Fail on enforced AVC denials that the allowlist does not name. + +``canary BEFORE AFTER --allowlist YAML --json OUT`` + Prove a deliberately denied operation shows up in the collected log + and makes ``gate`` fail. +""" +from __future__ import annotations + +import argparse +import json +import os +import re +import sys +from pathlib import Path + +SELINUX_XATTR = "security.selinux" +CANARY_TYPE = "httpd_t" + +_AUDIT_ID = re.compile(r"audit\((\d+\.\d+:\d+)\)") +_DENIED = re.compile(r"avc:\s+denied\s+\{\s*([^}]*?)\s*\}") +_FIELD = re.compile(r"\b(scontext|tcontext|tclass|permissive|comm)=(\"[^\"]*\"|\S+)") + + +# ── expected mode ──────────────────────────────────────────────────────────── + + +def read_selinux_config(deploy: Path) -> dict[str, str]: + config = deploy / "etc" / "selinux" / "config" + values: dict[str, str] = {} + if not config.is_file(): + return values + for line in config.read_text(encoding="utf-8", errors="replace").splitlines(): + line = line.strip() + if not line or line.startswith("#") or "=" not in line: + continue + key, _, value = line.partition("=") + values[key.strip()] = value.strip().strip('"') + return values + + +def expected_mode(deploy: Path) -> tuple[str, str]: + """Return (mode, policy). mode is ``enforcing`` or ``unsupported``. + + A shipped policy store means enforcing is required, even when the + candidate's config asks for permissive/disabled: that is a candidate + defect the runtime check must surface, not a reason to relax. + """ + config = read_selinux_config(deploy) + policy = config.get("SELINUXTYPE", "targeted") or "targeted" + contexts = deploy / "etc" / "selinux" / policy / "contexts" / "files" / "file_contexts" + if contexts.is_file(): + return "enforcing", policy + return "unsupported", "-" + + +# ── labeling ───────────────────────────────────────────────────────────────── + + +def has_label(path: str) -> bool: + try: + return bool(os.getxattr(path, SELINUX_XATTR, follow_symlinks=False)) + except OSError: + return False + + +def iter_tree(path: str): + if not os.path.lexists(path): + return + yield path + if os.path.isdir(path) and not os.path.islink(path): + for dirpath, dirnames, filenames in os.walk(path, followlinks=False): + for name in dirnames + filenames: + yield os.path.join(dirpath, name) + + +def unlabeled(root: str, paths: list[str], exclude: set[str]) -> list[str]: + root = root.rstrip("/") or "/" + found = set() + for top in paths: + if not (top == root or top.startswith(root + "/")): + raise ValueError(f"{top} is not under root {root}") + for path in iter_tree(top): + if path not in exclude and not has_label(path): + found.add(path) + return sorted(found) + + +# ── AVC parsing and gate ───────────────────────────────────────────────────── + + +def selinux_type(context: str) -> str: + parts = context.split(":") + return parts[2] if len(parts) >= 3 else context + + +def parse_denials(text: str) -> list[dict]: + denials: dict[str, dict] = {} + for line in text.splitlines(): + match = _DENIED.search(line) + if not match: + continue + fields = {k: v.strip('"') for k, v in _FIELD.findall(line[match.end():])} + if "scontext" not in fields or "tcontext" not in fields: + continue + audit_id = _AUDIT_ID.search(line) + denial = { + "audit_id": audit_id.group(1) if audit_id else "", + "permissions": sorted(match.group(1).split()), + "scontext": fields["scontext"], + "tcontext": fields["tcontext"], + "tclass": fields.get("tclass", ""), + "comm": fields.get("comm", ""), + "permissive": fields.get("permissive", "0") == "1", + } + # Records without an audit serial (journald's audit transport under + # `-o cat`) are keyed by their text, which carries a unique pid. + denial["key"] = "|".join( + [denial["audit_id"] or line.strip(), " ".join(denial["permissions"]), + denial["scontext"], denial["tcontext"], denial["tclass"]] + ) + denials.setdefault(denial["key"], denial) + return list(denials.values()) + + +def load_allowlist(path: Path) -> list[dict]: + import yaml + + data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + entries = data.get("allowed_denials") or [] + required = ("source_context", "target_context", "permission", "comm", "reason") + for index, entry in enumerate(entries): + missing = [key for key in required if not str(entry.get(key, "")).strip()] + if missing: + raise ValueError(f"allowlist entry {index} is missing {', '.join(missing)}") + return entries + + +def _perms(value) -> list[str]: + if isinstance(value, list): + return sorted(str(v) for v in value) + return sorted(str(value).split()) + + +def allowed_by(denial: dict, entries: list[dict]) -> dict | None: + for entry in entries: + if selinux_type(entry["source_context"]) != selinux_type(denial["scontext"]): + continue + if selinux_type(entry["target_context"]) != selinux_type(denial["tcontext"]): + continue + if _perms(entry["permission"]) != denial["permissions"]: + continue + if entry["comm"] != denial["comm"]: + continue + if entry.get("tclass") and entry["tclass"] != denial["tclass"]: + continue + return entry + return None + + +def evaluate(text: str, entries: list[dict]) -> dict: + unexpected, allowed, permissive = [], [], [] + for denial in parse_denials(text): + entry = allowed_by(denial, entries) + if entry is not None: + allowed.append({**denial, "reason": entry["reason"]}) + elif denial["permissive"]: + permissive.append(denial) + else: + unexpected.append(denial) + return { + "passed": not unexpected, + "unexpected": unexpected, + "allowed": allowed, + "permissive_domain": permissive, + } + + +def describe(denial: dict) -> str: + return ( + f"{{ {' '.join(denial['permissions'])} }} comm={denial['comm'] or '?'} " + f"{selinux_type(denial['scontext'])} -> {selinux_type(denial['tcontext'])}" + f":{denial['tclass']}" + ) + + +def canary_result(before: str, after: str, entries: list[dict]) -> dict: + seen = {d["key"] for d in parse_denials(before)} + new = [ + d + for d in parse_denials(after) + if d["key"] not in seen + and CANARY_TYPE in (selinux_type(d["scontext"]), selinux_type(d["tcontext"])) + ] + verdict = evaluate(after, entries) + detected = bool(new) and any(d in verdict["unexpected"] for d in new) + return {"detected": detected, "canary_denials": new, "gate_failed": not verdict["passed"]} + + +# ── CLI ────────────────────────────────────────────────────────────────────── + + +def _write_json(path: str | None, payload: dict) -> None: + if path: + Path(path).parent.mkdir(parents=True, exist_ok=True) + Path(path).write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + sub = parser.add_subparsers(dest="command", required=True) + + p = sub.add_parser("expected-mode") + p.add_argument("deploy", type=Path) + + p = sub.add_parser("unlabeled") + p.add_argument("--root", required=True) + p.add_argument("--exclude", type=Path) + p.add_argument("paths", nargs="+") + + p = sub.add_parser("check-mode") + p.add_argument("expected") + p.add_argument("observed") + + p = sub.add_parser("gate") + p.add_argument("log", type=Path) + p.add_argument("--allowlist", type=Path, required=True) + p.add_argument("--json") + + p = sub.add_parser("canary") + p.add_argument("before", type=Path) + p.add_argument("after", type=Path) + p.add_argument("--allowlist", type=Path, required=True) + p.add_argument("--json") + + args = parser.parse_args(argv) + + if args.command == "expected-mode": + mode, policy = expected_mode(args.deploy) + print(f"{mode} {policy}") + return 0 + + if args.command == "unlabeled": + exclude = set() + if args.exclude and args.exclude.is_file(): + exclude = set(args.exclude.read_text(encoding="utf-8").splitlines()) + try: + for path in unlabeled(args.root, args.paths, exclude): + print(path) + except ValueError as exc: + print(f"::error::{exc}", file=sys.stderr) + return 2 + return 0 + + if args.command == "check-mode": + observed = args.observed.strip() + if args.expected == "unsupported": + if observed == "Enforcing": + print("::error::image ships no SELinux policy store but the guest reports Enforcing") + return 1 + print(f"SELinux unsupported by this image (guest reports: {observed or 'no getenforce'})") + return 0 + if observed != "Enforcing": + print( + f"::error::SELinux must be Enforcing in the qualification VM; guest reports " + f"'{observed or 'nothing'}'. A candidate that ships a policy but boots " + "permissive or disabled fails qualification." + ) + return 1 + print("SELinux: Enforcing") + return 0 + + try: + entries = load_allowlist(args.allowlist) + except (OSError, ValueError) as exc: + print(f"::error::invalid SELinux allowlist: {exc}") + return 2 + + if args.command == "gate": + verdict = evaluate(args.log.read_text(encoding="utf-8", errors="replace"), entries) + _write_json(args.json, verdict) + for denial in verdict["allowed"]: + print(f"allowlisted: {describe(denial)} ({denial['reason']})") + for denial in verdict["permissive_domain"]: + print(f"::warning::AVC in permissive domain (not blocked): {describe(denial)}") + for denial in verdict["unexpected"]: + print(f"::error::unexpected SELinux denial: {describe(denial)}") + print( + f"AVC gate: {len(verdict['unexpected'])} unexpected, {len(verdict['allowed'])} " + f"allowlisted, {len(verdict['permissive_domain'])} permissive-domain" + ) + return 0 if verdict["passed"] else 1 + + result = canary_result( + args.before.read_text(encoding="utf-8", errors="replace"), + args.after.read_text(encoding="utf-8", errors="replace"), + entries, + ) + _write_json(args.json, result) + if not result["detected"]: + print( + f"::error::SELinux canary: a deliberately denied {CANARY_TYPE} operation did not " + "reach the AVC gate. Denial collection is broken, so a clean gate proves nothing." + ) + return 1 + for denial in result["canary_denials"]: + print(f"canary denial detected: {describe(denial)}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/selinux_allowlist.yaml b/selinux_allowlist.yaml index a481b8cf4..3123cadc3 100644 --- a/selinux_allowlist.yaml +++ b/selinux_allowlist.yaml @@ -9,9 +9,15 @@ # Format: # - source_context: the scontext from the AVC message # target_context: the tcontext from the AVC message -# permission: the denied permission(s) +# permission: the denied permission(s), space-separated, exact set # comm: the process comm field -# reason: why this denial is acceptable +# tclass: the target class (optional; narrows the match) +# reason: why this denial is acceptable (required) # upstream_bug: link to upstream tracker (if any) +# +# Contexts match on SELinux type only (e.g. xdm_t), so MLS ranges do not +# matter. The e2e SELinux denial gate (scripts/selinux_qualify.py) fails on +# any enforced denial without a matching entry. Prefer filing the denial in +# the owning image repo over adding an entry here. allowed_denials: [] diff --git a/tests/unit/test_selinux_qualify.py b/tests/unit/test_selinux_qualify.py new file mode 100644 index 000000000..fed8200df --- /dev/null +++ b/tests/unit/test_selinux_qualify.py @@ -0,0 +1,413 @@ +"""Unit tests for scripts/selinux_qualify.py and its e2e workflow wiring. + +The e2e VM boots enforcing (#1024). These tests lock in that the helpers +fail closed: a guest that is not enforcing, an unexpected denial, or a +collection path that cannot see a deliberate denial must all fail. +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path + +import pytest +import yaml + +ROOT = Path(__file__).resolve().parents[2] +sys.path.insert(0, str(ROOT)) +from scripts import selinux_qualify as sq # noqa: E402 + +SCRIPT = ROOT / "scripts" / "selinux_qualify.py" + +AUSEARCH_AVC = ( + 'type=AVC msg=audit(1761555000.101:412): avc: denied { read } for pid=812 ' + 'comm="gnome-shell" name="foo" dev="vda3" ino=42 ' + "scontext=unconfined_u:unconfined_r:xdm_t:s0-s0:c0.c1023 " + "tcontext=system_u:object_r:shadow_t:s0 tclass=file permissive=0" +) +KMSG_SAME_EVENT = ( + "audit: type=1400 audit(1761555000.101:412): avc: denied { read } for pid=812 " + 'comm="gnome-shell" name="foo" dev="vda3" ino=42 ' + "scontext=unconfined_u:unconfined_r:xdm_t:s0-s0:c0.c1023 " + "tcontext=system_u:object_r:shadow_t:s0 tclass=file permissive=0" +) +USER_AVC = ( + "type=USER_AVC msg=audit(1761555001.200:413): pid=700 uid=81 auid=4294967295 " + "ses=4294967295 subj=system_u:system_r:system_dbusd_t:s0 msg='avc: denied " + "{ send_msg } for msgtype=method_call interface=org.example.Foo member=Bar " + "dest=org.example spid=900 tpid=901 scontext=system_u:system_r:init_t:s0 " + "tcontext=system_u:system_r:colord_t:s0 tclass=dbus permissive=0 " + "exe=\"/usr/bin/dbus-broker\" sauid=81 hostname=? addr=? terminal=?'" +) +PERMISSIVE_AVC = ( + "type=AVC msg=audit(1761555002.300:414): avc: denied { getattr } for pid=9 " + 'comm="foo" scontext=system_u:system_r:foo_t:s0 ' + "tcontext=system_u:object_r:etc_t:s0 tclass=file permissive=1" +) +GRANTED = ( + "type=AVC msg=audit(1761555003.400:415): avc: granted { setsecparam } for pid=1 " + 'comm="load_policy" scontext=system_u:system_r:kernel_t:s0 ' + "tcontext=system_u:object_r:security_t:s0 tclass=security" +) +CANARY_AVC = ( + "audit: type=1400 audit(1761555100.500:900): avc: denied { entrypoint } for " + 'pid=1234 comm="(cat)" path="/usr/bin/cat" dev="vda3" ino=77 ' + "scontext=system_u:system_r:httpd_t:s0 tcontext=system_u:object_r:bin_t:s0 " + "tclass=file permissive=0" +) + +ALLOW_XDM_SHADOW = { + "source_context": "system_u:system_r:xdm_t:s0", + "target_context": "system_u:object_r:shadow_t:s0", + "permission": "read", + "comm": "gnome-shell", + "reason": "test fixture", +} + + +def _allowlist(tmp_path: Path, entries: list[dict]) -> Path: + path = tmp_path / "allow.yaml" + path.write_text(yaml.safe_dump({"allowed_denials": entries}), encoding="utf-8") + return path + + +def _run(*args: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, str(SCRIPT), *args], capture_output=True, text=True, check=False + ) + + +# ── expected mode ──────────────────────────────────────────────────────────── + + +def _deploy(tmp_path: Path, config: str | None, policy: str | None = "targeted") -> Path: + deploy = tmp_path / "deploy" + selinux = deploy / "etc" / "selinux" + selinux.mkdir(parents=True) + if config is not None: + (selinux / "config").write_text(config, encoding="utf-8") + if policy: + contexts = selinux / policy / "contexts" / "files" + contexts.mkdir(parents=True) + (contexts / "file_contexts").write_text("/.* system_u:object_r:default_t:s0\n") + return deploy + + +def test_policy_store_requires_enforcing(tmp_path): + deploy = _deploy(tmp_path, "SELINUX=enforcing\nSELINUXTYPE=targeted\n") + assert sq.expected_mode(deploy) == ("enforcing", "targeted") + + +def test_permissive_config_with_policy_still_requires_enforcing(tmp_path): + deploy = _deploy(tmp_path, "# comment\nSELINUX=permissive\nSELINUXTYPE=targeted\n") + assert sq.expected_mode(deploy) == ("enforcing", "targeted") + + +def test_policy_type_comes_from_config(tmp_path): + deploy = _deploy(tmp_path, 'SELINUX=enforcing\nSELINUXTYPE="mls"\n', policy="mls") + assert sq.expected_mode(deploy) == ("enforcing", "mls") + + +def test_image_without_policy_store_is_unsupported(tmp_path): + deploy = _deploy(tmp_path, None, policy=None) + assert sq.expected_mode(deploy) == ("unsupported", "-") + assert _run("expected-mode", str(deploy)).stdout.strip() == "unsupported -" + + +# ── check-mode ─────────────────────────────────────────────────────────────── + + +@pytest.mark.parametrize("observed", ["Permissive", "Disabled", "", "bash: getenforce: not found"]) +def test_check_mode_rejects_anything_but_enforcing(observed): + result = _run("check-mode", "enforcing", observed) + assert result.returncode == 1 + assert "::error::" in result.stdout + + +def test_check_mode_accepts_enforcing(): + assert _run("check-mode", "enforcing", "Enforcing\n").returncode == 0 + + +def test_check_mode_unsupported_is_reported_not_silent(): + result = _run("check-mode", "unsupported", "") + assert result.returncode == 0 + assert "unsupported" in result.stdout + + +def test_check_mode_unsupported_but_enforcing_is_inconsistent(): + assert _run("check-mode", "unsupported", "Enforcing").returncode == 1 + + +# ── unlabeled ──────────────────────────────────────────────────────────────── + + +def _labelled_tree(tmp_path: Path, monkeypatch, labelled: set[str]) -> Path: + root = tmp_path / "dep" + (root / "etc" / "ssh" / "sshd_config.d").mkdir(parents=True) + (root / "etc" / "passwd").write_text("root:x:0:0::/root:/bin/sh\n") + (root / "etc" / "ssh" / "sshd_config.d" / "00-ci-auth.conf").write_text("x\n") + (root / "etc" / "masked.service").symlink_to("/dev/null") + monkeypatch.setattr( + sq, "has_label", lambda path: str(Path(path).relative_to(root)) in labelled + ) + return root + + +def test_unlabeled_lists_new_files_and_symlinks_without_following(tmp_path, monkeypatch): + root = _labelled_tree(tmp_path, monkeypatch, {"etc", "etc/passwd", "etc/ssh"}) + found = sq.unlabeled(str(root), [str(root / "etc")], set()) + assert [str(Path(p).relative_to(root)) for p in found] == [ + "etc/masked.service", + "etc/ssh/sshd_config.d", + "etc/ssh/sshd_config.d/00-ci-auth.conf", + ] + + +def test_unlabeled_excludes_candidate_baseline(tmp_path, monkeypatch): + root = _labelled_tree(tmp_path, monkeypatch, {"etc", "etc/ssh"}) + baseline = {str(root / "etc" / "passwd")} + found = sq.unlabeled(str(root), [str(root / "etc")], baseline) + assert str(root / "etc" / "passwd") not in found + assert str(root / "etc" / "masked.service") in found + + +def test_unlabeled_rejects_paths_outside_root(tmp_path): + with pytest.raises(ValueError): + sq.unlabeled(str(tmp_path / "a"), [str(tmp_path / "b")], set()) + result = _run("unlabeled", "--root", str(tmp_path / "a"), str(tmp_path / "b")) + assert result.returncode == 2 + + +def test_unlabeled_missing_path_is_empty(tmp_path): + assert sq.unlabeled(str(tmp_path), [str(tmp_path / "absent")], set()) == [] + + +def test_has_label_false_for_missing_path(tmp_path): + assert sq.has_label(str(tmp_path / "missing")) is False + + +# ── parsing ────────────────────────────────────────────────────────────────── + + +def test_parse_ausearch_kmsg_and_user_avc(): + denials = sq.parse_denials("\n".join([AUSEARCH_AVC, USER_AVC, GRANTED, "noise"])) + assert len(denials) == 2 + kernel, user = denials + assert kernel["permissions"] == ["read"] + assert kernel["comm"] == "gnome-shell" + assert sq.selinux_type(kernel["scontext"]) == "xdm_t" + assert kernel["tclass"] == "file" + assert kernel["permissive"] is False + assert user["tclass"] == "dbus" + assert sq.selinux_type(user["tcontext"]) == "colord_t" + + +def test_same_event_from_two_sinks_counts_once(): + assert len(sq.parse_denials(f"{AUSEARCH_AVC}\n{KMSG_SAME_EVENT}\n")) == 1 + + +def test_records_without_audit_id_stay_distinct(): + a = "AVC avc: denied { read } for pid=1 comm=\"a\" scontext=s:r:a_t:s0 tcontext=s:r:b_t:s0 tclass=file permissive=0" + b = a.replace("pid=1", "pid=2") + assert len(sq.parse_denials(f"{a}\n{b}\n")) == 2 + + +# ── gate ───────────────────────────────────────────────────────────────────── + + +def test_gate_fails_on_unexpected_denial(tmp_path): + log = tmp_path / "avc.log" + log.write_text(AUSEARCH_AVC + "\n") + out = tmp_path / "verdict.json" + result = _run("gate", str(log), "--allowlist", str(_allowlist(tmp_path, [])), "--json", str(out)) + assert result.returncode == 1 + assert "unexpected SELinux denial" in result.stdout + assert json.loads(out.read_text())["passed"] is False + + +def test_gate_passes_clean_log(tmp_path): + log = tmp_path / "avc.log" + log.write_text(GRANTED + "\n") + allow = _allowlist(tmp_path, []) + assert _run("gate", str(log), "--allowlist", str(allow)).returncode == 0 + + +def test_gate_accepts_narrow_allowlist_match(tmp_path): + log = tmp_path / "avc.log" + log.write_text(AUSEARCH_AVC + "\n") + allow = _allowlist(tmp_path, [ALLOW_XDM_SHADOW]) + result = _run("gate", str(log), "--allowlist", str(allow)) + assert result.returncode == 0 + assert "allowlisted" in result.stdout + + +@pytest.mark.parametrize( + "override", + [ + {"comm": "gdm"}, + {"permission": "read write"}, + {"target_context": "system_u:object_r:etc_t:s0"}, + {"source_context": "system_u:system_r:init_t:s0"}, + {"tclass": "dir"}, + ], +) +def test_allowlist_does_not_widen(override): + entries = [{**ALLOW_XDM_SHADOW, **override}] + verdict = sq.evaluate(AUSEARCH_AVC, entries) + assert verdict["passed"] is False + + +def test_allowlist_entry_needs_reason(tmp_path): + entry = {**ALLOW_XDM_SHADOW, "reason": ""} + with pytest.raises(ValueError, match="reason"): + sq.load_allowlist(_allowlist(tmp_path, [entry])) + log = tmp_path / "avc.log" + log.write_text("") + assert _run("gate", str(log), "--allowlist", str(_allowlist(tmp_path, [entry]))).returncode == 2 + + +def test_permissive_domain_denial_is_reported_not_fatal(): + verdict = sq.evaluate(PERMISSIVE_AVC, []) + assert verdict["passed"] is True + assert len(verdict["permissive_domain"]) == 1 + + +def test_repository_allowlist_is_valid(): + sq.load_allowlist(ROOT / "selinux_allowlist.yaml") + + +# ── canary ─────────────────────────────────────────────────────────────────── + + +def test_canary_detected_when_new_denial_fails_gate(tmp_path): + before = tmp_path / "before.log" + after = tmp_path / "after.log" + before.write_text(GRANTED + "\n") + after.write_text(f"{GRANTED}\n{CANARY_AVC}\n") + out = tmp_path / "canary.json" + result = _run( + "canary", str(before), str(after), "--allowlist", str(_allowlist(tmp_path, [])), + "--json", str(out), + ) + assert result.returncode == 0, result.stdout + payload = json.loads(out.read_text()) + assert payload["detected"] is True + assert payload["gate_failed"] is True + + +def test_canary_missing_fails_closed(tmp_path): + before = tmp_path / "before.log" + before.write_text(AUSEARCH_AVC + "\n") + allow = _allowlist(tmp_path, []) + result = _run("canary", str(before), str(before), "--allowlist", str(allow)) + assert result.returncode == 1 + assert "did not reach the AVC gate" in result.stdout + + +def test_canary_already_present_before_does_not_count(): + assert sq.canary_result(CANARY_AVC, CANARY_AVC, [])["detected"] is False + + +def test_allowlisting_the_canary_breaks_detection(): + entry = { + "source_context": "system_u:system_r:httpd_t:s0", + "target_context": "system_u:object_r:bin_t:s0", + "permission": "entrypoint", + "comm": "(cat)", + "reason": "would hide the canary", + } + assert sq.canary_result("", CANARY_AVC, [entry])["detected"] is False + + +# ── workflow wiring ────────────────────────────────────────────────────────── + + +def _e2e() -> dict: + return yaml.safe_load((ROOT / ".github" / "workflows" / "e2e.yml").read_text()) + + +def _steps() -> dict[str, dict]: + return {step.get("name"): step for step in _e2e()["jobs"]["e2e"]["steps"]} + + +def test_guest_kernel_args_do_not_disable_selinux(): + install = _steps()["Install OCI image and configure disk"]["run"] + kernel_args = next(line for line in install.splitlines() if 'KERNEL_ARGS="root=' in line) + for arg in ("selinux=0", "enforcing=0", "security=none"): + assert arg not in kernel_args + # selinux=0 is only appended when enforcing mode was not opted into. + assert install.count("selinux=0") == 1 + guard = install.index('if [[ "${SELINUX_ENFORCING}" != "true" ]]; then') + assert guard < install.index('KERNEL_ARGS="${KERNEL_ARGS} selinux=0"') < install.index( + 'echo "KERNEL_ARGS=${KERNEL_ARGS}" >> "$GITHUB_ENV"' + ) + + +def test_enforcing_mode_is_opt_in_and_defaults_off(): + selinux_input = _e2e()[True]["workflow_call"]["inputs"]["selinux_enforcing"] + assert selinux_input["type"] == "boolean" + assert selinux_input["default"] is False + install_step = _steps()["Install OCI image and configure disk"] + assert "inputs.selinux_enforcing" in install_step["env"]["SELINUX_ENFORCING"] + install = install_step["run"] + opt_in = install.index('if [[ "${SELINUX_ENFORCING}" == "true" ]]; then') + assert opt_in < install.index("selinux_qualify.py expected-mode") < install.index('SELINUX_INFO="off none"') + assert _steps()["Verify SELinux enforcing"]["if"] == "env.SELINUX_EXPECTED != 'off'" + assert "env.SELINUX_EXPECTED == 'enforcing'" in _steps()["SELinux denial gate"]["if"] + + +def test_manual_dispatch_can_opt_into_enforcing(): + manual = yaml.safe_load((ROOT / ".github" / "workflows" / "manual.yml").read_text()) + assert manual[True]["workflow_dispatch"]["inputs"]["selinux_enforcing"]["default"] == "false" + passed = manual["jobs"]["test"]["with"]["selinux_enforcing"] + assert passed == "${{ github.event.inputs.selinux_enforcing == 'true' }}" + + +def test_sparse_checkout_ships_selinux_helpers(): + checkout = _steps()["Checkout testsuite"]["with"]["sparse-checkout"].split() + for path in ( + "scripts/selinux_qualify.py", + "scripts/selinux_collect_avc.sh", + "selinux_allowlist.yaml", + ): + assert path in checkout + assert (ROOT / path).exists() + + +def test_harness_files_are_labeled_before_unmount_with_candidate_setfiles(): + install = _steps()["Install OCI image and configure disk"]["run"] + baseline = install.index("baseline-unlabeled-var.txt") + first_injection = install.index('"${DEP}/etc/ssh/sshd_config.d/"') + labeling = install.index("setfiles -m -F -r") + umount = install.index("sudo umount /mnt/root") + last_injection = install.index('sudo cp /tmp/vm_key.pub "${DEP}/etc/ssh/ci-authorized-keys"') + assert baseline < first_injection < last_injection < labeling < umount + assert '"${IMAGE}" setfiles' in install + assert "--exclude" in install + assert "still unlabeled after setfiles" in install + + +def test_enforcing_verified_after_boot_and_after_suite(): + steps = list(_steps()) + verify = steps.index("Verify SELinux enforcing") + assert steps.index("Wait for SSH") < verify < steps.index("Run behave suite") + gate_index = steps.index("SELinux denial gate") + assert steps.index("Run behave suite") < gate_index + assert 'check-mode "${SELINUX_EXPECTED:-enforcing}"' in _steps()["Verify SELinux enforcing"]["run"] + gate = _steps()["SELinux denial gate"] + assert "always()" in gate["if"] + assert "check-mode enforcing" in gate["run"] + assert "ControlMaster=no" in gate["run"] + + +def test_gate_runs_canary_after_scenario_collection(): + gate = _steps()["SELinux denial gate"]["run"] + collect = gate.index("avc-scenario.log") + verdict = gate.index("selinux_qualify.py gate") + canary = gate.index("SELinuxContext=system_u:system_r:httpd_t:s0") + check = gate.index("selinux_qualify.py canary") + assert collect < verdict < canary < check + assert "StandardOutput=null" in gate + assert 'exit "${RC}"' in gate