kprune AGENTS.md
13 kB 228 lines
Markdown
at main

AGENTS.md #

Dev log for kprune. Read this before working on the codebase; it records the decisions, the style conventions, and the gotchas already paid for.

What this is #

kprune is a standalone Rust package (no workspace) producing one static binary with three subcommands:

  • kprune collect — run as root on the live server; samples /proc and gathers evidence; optionally runs ftrace (--trace SECS) for execution evidence; writes a tar.gz manifest.
  • kprune generate — manifest → minimal hardened kernel .config, Kconfig mode with --kernel-src or surgery mode without. Traced modules seed =m; traced built-ins map to CONFIG symbols via the source tree (Kconfig mode).
  • kprune check — audit a config (or a manifest) against the hardening rules.

It is a spiritual successor to undertaker/tailor and kernel-hardening-checker. The ftrace approach mirrors tailor's strongest evidence (what actually executed), minus the SAT solver and kernel rebuild.

Repository layout #

Makefile            docker build wrapper; default target -> out/kprune
README.md           human documentation
src/Containerfile   build: locked pallet-rust, ADD src/ /src, FROM scratch final
src/Cargo.toml      package manifest (kprune 0.1.0, edition 2024)
src/Cargo.lock      lock file; --frozen/--locked builds need it beside the manifest
src/src/            all Rust sources
src/src/map/        generated syscall tables (syscalls_x86_64.rs, syscalls_aarch64.rs)
out/                docker build output (gitignored)

The crate lives in src/ (manifest src/Cargo.toml, sources src/src/) because the Containerfile ADDs only src/ into the build stage and the build runs cargo build --frozen. cargo at the repo root will not find the manifest; always use --manifest-path src/Cargo.toml (the Makefile does).

Module map #

  • main.rs — clap CLI, manifest/config loading (tar.gz/tar/json), subcommand dispatch.
  • result.rs — error handling: Context trait, CtxError, Result<T, E = CtxError>, ctx_os_error, warn, log, fatal. No anyhow.
  • json.rs — hand-rolled JSON (Value enum, parse, escape). No serde.
  • config.rs — kernel .config parse/emit, value accessors.
  • host.rs — uname via libc, /proc sampling (syscalls, wchans, stacks), kallsyms, cmdline, running config.
  • map.rs — const tables: MODULE_MAP, FS_MAP, CRYPTO_MAP, PROTO_MAP; symbol lookups; syscall name mapping. Submodules map/syscalls_{x86_64,aarch64}.rs.
  • kconfig/parse.rs — Kconfig parser: symbols, if/menu/choice blocks, source following (cycle-safe), expressions with =/!=/&&/||/!/parens.
  • kconfig/mod.rs — Resolver (fixpoint), Value enum, emit_config, conflicts.
  • generate.rs — RULES (data), generate() dispatching to generate_kconfig or generate_surgery, Report. Seeds traced modules =m; maps traced built-ins via kbuild and forces their CONFIGs on.
  • check.rs — check() audit, print().
  • collect.rs — evidence gathering, manifest assembly, tar/tar.gz writing. Optional ftrace block (trace_secs) → trace_entries/trace_modules/trace_builtins/ trace_unresolved manifest fields.
  • trace.rs — ftrace function tracer capture (save→enable→sleep→stop→read tail→ always restore), parse_trace, resolve_modules via kallsyms [mod] tag.
  • kbuild.rs — Kbuild Makefile/Kbuild parser (obj-/core- suffixes, ifeq-on- CONFIG_ guards, subdirectory recursion) → object→CONFIG map; C column-0 definition scanner; function_configs maps traced function names → the CONFIGs of their defining object.

Style (ryan's conventions, from nit/keyfork/icepick) #

  • No anyhow. Result<T, E = CtxError> with .context(format_args!(...)) for error context. ctx_os_error(format_args!(...)) for last-OS-error returns.
  • Lowercase, wry comments explaining why, not what.
  • format_args! for message construction.
  • impl AsRef<Path> for path parameters where it fits.
  • Minimal dependencies: libc, clap (derive, wrap_help), tar, flate2. That is the whole list. JSON and config parsing are hand-rolled.
  • edition 2024.
  • rustfmt defaults (no rustfmt.toml).

Containerfile / Makefile conventions (from nit/keyfork in stagex) #

  • FROM stagex/pallet-rust@sha256:... — locked digest, not a tag.
  • ADD src/ /src — only the source directory.
  • ENV RUSTFLAGS="-C target-feature=+crt-static" — static linking.
  • RUN cargo fetch (networked) before RUN --network=none — the offline build cannot download dependencies. This was a real break; do not "optimize it out".
  • cargo build --frozen --release --target "${TARGET}"-unknown-linux-musl inside the --network=none step.
  • ARG TARGETARCH case (amd64→x86_64, arm64→aarch64, else $(uname -m)).
  • mkdir -p /rootfs; install -Dm755 ... /rootfs/kprune.
  • FROM scratch AS package; COPY --from=build /rootfs/kprune /kprune.
  • Stage names capitalized (AS build, AS package) to avoid the FromAsCasing lint.
  • Makefile default target runs docker build --output type=local,rewrite-timestamp=true,dest=out -f src/Containerfile . → out/kprune.

Gotchas (already paid for, do not rediscover) #

  • gen is a reserved keyword in edition 2024 → the module is named generate.
  • Submodules of map.rs live in src/src/map/, not beside map.rs (caused a phantom E0583; rustc was stat'ing src/map/syscalls_*.rs).
  • flate2: GzDecoder is in flate2::read, GzEncoder in flate2::write (not the crate root). Decompress::decompress takes flate2::FlushDecompress::None, not a bool.
  • matches! does not support pattern guards.
  • Declarative macros with a literal fragment vs a literal identifier at the same position → "local ambiguity"; use explicit struct literals instead.
  • The Context trait is implemented for Result<T, E>, not bare errors. Use Err(io_err).context(...) or ? (there is From<std::io::Error> for CtxError). For a bare OS error, use ctx_os_error(...).
  • kconfig Value is Clone but not Copy (owns a String) → .cloned().
  • Heredoc-within-heredoc in bash breaks (the inner EOF terminates the outer); write files with the edit tool or use distinct delimiters.
  • awk (mawk) cannot use name as an array variable.
  • The Kconfig parser must treat tab-indented lines as option lines (real Kconfig uses tabs; a space-only check silently dropped every option).
  • depends on EXPR — the on keyword must be stripped before parsing the expression; use strip_prefix("on ") (with the space) so a symbol named on* is not mangled.
  • The resolver's select logic needs the reverse index (who selects this symbol), not the symbol's own selects list. A select outranks dependencies, like the real kernel; a module selecting a bool yields y.
  • conflicts() is keyed on the dependency check, not the final value: a forced symbol can be enabled while its dependencies are not, and that is exactly what should be reported.
  • This nightly's str has no rsplit_whitespace (verified with a standalone repro; split_whitespace and rsplit(' ') exist). Workaround in trace.rs: rolling last-two-tokens scan. Do not call rsplit_whitespace.
  • ends_with('.o') is a char-literal error (.o is two chars); use the string ".o". Same trap for any multi-char '.x'.
  • The C definition scanner (kbuild::c_functions) is a column-0 heuristic: a line with (, no ;/= before the first paren, whose signature (possibly multi-line, or a single-line ... ) { ... }) is followed by {. It over-reports (real definitions it should skip, and some callsites); that is fine because the result is intersected with the traced name set, which filters false positives. Do not "fix" it to be stricter than the traced-set intersection requires.
  • Evidence precedence (decided, bug-fixed): module evidence (loaded or traced ⇒ =m) outranks "in use" (mounted fs / registered crypto / proto ⇒ force on only if not already M), which outranks Kconfig defaults. Traced built-ins are mapped and forced after module seeding, so a builtin mapping can flip a traced module's symbol from m to y (the code ran from vmlinux, so it was built in).
  • The kallsyms [mod] tag is the whole function→module mechanism. It survives kptr_restrict zeroing the addresses, so no ELF parsing or new dependency is needed. Untagged functions are built-ins.
  • str::lines().collect::<Vec<&str>>() then index by line for the C scanner; do not use rsplit/rsplit_whitespace on the whole file.
  • /proc/config.gz is a gzip container, not zlib/deflate. The old reader used flate2::Decompress (raw/zlib) which silently fails on the gzip header and the running config is lost. Use flate2::read::GzDecoder. (/boot/config-* is plain text.) Verified live on a kernel with only IKCONFIG (no /boot config).
  • Hardening rules must carry the right arches. SHADOW_CALL_STACK was arches: &[] (all arches) and leaked into x86_64 configs even though it only exists in arm64's Kconfig. aarch64-only symbols (ARM64_BTI/PAC/MTE, SHADOW_CALL_STACK) need arches: &["aarch64"]; the x86_64 trio (RANDOMIZE_MEMORY, LEGACY_VSYSCALL_NONE, X86_X32) needs arches: &["x86_64"]. arch_guards_hold test pins this.
  • On a kernel with no CONFIG_MODULES (all built-in) there is no /proc/modules, and surgery mode prunes nothing (no =m to remove) — the diff is the hardening delta only. On a kernel with no CONFIG_TRACE_FS there is no /sys/kernel/tracing and --trace produces no evidence. Both are honest, best-effort degradations, not errors.

Data discipline #

Never fabricate kernel data. The syscall tables in src/src/map/ were generated from the real uapi headers /usr/include/{x86_64,aarch64}-linux-gnu/asm/unistd_64.h; regenerate from headers, do not hand-write. Module/fs/crypto/proto entries in map.rs must be real CONFIG symbols (caught and removed a hallucinated entry once; caught and fixed a BINfmt_MISC typo → BINFMT_MISC). Only modules with a known name are auto-pruned; unknowns are kept and reported. The kbuild.rs Makefile/C heuristics are approximations ($(filter), $(if), recursive $(MAKE) -C ignored; ifeq guards tracked only for CONFIG_ vars; C scanner is a column-0 heuristic). They must stay verified by the kbuild unit tests and the E2E before being trusted; an unmapped function is reported, never guessed.

Verification status #

  • cargo test --manifest-path src/Cargo.toml — 23 unit tests pass (json, config, host uname, map lookups, kconfig expr parsing, kconfig tree + resolver select/module-select/force-off/conflict, trace parse/resolve x3, kbuild obj-parse/c-scan/function-map x4).
  • E2E on a live x86_64 host (Debian 6.12): collect -s 5 → tar.gz; generate surgery mode prunes only =m unloaded modules (verified: none of the removed symbols were =y, none were loaded modules); check passes the generated config and correctly flags the running config's low-severity USER_NS/BPF_SYSCALL.
  • E2E Kconfig mode verified against a synthetic Kconfig tree (selects, choice defaults, module pruning, hardening forces all resolve correctly).
  • ftrace E2E (live, via sudo): collect -s 3 --trace 3 → ~72M entries, thousands of unique functions resolved to modules + built-ins, 0 unresolved; tracer verified restored to nop. Surgery mode kept all traced modules (none removed); Kconfig mode (synthetic tree with Makefiles + C sources) produced DRM=m DRM_KMS_HELPER=m EXT4_FS=m KVM=m KVM_AMD=m from trace evidence and forced the mapped built-in's CONFIG on; traced_builtins_unmapped reported for the rest.
  • make (docker) produces a static out/kprune (2.1 MB, static-pie).
  • Remaining: Kconfig-mode e2e against a real kernel source tree (none on this host; ~/Sources/lb-vanilla is not kernel source) to validate the built-in mapper at real scale; icepick not yet examined as a style reference.

Commands that work #

cargo build --manifest-path src/Cargo.toml
cargo test  --manifest-path src/Cargo.toml
cargo fmt   --manifest-path src/Cargo.toml
cargo generate-lockfile --manifest-path src/Cargo.toml
make                       # docker build -> out/kprune
strace -f -e trace=openat,statx <cmd>   # for module-resolution debugging

# ftrace E2E (the whole sequence in ONE sudo bash -c; cd into tracefs is root-only):
sudo bash -c 'cd /sys/kernel/tracing && ./kprune collect -s 3 --trace 3 -o /tmp/x.tar.gz'
# verify the tracer was restored (expect "nop"):
sudo bash -c 'cat /sys/kernel/tracing/current_tracer'

E2E gotchas (ftrace) #

  • cargo test does not refresh target/debug/kprune; always cargo build before running the E2E binary (hit: --trace "unexpected argument" from a stale bin).
  • The trace E2E needs the whole sequence in one sudo bash -c '...' (tracefs is 0700 root). A killed job once left the tracer at function/on=1 until manually restored — always verify current_tracer == nop after a trace run.
  • Report files written via 2>file contain result::log stderr lines BEFORE the JSON; extract with sed -n '/^{/,$p' file before json.load.
  • /tmp is cleaned between sessions; the synthetic Kconfig tree, kbuild fixture, and E2E artifacts must be recreated (the kbuild unit test recreates its own fixture at /tmp/kprune-kbuild-test).