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-srcor 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:Contexttrait,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. Submodulesmap/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),Valueenum,emit_config,conflicts.generate.rs— RULES (data),generate()dispatching togenerate_kconfigorgenerate_surgery,Report. Seeds traced modules=m; maps traced built-ins viakbuildand 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_unresolvedmanifest fields.trace.rs— ftracefunctiontracer capture (save→enable→sleep→stop→read tail→ always restore),parse_trace,resolve_modulesvia kallsyms[mod]tag.kbuild.rs— KbuildMakefile/Kbuildparser (obj-/core- suffixes, ifeq-on- CONFIG_ guards, subdirectory recursion) → object→CONFIG map; C column-0 definition scanner;function_configsmaps 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) beforeRUN --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-muslinside the--network=nonestep.ARG TARGETARCHcase (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) #
genis a reserved keyword in edition 2024 → the module is namedgenerate.- Submodules of
map.rslive insrc/src/map/, not besidemap.rs(caused a phantom E0583; rustc was stat'ingsrc/map/syscalls_*.rs). - flate2:
GzDecoderis inflate2::read,GzEncoderinflate2::write(not the crate root).Decompress::decompresstakesflate2::FlushDecompress::None, not a bool. matches!does not support pattern guards.- Declarative macros with a
literalfragment vs a literal identifier at the same position → "local ambiguity"; use explicit struct literals instead. - The
Contexttrait is implemented forResult<T, E>, not bare errors. UseErr(io_err).context(...)or?(there isFrom<std::io::Error> for CtxError). For a bare OS error, usectx_os_error(...). - kconfig
ValueisClonebut notCopy(owns aString) →.cloned(). - Heredoc-within-heredoc in bash breaks (the inner
EOFterminates the outer); write files with the edit tool or use distinct delimiters. - awk (mawk) cannot use
nameas 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— theonkeyword must be stripped before parsing the expression; usestrip_prefix("on ")(with the space) so a symbol namedon*is not mangled.- The resolver's select logic needs the reverse index (who selects this symbol),
not the symbol's own
selectslist. A select outranks dependencies, like the real kernel; a module selecting a bool yieldsy. 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
strhas norsplit_whitespace(verified with a standalone repro;split_whitespaceandrsplit(' ')exist). Workaround intrace.rs: rolling last-two-tokens scan. Do not callrsplit_whitespace. ends_with('.o')is a char-literal error (.ois 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 alreadyM), 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 frommtoy(the code ran from vmlinux, so it was built in). - The kallsyms
[mod]tag is the whole function→module mechanism. It surviveskptr_restrictzeroing 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 usersplit/rsplit_whitespaceon the whole file./proc/config.gzis a gzip container, not zlib/deflate. The old reader usedflate2::Decompress(raw/zlib) which silently fails on the gzip header and the running config is lost. Useflate2::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_STACKwasarches: &[](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) needarches: &["aarch64"]; the x86_64 trio (RANDOMIZE_MEMORY, LEGACY_VSYSCALL_NONE, X86_X32) needsarches: &["x86_64"].arch_guards_holdtest pins this. - On a kernel with no
CONFIG_MODULES(all built-in) there is no/proc/modules, and surgery mode prunes nothing (no=mto remove) — the diff is the hardening delta only. On a kernel with noCONFIG_TRACE_FSthere is no/sys/kernel/tracingand--traceproduces 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;generatesurgery mode prunes only=munloaded modules (verified: none of the removed symbols were=y, none were loaded modules);checkpasses 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 tonop. Surgery mode kept all traced modules (none removed); Kconfig mode (synthetic tree with Makefiles + C sources) producedDRM=m DRM_KMS_HELPER=m EXT4_FS=m KVM=m KVM_AMD=mfrom trace evidence and forced the mapped built-in's CONFIG on;traced_builtins_unmappedreported for the rest. make(docker) produces a staticout/kprune(2.1 MB, static-pie).- Remaining: Kconfig-mode e2e against a real kernel source tree (none on this
host;
~/Sources/lb-vanillais 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 testdoes not refreshtarget/debug/kprune; alwayscargo buildbefore 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 atfunction/on=1 until manually restored — always verifycurrent_tracer==nopafter a trace run. - Report files written via
2>filecontainresult::logstderr lines BEFORE the JSON; extract withsed -n '/^{/,$p' filebeforejson.load. /tmpis 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).