Skip to content

kemu: seal private mappings and fix security audit findings - #11

Merged
losfair merged 6 commits into
losfair:mainfrom
CommaBot:fix/security-audit
Nov 18, 2026
Merged

losfair merged 6 commits into
losfair:mainfrom
CommaBot:fix/security-audit

Conversation

@CommaBot

@CommaBot CommaBot commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fix 15 security and correctness issues identified in a full-tree audit of kemu against Linux v6.18:

Critical & High

  • Seal private region mappings (VM_SEALED): Install [kemu-code], [kemu-table], [kemu-slots], and the [vdso] sigreturn trampoline with VM_SEALED once all four mappings are in place. Previously, a guest could split these VM_PFNMAP VMAs via mprotect/munmap/mmap(MAP_FIXED) so that kemu_zap_region() on fork() or kemu_reclaim() on chunk retirement failed to zap split sub-VMAs, leaving live Ring-3 PTEs pointing to freed kernel physical pages.
  • Gate enablement on required host CPU features & sync optional capabilities: Verify required x86-64-v3, CX16, FSGSBASE, AES, PCLMULQDQ, and XCR0 AVX state in kemu_init() before enabling binfmt_kemu (preventing Ring-0 #UD in try_cmpxchg128 or VEX-256 lowering on stripped CPUs/VMs). Pass AES/PCLMULQDQ/SHA_NI/RDRAND availability via cpu_feature_enabled() into kemu_core so clearcpuid= is respected and an absent RDRAND consistently clears HWCAP2_RNG, ID_AA64ISAR0_EL1.RNDR, and RNDR/RNDRRS.
  • Enforce host _PAGE_NX on guest VMAs & reject x86 emulate_vsyscall(): Mark guest mm_struct with kemu_guest in kemu_set_personality() (before any stack or ELF VMA is mapped) so vma_set_page_prot() strips host executability from every non-kemu-region VMA from creation (per DESIGN.md §6.1). Return false for kemu tasks in emulate_vsyscall() so jumping to the x86 legacy vsyscall gate raises SIGSEGV rather than running x86 syscall numbers under AUDIT_ARCH_AARCH64 seccomp filters.
  • Translator panic & overflow hardening: Gate kemu_core non-test builds with #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic)], remove unwrap() and unchecked Slow::push indexing in jit/t1/fp.rs, and build kemu_rs.o with -Coverflow-checks=no.

Medium & Low

  • sigaltstack minimum size: Enforce KEMU_MINSIGSTKSZ (5120 bytes) in kemu_sys_sigaltstack() so stacks between 2048 and 5119 bytes are rejected with -ENOMEM instead of underflowing on arm64 rt_sigframe delivery.
  • JIT cache invalidation, translation/unmap race & pending interpreter svc: Hook madvise(MADV_DONTNEED/MADV_FREE) and FOLL_FORCE writes (__access_remote_vm) on executable VMAs; avoid skipping invalidation when km->wide blocks exist; track atomic64_t unmap_seq before early returns in kemu_unmapped() to discard translations built concurrently with munmap; track KEMU_TF_PENDING_SVC so a guest svc retired by the interpreter fallback (or single-step/helper) still enters interp_svc across epoch changes (kemu.stress, sibling invalidations) and rewinds pc on signal materialization instead of being skipped.
  • Shared [kemu-slots] hardening: Recover raced cross-thread state-page divisors that raise #DE in translated div/idiv via exc_divide_error -> kemu_user_de() single-step interpretation (producing architectural AArch64 0 / INT_MIN without SIGFPE or leaking [kemu-code] addresses); clear reused slot return-stack pages; add READ_ONCE() on kt->cpu reads.
  • Memory accounting, tbi_pcs bounds & sysctls: Switch per-mm vzalloc and XArray/IDA/sigframe allocations to GFP_KERNEL_ACCOUNT; clear km->tbi_pcs on flush and range invalidation; register kernel.kemu.enabled and kernel.kemu.restrict sysctls.
  • Syscall, ptrace, TLS, TBI & kemu-user fixes: Reject x86-only MAP_32BIT, PR_GET_TSC/PR_SET_TSC, and PR_SET_SYSCALL_USER_DISPATCH; hide private mappings in query_matching_vma() (PROCMAP_QUERY) and numa_maps while reporting guest PC/SP in /proc/<pid>/stat and %p in debug signal logs; fix kemu_dup_mm() slot OOM return code (-ENOMEM); use pin_user_pages_fast() + conditional unpin_user_pages_dirty_lock() in kemu_cmpxchg128(); set KEMU_TF_KSTATE in kemu_gpr_set()/kemu_fpr_set() and propagate x0 into regs->ax for ptrace syscall-skip return injection; skip x86 set_new_tls() for CLONE_SETTLS with tagged TPIDR_EL0; untag RDX in TBI dc_zva(); harden tools/kemu-user ELF bounds and use MAP_FIXED_NOREPLACE.

Test Plan

  • cargo test (kemu_core + kemu-user), cargo clippy, and jit-test differential suites.
  • Clean patch application (scripts/apply.sh) and make LLVM=1 bzImage (CONFIG_KEMU=y) against pristine Linux v6.18.
  • Kernel regression tests (tests/kernel/kemu-sec.c and tests/kernel/divrace.c) and scripts/vm-smoke.sh (sysctl toggle).

CommaBot and others added 6 commits November 18, 2026 05:04
Address the critical and several high/medium audit findings in the core
per-mm region and task lifecycle:

- C-01: install [kemu-code]/[kemu-table]/[kemu-slots]/[vdso] and then seal
  them with VM_SEALED, so the guest can no longer munmap/mprotect/mremap or
  mmap-over and split a VMA. That split was what let fork's PTE copy and
  chunk reclaim leave live Ring-3 PTEs on freed pages (a physical-page UAF).
  Sealing is applied only after all four mappings exist, so the fail_unmap
  teardown (do_munmap) still works if an install fails midway.
- H-01: refuse to enable kemu unless the host CPU provides every feature the
  translator and glue emit unconditionally (x86-64-v3 + CX16/FSGSBASE +
  AES-NI/PCLMULQDQ), so translated code or LOCK CMPXCHG16B can never #UD in
  the kernel. Hand the optional features (AES/PCLMUL/SHA/RDRAND) to the Rust
  core via cpu_feature_enabled() so clearcpuid= is honoured, and mask
  HWCAP2_RNG without RDRAND.
- H-02a: strip host executability from guest VMAs. mm->kemu_guest is set in
  SET_PERSONALITY (before any stack/ELF VMA exists), so vma_set_page_prot()
  marks every guest mapping NX from birth -- no PTE is ever created
  host-executable. Guest code is only read for translation, never run
  natively; kemu's own region stays executable.
- M-03.3: clear a reused thread slot's return-stack pages.
- M-04: register kernel.kemu.{enabled,restrict}; account slot and
  chunk/table allocations (__vmalloc(GFP_KERNEL_ACCOUNT)); gate the
  translator on the init userns / CAP_SYS_ADMIN when restrict=1.
- M-02: an atomic64 unmap_seq, bumped before kemu_unmapped()'s own early
  returns, lets a concurrent translation detect a mapping teardown even
  before its block is indexed; don't early-return while a wide block exists.
- L-01: report the guest PC for /proc/<pid>/stat kstkeip.
- L-02: return -ENOMEM (not 0) when kemu_dup_mm() can't allocate the slot.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- M-02: discard a freshly translated block when unmap_seq advanced during
  translation (its instructions may be stale); the sequence is sampled under
  km->lock and re-checked after an smp_mb() so it can't miss an unmap whose
  invalidation already ran. Invalidate wide blocks; drop TBI hints for
  invalidated ranges.
- M-03.1: recover a host #DE in translated code (a raced cross-thread
  divisor) by running the one guest instruction in the interpreter, which
  yields the architectural AArch64 result (UDIV/0 = 0, SDIV INT_MIN/-1 =
  INT_MIN) instead of a SIGFPE that also leaks a code-cache address. The
  divide-error IDT hook lives in the regenerated patch set.
- M-03.2: READ_ONCE() the guest-writable state-page fields (pc, exit_info,
  svc pc) the kernel reads for control decisions.
- M-04: drop the TBI hint set on flush so it can't grow without bound;
  account the block-index allocations.
- Never skip a guest svc the interpreter retired. Since M-02 discards raced
  translations, the interpreter fallback often stops at an svc with pc
  already at svc + 4, expecting the interp_svc stub to perform it. An epoch
  change (a sibling invalidation, kemu.stress) or a pending signal on the
  way out redirected to dispatch instead, dropping the syscall with x0 still
  holding its first argument (glibc: "The futex facility returned an
  unexpected error code"). KEMU_TF_PENDING_SVC makes exit_to_user resume at
  interp_svc, and kemu_materialize() rewinds pc to restart the svc when a
  signal frame is built first, as for an interrupted svc stub. The helper
  and single-step paths use the same mechanism.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- M-01: wrap sigaltstack to require the arm64 minimum alternate-stack size
  (KEMU_MINSIGSTKSZ), rejecting 2048..5119-byte stacks the x86 entry point
  would accept and that would underflow on signal delivery.
- M-05: wrap mmap (reject x86-only MAP_32BIT) and prctl (reject PR_SET_TSC /
  PR_GET_TSC and PR_SET_SYSCALL_USER_DISPATCH, which would hijack kemu's own
  host syscall instructions).
- L-03: pin the cmpxchg16b target page (pin_user_pages_fast) and only mark
  it dirty when the exchange actually stored.
- L-04: after a tracer writes the guest GPRs/FP regs, mark the state page
  authoritative (KEMU_TF_KSTATE) and redirect so exit-to-user rebuilds the
  flags/MXCSR image and translated code reloads the registers; carry a
  tracer-injected x0 into the result register so a skipped syscall
  (NT_ARM_SYSTEM_CALL = -1) returns it instead of -ENOSYS.
- L-01: use %p rather than %px in the debug signal log.
- M-04: account the transient signal-frame allocations.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- H-01: the Rust core takes the optional host features (AES/PCLMUL/SHA from
  the kernel instead of a raw CPUID, and RDRAND) via kemu_rs_set_host_features;
  when the host has no RDRAND, ID_AA64ISAR0_EL1.RNDR is cleared and RNDR/RNDRRS
  trap as UNDEFINED, keeping the ID register, HWCAP2_RNG and the instruction
  consistent.
- L-05: DC ZVA honours TBI -- strip the address tag before the zeroing store
  in tagged mode, like every other data access. Adds a regression test.
- H-03: forbid clippy::{unwrap_used,expect_used,panic} outside the test build
  (a panic in the kernel core is a BUG()); make Slow::push bounds-checked;
  replace the infallible FP mask .try_into().unwrap()s; and build kemu_rs.o
  with -Coverflow-checks=no so two's-complement wrapping can't BUG() under
  CONFIG_RUST_OVERFLOW_CHECKS=y.
- L-06: bound the kemu-user ELF loader with checked arithmetic and slice
  gets, and reserve segment spans with MAP_FIXED_NOREPLACE.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Kernel-side hooks for the overlay changes, re-exported with
scripts/export-patches.sh (now also exporting mm/madvise.c):

- H-02a (0002): add mm_struct.kemu_guest, set early at exec, and strip host
  exec for guest VMAs in vma_set_page_prot().
- H-02b (0003): emulate_vsyscall() returns false for kemu tasks, so a forged
  return into the x86 vsyscall gate raises SIGSEGV instead of running an
  x86_64 syscall under AUDIT_ARCH_AARCH64 (seccomp confusion).
- L-05 (0005): skip set_new_tls() for kemu CLONE_SETTLS so a tagged guest
  TPIDR_EL0 is accepted.
- M-03.1 (0009): route a translated-code #DE through kemu_user_de().
- M-02 (0010): invalidate kemu translations on madvise(DONTNEED/FREE) and on
  FOLL_FORCE writes to executable mappings; strip host exec in
  vma_set_page_prot().
- L-01 (0011): hide the kemu region from numa_maps and skip it inside
  query_matching_vma() so a PROCMAP_QUERY COVERING_OR_NEXT scan keeps
  returning the real guest VMAs above it; report guest PC/SP in /proc stat.

Verified: scripts/apply.sh applies the series to a pristine linux-6.18 with
zero conflicts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
kemu-sec: sigaltstack minimum size; prctl/mmap rejects; CLONE_SETTLS with a
tagged TPIDR_EL0; DC ZVA through a tagged pointer; the kemu region hidden
from /proc maps and from a PROCMAP_QUERY COVERING_OR_NEXT scan that still
reaches the stack VMA; the sealed [vdso] rejecting mprotect/munmap; a
ptrace syscall-skip that injects a return value; and a getpid svc run from
freshly mapped pages while another thread churns mappings and a third
keeps signalling, which must never be skipped.
divrace: AArch64 division semantics (no trap) under multi-threaded flipping
of a divisor pinned to a memory-resident guest register.
vm-smoke.sh also toggles kernel.kemu.enabled.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@losfair
losfair merged commit 6bd4fa3 into losfair:main Nov 18, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants