kexec: Use BPF lskel to enable kexec to load PE format boot image
Subsystems (8)
v7 cover kexec: Use BPF lskel to enable kexec to load PE format boot image
*** The history ***
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/Image
For the first approach, I tried a purgatory-style emulator [1], but it encounters hardware scaling issues. For the second approach, both zboot-format [2] and UKI-format [3] parsers were rejected due to concerns that variant format parsers would bloat the kernel code. Additionally, for example in arm64, both UKI and zboot format parsers would need to be introduced and chained together to handle image loading. For the third approach, I attempted [4], but since zboot or UKI images already have signatures, upstream maintainers dislike the additional signature on the Image. Moreover, for secure boot UKI, this method cannot use signatures to protect the initramfs.
*** The approach in this series ***
This series introduces an approach that allows image formats to be parsed by BPF programs. Through BPF, two main functions, collecting kernel boot protocol data and decompression, are exposed to BPF programs via the commands KEXEC_BPF_CMD_DECOMPRESS and KEXEC_BPF_CMD_COPY. As a result, the kexec kernel code can remain relatively stable without requiring new parsers for different architectures.
Beside above, this approach redesigns kexec_file_load(): kernel_fd is used to pass the BPF parser, while initrd_fd can be used to carry everything else, the kernel image, initrd, and cmdline data. So we can avoid changing the kexe_file_load() protocol.
The main purpose of this series is to provide format flexibility. This is demonstrated by the patch 'tools/kexec: Introduce a bpf-prog to handle zboot image', where the BPF program works in conjunction with a private format defined in 'tools/kexec: Introduce a tool to build zboot envelope'.
*** Outlook for the security support (the next step) ***
The remaining issue in this series is the security support. The isolated bpf-prog can be signed as what is done on kernel module, and verified as the trusted root later.
Each signed PE can be asked to be verified by the trusted bpf-prog.
For IMA, an out-most bpf-parser will be introduced to read each file by kernel_read_file_from_path(..., READING_KEXEC_IMAGE).
*** Thanks ***
I would like to thank Philipp Rudo, whose insights inspired this approach and who dedicated significant time to evaluating its practicality. I am also grateful to Viktor Malik for his guidance on using BPF light skeleton to prevent malicious attacks from user space.
*** Test approach ***
-1. compile kexec-tools from https://github.com/pfliu/kexec-tools/tree/bpf_loader
-2. compile kernel
-3. For UKI, get the UKI parser bpf-prog by 'make -C tools/kexec uki',
there will be uki.bpf.
Load it by:
kexec -s -l uki.bpf image.uki
For zboot, get the zboot parser by 'make -C tools/kexec zboot' create the zboot envelop (packing vmlinuz.efi, initrd, cmdline) by:
tools/kexec/build_zboot_envelop vmlinuz.efi initrd "cmdline"
The default envelop image is named "zboot_image.elf" Load it by:
kexec -s -l zboot.bpf zboot_image.elf
[1]: https://lore.kernel.org/lkml/[email protected]/T/
[2]: https://lore.kernel.org/kexec/[email protected]/
[3]: https://lore.kernel.org/lkml/[email protected]/
[4]: https://lore.kernel.org/linux-efi/[email protected]/
*** Changes ***
v6 -> v7:
- Redesign the kexec_file_load interface to prevent BPF section injection into UKI or zboot images. The kernel_fd now carries the BPF parser, while initrd_fd carries the UKI image.
- Introduce a UKI image parser.
- Enhance the zboot parser to support both UKI and direct zboot images.
- Fix the bug reported by bot+bpf-ci
v5 -> v6
- Re-organize the layers in kexec_file_load into two layers: format-parsing and kernel boot protocol handling.
- Simplify the bpf kfunc interface.
- rebased onto Linux 6.19-rc2
v4 -> v5
- rebased onto Linux 6.17-rc2
- [1/12], use a separate CONFIG_KEEP_COMPRESSOR to decide the section of decompressor method
- [10/12], add Catalin's acked-by (Thanks Catalin!)
v3 -> v4
- Use dynamic allocator in decompression ([4/12])
- Fix issue caused by Identical Code Folding ([5/12])
- Integrate the image generator tool in the kernel tree ([11,12/12])
- Address the issue according to Philipp's comments in v3 reviewing. Thanks Philipp!
RFCv2 -> v3
- move the introduced bpf kfuncs to kernel/bpf/* and mark them sleepable
- use listener and publisher model to implement bpf_copy_to_kernel()
- keep each introduced kfunc under the control of memcg
RFCv1 -> RFCv2
- Use bpf kfunc instead of helper
- Use C source code to generate the light skeleton file
Pingfan Liu (13):
bpf: Introduce kfuncs to parser buffer content
kexec_file: Use bpf-prog to decompose image lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR
kexec_file: Implement decompress method for parser
kexec_file: Implement copy method for parser
kexec_file: Chain the stages into a pipeline
kexec_file: Introduce a bpf-prog lskel to run a format parser
kexec_file: Factor out routine to find a symbol in ELF
kexec_file: Integrate bpf light skeleton to load image with bpf-prog arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image tools/kexec: Introduce a bpf-prog to handle zboot image tools/kexec: Introduce a bpf-prog to handle UKI image tools/kexec: Introduce a tool to build zboot envelop
arch/arm64/Kconfig | 1 + include/linux/bpf.h | 20 + include/linux/decompress/mm.h | 8 + kernel/Kconfig.kexec | 8 + kernel/Makefile | 2 + kernel/bpf/Makefile | 3 + kernel/bpf/bpf_buffer_parser.c | 186 ++++ kernel/kexec_bpf/Makefile | 70 ++ kernel/kexec_bpf/kexec_pe_parser_bpf.c | 12 + kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 130 +++ kernel/kexec_bpf/template.c | 72 ++ kernel/kexec_bpf_loader.c | 873 +++++++++++++++++++ kernel/kexec_file.c | 104 ++- kernel/kexec_internal.h | 5 + lib/Kconfig | 6 + lib/decompress.c | 6 +- tools/kexec/Makefile | 203 +++++ tools/kexec/build_zboot_envelop.c | 362 ++++++++ tools/kexec/template.c | 72 ++ tools/kexec/uki_parser_bpf.c | 235 +++++ tools/kexec/zboot_envelop.h | 7 + tools/kexec/zboot_parser_bpf.c | 348 ++++++++ 22 files changed, 2719 insertions(+), 14 deletions(-) create mode 100644 kernel/bpf/bpf_buffer_parser.c create mode 100644 kernel/kexec_bpf/Makefile create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.c create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h create mode 100644 kernel/kexec_bpf/template.c create mode 100644 kernel/kexec_bpf_loader.c create mode 100644 tools/kexec/Makefile create mode 100644 tools/kexec/build_zboot_envelop.c create mode 100644 tools/kexec/template.c create mode 100644 tools/kexec/uki_parser_bpf.c create mode 100644 tools/kexec/zboot_envelop.h create mode 100644 tools/kexec/zboot_parser_bpf.c
Signature · 1 line
2.49.0
PATCH v7 1/13 bpf: Introduce kfuncs to parser buffer content
In the security kexec_file_load case, the buffer holding the kernel image should not be accessible from userspace.
Typically, BPF data flow occurs between user space and kernel space in either direction. However, the above case presents a unique scenario where the kernel, instead of a user task, reads data from a file, passes it to a BPF program for parsing, and finally stores the parsed result.
This requires a mechanism to channel the intermediate data from the BPF program directly to the kernel. BPF buffer parser kfuncs are introduced to serve this purpose:
BTF_ID_FLAGS(func, bpf_get_parser_context, KF_ACQUIRE | KF_RET_NULL) BTF_ID_FLAGS(func, bpf_put_parser_context, KF_RELEASE) BTF_ID_FLAGS(func, bpf_buffer_parser, KF_SLEEPABLE)
where bpf_get_parser_context() and bpf_put_parser_context() manage the trusted argument, and bpf_buffer_parser() forwards data to a callback that processes the structured buffer constructed by the BPF program.
--- include/linux/bpf.h | 20 ++++ kernel/bpf/Makefile | 3 + kernel/bpf/bpf_buffer_parser.c | 186 +++++++++++++++++++++++++++++++++ 3 files changed, 209 insertions(+) create mode 100644 kernel/bpf/bpf_buffer_parser.c
include/linux/bpf.h +20 -0
@@ -4005,4 +4005,24 @@ static inline int bpf_map_check_op_flags(struct bpf_map *map, u64 flags, u64 all return 0; } +struct bpf_parser_buf { +char *buf; +int size; +}; + +struct bpf_parser_context ; +typedef int (*bpf_parser_handler_t )(struct bpf_parser_context *ctx); + +struct bpf_parser_context { +struct kref ref; +struct hlist_node hash_node; +/* This callback should be sync so that @buf can be freed */ +bpf_parser_handler_t func; +struct bpf_parser_buf *buf; +void *data; +}; + +struct bpf_parser_context *alloc_bpf_parser_context (bpf_parser_handler_t func, +void *data); +void put_bpf_parser_context (struct bpf_parser_context *ctx);#endif /* _LINUX_BPF_H */
kernel/bpf/Makefile +3 -0
@@ -66,6 +66,9 @@ obj-$(CONFIG_BPF_SYSCALL) += kmem_cache_iter.o ifeq ($(CONFIG_DMA_SHARED_BUFFER),y) obj-$(CONFIG_BPF_SYSCALL) += dmabuf_iter.o endif +ifeq ($(CONFIG_KEXEC_BPF),y) +obj-$(CONFIG_BPF_SYSCALL) += bpf_buffer_parser.o +endif CFLAGS_REMOVE_percpu_freelist.o = $(CC_FLAGS_FTRACE) CFLAGS_REMOVE_bpf_lru_list.o = $(CC_FLAGS_FTRACE)
kernel/bpf/bpf_buffer_parser.c new file +186 -0
186 lines not on this page · raw message
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 01/13] bpf: Introduce kfuncs to parser buffer content
If release_bpf_parser_context() runs while bpf_buffer_parser() has stored the sentinel (void *)1 in ctx->buf via:
Quoted 5 lines
kernel/bpf/bpf_buffer_parser.c new file +0
-0
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 27
Quoted 8 lines
kernel/bpf/bpf_buffer_parser.c new file +8
-0+static void release_bpf_parser_context (struct kref *kref) +{ + struct bpf_parser_context *ctx = container_of(kref, struct bpf_parser_context, ref); + +if (ctx->buf) { +vfree (ctx->buf->buf); +kfree (ctx->buf); + }
If release_bpf_parser_context() runs while bpf_buffer_parser() has stored the sentinel (void *)1 in ctx->buf via:
old_val = cmpxchg(&context->buf, NULL, (void *)1);
then ctx->buf is non-NULL but not a valid struct bpf_parser_buf pointer, and vfree(ctx->buf->buf) will dereference address 1.
The BPF verifier prevents this today by holding the acquired reference across the kfunc call, but release_bpf_parser_context() has no awareness of the sentinel value. Would it be worth adding a check here to handle the sentinel, or using a separate flag/mutex instead of overloading ctx->buf?
[ ... ]
Quoted 3 lines
kernel/bpf/bpf_buffer_parser.c new file +3
-0+__bpf_kfunc int bpf_buffer_parser(char *buf, int buf_sz, +struct bpf_parser_context *context) +{
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 129
Quoted 2 lines
kernel/bpf/bpf_buffer_parser.c new file +2
-0+ ret =copy_from_kernel_nofault (b, buf, buf_sz); +if (!!ret) {
The !!ret is equivalent to just testing ret here. Was the double negation intentional?
Quoted 4 lines
kernel/bpf/bpf_buffer_parser.c new file +4
-0+ context->buf =NULL ; +vfree (b); +return ret; + }
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 163
Quoted 4 lines
kernel/bpf/bpf_buffer_parser.c new file +4
-0+static const struct btf_kfunc_id_set buffer_parser_kfunc_set = { + .owner =THIS_MODULE , + .set = &buffer_parser_ids, +};
These two lines use spaces for indentation instead of tabs.
kernel/bpf/bpf_buffer_parser.c
Quoted 2 lines
kernel/bpf/bpf_buffer_parser.c new file +2
-0+ +
There is a double blank line here.
Quoted 1 line
+BTF_ID_LIST(buffer_parser_dtor_ids)
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 181
Quoted 2 lines
kernel/bpf/bpf_buffer_parser.c new file +2
-0+ ret =register_btf_kfunc_id_set (BPF_PROG_TYPE_TRACING , &buffer_parser_kfunc_set); + return ret ?: register_btf_id_dtor_kfuncs(buffer_parser_dtors,
There is a double space before ret.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
[email protected]
AI reviewRe: [PATCHv7 01/13] bpf: Introduce kfuncs to parser buffer content
In reply to Pingfan LiuThank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider: - [Critical] `bpf_buffer_parser` enables a tracing program to alter the behavior of privileged operations…
Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:
- [Critical] bpf_buffer_parser enables a tracing program to alter the behavior of privileged operations without the KF_DESTRUCTIVE flag, bypassing Secure Boot and lockdown restrictions.
- [High] The bpf_buffer_parser kfunc lacks the mandatory __sz suffix for its size argument, preventing the BPF verifier from enforcing bounds checking and allowing arbitrary out-of-bounds kernel memory reads.
- [High] Context ID allocation uses raw memory addresses, allowing a BPF program to exploit an ABA vulnerability to hijack unrelated parser contexts.
- [High] The kfuncs bpf_get_parser_context and bpf_put_parser_context use a bare spin_lock() to protect the context hashmap, leading to deadlocks when called from BPF tracing programs executing in IRQ or NMI contexts.
- [High] BPF programs can asynchronously extend a parser context's lifetime beyond the kernel caller's underlying resources, causing context->func to trigger a Use-After-Free.
- [High] The release function for the parser context invokes vfree() and kfree(), which are unsafe and will crash when called from an atomic or NMI context.
- [Medium] Releasing the context->buf pseudo-lock uses a plain store, allowing memory reordering to cause data races.
--
--- Patch [1]: [PATCHv7 01/13] bpf: Introduce kfuncs to parser buffer content --- commit aad6827f1d21b01308897cd07d851cc0ef53ac1c
Author: Pingfan Liu <[email protected]>
bpf: Introduce kfuncs to parser buffer content
This patch introduces BPF buffer parser kfuncs to allow BPF programs to construct and pass structured buffers directly to kernel callbacks. It adds mechanisms for acquiring, releasing, and using a parser context within BPF tracing programs.
Quoted 6 lines
kernel/bpf/bpf_buffer_parser.c new file +0
-0@@ -0,0 +1,186 @@
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 27
Quoted 8 lines
kernel/bpf/bpf_buffer_parser.c new file +8
-0+static void release_bpf_parser_context (struct kref *kref) +{ + struct bpf_parser_context *ctx = container_of(kref, struct bpf_parser_context, ref); + +if (ctx->buf) { +vfree (ctx->buf->buf); +kfree (ctx->buf); + }
[Severity: High]
Can this trigger a crash if the last kref is put from an NMI or hardirq context?
Since BPF tracing programs can run in these contexts, dropping the last reference via bpf_put_parser_context() would synchronously call vfree() and kfree(), which sleep and are not NMI-safe.
Quoted 9 lines
kernel/bpf/bpf_buffer_parser.c new file +9
-0+spin_lock (&bpf_parser_context_lock); +hash_del (&ctx->hash_node); +spin_unlock (&bpf_parser_context_lock); +kfree (ctx); +} + +struct bpf_parser_context *alloc_bpf_parser_context (bpf_parser_handler_t func, +void *data) +{
kernel/bpf/bpf_buffer_parser.c line 46
Quoted 10 lines
kernel/bpf/bpf_buffer_parser.c new file +10
-0+struct bpf_parser_context *ctx; +unsigned int key; + + ctx =kzalloc (sizeof (*ctx),GFP_KERNEL ); +if (!ctx) +return NULL ; + ctx->func = func; + ctx->data = data; +kref_init (&ctx->ref); + key =bpf_parser_context_hash_key (ctx);
[Severity: High]
Does using the raw pointer address as the hash key introduce an ABA vulnerability?
If a context is freed and the SLUB allocator reuses the exact same memory address for a new context, could a BPF program holding the old ID unexpectedly hijack the new operation?
kernel/bpf/bpf_buffer_parser.c
Quoted 1 line
kernel/bpf/bpf_buffer_parser.c new file +1
-0+spin_lock (&bpf_parser_context_lock);
[Severity: High]
Does this risk a deadlock if an interrupt fires while this lock is held in process context?
If a BPF tracing program in the interrupt handler calls bpf_get_parser_context(), it will attempt to acquire this same bpf_parser_context_lock, which is a bare spin_lock() and does not disable interrupts.
Quoted 5 lines
kernel/bpf/bpf_buffer_parser.c new file +5
-0+hash_add (bpf_parser_context_map, &ctx->hash_node, key); +spin_unlock (&bpf_parser_context_lock); + +return ctx; +}
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 70
Quoted 10 lines
kernel/bpf/bpf_buffer_parser.c new file +10
-0+static struct bpf_parser_context *find_bpf_parser_context (unsigned long id) +{ +struct bpf_parser_context *ctx; +unsigned int key; +int cnt; + + key =bpf_parser_context_hash_key ((struct bpf_parser_context *)id); +spin_lock (&bpf_parser_context_lock); +hash_for_each_possible (bpf_parser_context_map, ctx, hash_node, key) { +if (ctx == (struct bpf_parser_context *)id) {
[Severity: High]
Is it safe to directly cast the user-provided integer id back to a struct bpf_parser_context pointer for comparison?
This seems to complete the ABA vector mentioned above, allowing direct access if the memory address happens to be reallocated for a new context.
Quoted 11 lines
kernel/bpf/bpf_buffer_parser.c new file +11
-0+ cnt =kref_get_unless_zero (&ctx->ref); +if (!cnt) + ctx =NULL ; +spin_unlock (&bpf_parser_context_lock); +return ctx; + } + } +spin_unlock (&bpf_parser_context_lock); + +return NULL ; +}
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 107
Quoted 3 lines
kernel/bpf/bpf_buffer_parser.c new file +3
-0+__bpf_kfunc int bpf_buffer_parser(char *buf, int buf_sz, +struct bpf_parser_context *context) +{
[Severity: High]
Does buf_sz need the __sz suffix in its name for the BPF verifier to enforce bounds checking?
Without the suffix, the verifier might treat the size parameter as an independent scalar. This could allow out-of-bounds kernel memory reads when the arbitrary size is later passed to copy_from_kernel_nofault().
Quoted 4 lines
kernel/bpf/bpf_buffer_parser.c new file +4
-0+struct bpf_parser_buf *parser_buf; +void *old_val; +int ret; +char *b;
[ ... ]
kernel/bpf/bpf_buffer_parser.c line 145
Quoted 5 lines
kernel/bpf/bpf_buffer_parser.c new file +5
-0+ parser_buf->buf = b; + parser_buf->size = buf_sz; + context->buf = parser_buf; +/* @func should be a sync call */ + ret = context->func (context);
[Severity: High]
Can context->func() trigger a use-after-free here?
If a BPF program acquires the context reference and sleeps, the original kernel caller might complete and free the underlying context->data. When bpf_buffer_parser() is eventually called, it would execute context->func on freed external data.
kernel/bpf/bpf_buffer_parser.c
Quoted 1 line
kernel/bpf/bpf_buffer_parser.c new file +1
-0+ context->buf =NULL ;
[Severity: Medium]
Should this be an smp_store_release()?
Using a plain store to release the context->buf lock might allow memory reordering, causing concurrent programs on weakly-ordered CPUs to observe incomplete memory writes.
kernel/bpf/bpf_buffer_parser.c line 157
Quoted 11 lines
kernel/bpf/bpf_buffer_parser.c new file +11
-0+vfree (b); +kfree (parser_buf); + +return ret; +} +__bpf_kfunc_end_defs (); + +BTF_KFUNCS_START(buffer_parser_ids) +BTF_ID_FLAGS(func, bpf_get_parser_context, KF_ACQUIRE | KF_RET_NULL) +BTF_ID_FLAGS(func, bpf_put_parser_context, KF_RELEASE) +BTF_ID_FLAGS(func, bpf_buffer_parser, KF_SLEEPABLE)
[Severity: Critical]
Does bpf_buffer_parser require the KF_DESTRUCTIVE flag?
Since this kfunc enables a tracing program to alter the behavior of privileged operations like kexec, omitting the flag might allow unprivileged tracing programs to bypass kernel lockdown and Secure Boot by covertly injecting malicious payloads.
Quoted 1 line
+BTF_KFUNCS_END(buffer_parser_ids)
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=1
PATCH v7 2/13 kexec_file: Use bpf-prog to decompose image
In reply to Pingfan LiuAs UEFI becomes popular, a few architectures support to boot a PE format kernel image directly. But the internal of PE format varies, which means each parser for each format.
This patch (with the rest in this series) introduces a common skeleton to all parsers, and leave the format parsing in
bpf-prog, so the kernel code can keep relative stable.
History, the syscall
SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
unsigned long, cmdline_len, const char __user *, cmdline_ptr, unsigned long, flags)
complies with the kernel protocol: bootable kernel, initramfs, cmdline.
But the occurrence of UKI images challenges the traditional model. The image itself contains the kernel, initrd, and cmdline. To be compatible with both the old and new models, kexec_file_load can be reorganized into two stages. In the first stage, "decompose_kexec_image()" breaks down the passed-in image into the components required by the kernel boot protocol. In the second stage, the traditional image loader "arch_kexec_kernel_image_load()" prepares the switch to the next kernel.
During the decomposition stage, the decomposition process can be nested. In each sub-process, BPF bytecode is extracted from the '.bpf' section to parse the current PE file. If the data section in the PE file contains another PE file, the sub-process is repeated. This is designed to handle the zboot format embedded in UKI format on the arm64 platform.
There are some placeholder functions in this patch. (They will take effect after the introduction of kexec BPF light skeleton and BPF helpers.)
--- kernel/Kconfig.kexec | 8 + kernel/Makefile | 1 + kernel/kexec_bpf_loader.c | 472 ++++++++++++++++++++++++++++++++++++++ kernel/kexec_file.c | 43 +++- kernel/kexec_internal.h | 4 + 5 files changed, 517 insertions(+), 11 deletions(-) create mode 100644 kernel/kexec_bpf_loader.c
kernel/Kconfig.kexec +8 -0
@@ -46,6 +46,14 @@ config KEXEC_FILE for kernel and initramfs as opposed to list of segments as accepted by kexec system call. +config KEXEC_BPF + bool "Enable bpf-prog to parse the kexec image" + depends on KEXEC_FILE + depends on DEBUG_INFO_BTF && BPF_SYSCALL + help + This is a feature to run bpf section inside a kexec image file, which + parses the image properly and help kernel set up kexec boot protocol + config KEXEC_SIG bool "Verify kernel signature during kexec_file_load() syscall" depends on ARCH_SUPPORTS_KEXEC_SIG
kernel/Makefile +1 -0
@@ -85,6 +85,7 @@ obj-$(CONFIG_CRASH_DUMP_KUNIT_TEST) += crash_core_test.o obj-$(CONFIG_KEXEC) += kexec.o obj-$(CONFIG_KEXEC_FILE) += kexec_file.o obj-$(CONFIG_KEXEC_ELF) += kexec_elf.o +obj-$(CONFIG_KEXEC_BPF) += kexec_bpf_loader.o obj-$(CONFIG_BACKTRACE_SELF_TEST) += backtracetest.o obj-$(CONFIG_COMPAT) += compat.o obj-$(CONFIG_CGROUPS) += cgroup/
kernel/kexec_bpf_loader.c new file +472 -0
472 lines not on this page · raw message
kernel/kexec_file.c +32 -11
83 lines not on this page · raw message
kernel/kexec_internal.h +4 -0
@@ -33,9 +33,13 @@ static inline void kexec_unlock(void)#ifdef CONFIG_KEXEC_FILE #include <linux/purgatory.h> + +/* Maximum size in bytes for kernel/initrd files. */ +#define KEXEC_FILE_SIZE_MAX min_t(s64, 4LL << 30, SSIZE_MAX)void kimage_file_post_load_cleanup (struct kimage *image);extern char kexec_purgatory[];extern size_t kexec_purgatory_size; +extern int decompose_kexec_image (struct kimage *image,int extended_fd);#else /* CONFIG_KEXEC_FILE */ static inline void kimage_file_post_load_cleanup (struct kimage *image) { }#endif /* CONFIG_KEXEC_FILE */
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 02/13] kexec_file: Use bpf-prog to decompose image
Are asm/image.h and asm/memory.h needed here? I could not find any symbols from either header used in this file. asm/image.h only exists for arm64, loongarch, and riscv, and asm/memory.h only for…
Quoted 5 lines
kernel/kexec_bpf_loader.c new file +0
-0
[ ... ]
kernel/kexec_bpf_loader.c line 24
Quoted 6 lines
kernel/kexec_bpf_loader.c new file +6
-0+#include <linux/bpf.h> +#include <linux/filter.h> +#include <asm/byteorder.h> +#include <asm/image.h> +#include <asm/memory.h> +#include "kexec_internal.h"
Are asm/image.h and asm/memory.h needed here? I could not find any symbols from either header used in this file. asm/image.h only exists for arm64, loongarch, and riscv, and asm/memory.h only for arm, arm64, and csky.
Since CONFIG_KEXEC_BPF has no architecture dependency, enabling it on x86 would cause a build failure from these missing headers.
[ ... ]
Quoted 3 lines
kernel/kexec_bpf_loader.c new file +3
-0+static int process_bpf_parsers_container (const char *elf_buf,size_t elf_sz, +struct kexec_context *context,int depth) +{
[ ... ]
Quoted 7 lines
kernel/kexec_bpf_loader.c new file +7
-0+/* +* Give the BPF prog a clean slate so context->parsed reliably +* reflects whether *this* invocation succeeded. +*/ + context->parsed = false; +/* This is the hook point for bpf-prog */ +kexec_image_parser_anchor (context, (unsigned long )bpf);
kernel/kexec_bpf_loader.c line 374
Quoted 10 lines
kernel/kexec_bpf_loader.c new file +10
-0+disarm_bpf_prog (); + +/* Free the old parsing context, and reload the new */ +for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (!!context->parsing_buf[i]) +break ; +vfree (context->parsing_buf[i]); + context->parsing_buf[i] =NULL ; + context->parsing_buf_sz[i] =0 ; + }
The comment says "free the old parsing context" but the condition appears inverted. !!context->parsing_buf[i] is true when the pointer is non-NULL, so the loop breaks at the first populated entry and only calls vfree() on NULL pointers (which is a no-op).
Should this be if (!context->parsing_buf[i]) instead?
[ ... ]
Quoted 6 lines
kernel/kexec_bpf_loader.c new file +6
-0+int decompose_kexec_image (struct kimage *image,int extended_fd) +{ +struct kexec_context ctx = {0 }; +unsigned long parser_sz; +char *parser_start; +int ret = -EINVAL ;
[ ... ]
Quoted 24 lines
kernel/kexec_bpf_loader.c new file +24
-0+if (!validate_elf_bpf_sections (parser_start, parser_sz)) { + + ret =kernel_read_file_from_fd (extended_fd, +0 , + (void **)&ctx.parsing_buf[0 ], +KEXEC_FILE_SIZE_MAX , +NULL , +0 ); +if (ret <0 ) { +pr_err ("Fail to read image container\n" ); +return -EINVAL ; + } + ctx.parsing_buf_sz[0 ] = ret; + ret =process_bpf_parsers_container (parser_start, parser_sz, &ctx,0 ); +if (!ret) { +char *p; + +/* Envelop should hold valid kernel, initrd, cmdline sections */ +if (!ctx.kernel || !ctx.initrd || !ctx.cmdline) { +vfree (ctx.kernel); +vfree (ctx.initrd); +vfree (ctx.cmdline); +return -EINVAL ; + }
[ ... ]
kernel/kexec_bpf_loader.c line 209
Quoted 6 lines
kernel/kexec_bpf_loader.c new file +6
-0+ } +return ret; + } + +return -EINVAL ; +}
When process_bpf_parsers_container() fails, or when the !ctx.kernel || !ctx.initrd || !ctx.cmdline check triggers, ctx.parsing_buf[0] was allocated by kernel_read_file_from_fd() but is never freed before returning. Does this leak the buffer?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
PATCH v7 3/13 lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR
In reply to Pingfan LiuThe KEXE PE format parser needs the kernel built-in decompressor to decompress the kernel image. So moving the decompressor out of __init sections.
--- include/linux/decompress/mm.h | 8 ++++++++ lib/Kconfig | 6 ++++++ lib/decompress.c | 6 +++--- 3 files changed, 17 insertions(+), 3 deletions(-)
include/linux/decompress/mm.h +8 -0
@@ -81,6 +81,7 @@ MALLOC_VISIBLE void free(void *where)#include <linux/string.h> #include <linux/slab.h> #include <linux/vmalloc.h> +#include <generated/autoconf.h> /* Use defines rather than static inline in order to avoid spurious * warnings when not needed (indeed large_malloc / large_free are not
@@ -92,7 +93,14 @@ MALLOC_VISIBLE void free(void *where)#define large_malloc (a) vmalloc(a)#define large_free (a) vfree(a) +#ifdef CONFIG_KEEP_DECOMPRESSOR +#define INIT +#define INITCONST +#else #define INIT __init +#define INITCONST __initconst +#endif +#define STATIC #include <linux/init.h>
lib/Kconfig +6 -0
@@ -165,6 +165,12 @@ config RANDOM32_SELFTEST # # compression support is select'ed if needed # +config KEEP_DECOMPRESSOR + bool "keeps the decompress routines after kernel initialization" + default n + help + This option keeps the decompress routines after kernel initialization + config 842_COMPRESS select CRC32 tristate
lib/decompress.c +3 -3
@@ -6,7 +6,7 @@*/ #include <linux/decompress/generic.h> - +#include <linux/decompress/mm.h> #include <linux/decompress/bunzip2.h> #include <linux/decompress/unlzma.h> #include <linux/decompress/unxz.h>
@@ -48,7 +48,7 @@ struct compress_format {decompress_fn decompressor; }; -static const struct compress_format compressed_formats[]__initconst = { +static const struct compress_format compressed_formats[] INITCONST = { { .magic = {0x1f ,0x8b }, .name ="gzip" , .decompressor = gunzip }, { .magic = {0x1f ,0x9e }, .name ="gzip" , .decompressor = gunzip }, { .magic = {0x42 ,0x5a }, .name ="bzip2" , .decompressor = bunzip2 },
@@ -60,7 +60,7 @@ static const struct compress_format compressed_formats[] __initconst = { {/* sentinel */ } }; -decompress_fn __init decompress_method (const unsigned char *inbuf,long len, +decompress_fn INIT decompress_method(const unsigned char *inbuf, long len,const char **name) {const struct compress_format *cf;
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 03/13] lib/decompress: Keep decompressor when CONFIG_KEEP_DECOMPRESSOR
The INITCONST macro is defined here in the kernel path (the #else branch of #ifdef STATIC), but the pre-boot path earlier in this header only defines INIT:
Quoted 4 lines
include/linux/decompress/mm.h +0
-0
[ ... ]
include/linux/decompress/mm.h MALLOC_VISIBLE void free(void *where) · line 102
Quoted 11 lines
include/linux/decompress/mm.h +6
-0@@ -92,7 +93,14 @@ MALLOC_VISIBLE void free(void *where)#define large_malloc (a) vmalloc(a)#define large_free (a) vfree(a) +#ifdef CONFIG_KEEP_DECOMPRESSOR +#define INIT +#define INITCONST +#else #define INIT __init +#define INITCONST __initconst +#endif
The INITCONST macro is defined here in the kernel path (the #else branch of #ifdef STATIC), but the pre-boot path earlier in this header only defines INIT:
include/linux/decompress/mm.h:
#ifdef STATIC
...
#define INITShould INITCONST also be defined in the pre-boot path for consistency? The individual decompressor files (decompress_inflate.c, decompress_bunzip2.c, etc.) all include this header and are compiled in both contexts. If any of them later uses INITCONST for a const array following the pattern in lib/decompress.c, the pre-boot build would fail with an undefined macro.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
PATCH v7 4/13 kexec_file: Implement decompress method for parser
In reply to Pingfan LiuOn arm64, there is no boot-time decompression for the kernel image. Therefore, when a compressed kernel image is loaded, it must be decompressed.
It is impractical to implement the complex decompression methods in BPF bytecode. However, decompression routines exist in the kernel. This patch bridges the compressed data with the kernel's decompression methods.
--- kernel/Kconfig.kexec | 2 +- kernel/kexec_bpf_loader.c | 236 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 237 insertions(+), 1 deletion(-)
kernel/Kconfig.kexec +1 -1
@@ -49,7 +49,7 @@ config KEXEC_FILE config KEXEC_BPF bool "Enable bpf-prog to parse the kexec image" depends on KEXEC_FILE - depends on DEBUG_INFO_BTF && BPF_SYSCALL + depends on DEBUG_INFO_BTF && BPF_SYSCALL && KEEP_DECOMPRESSOR help This is a feature to run bpf section inside a kexec image file, which parses the image properly and help kernel set up kexec boot protocol
kernel/kexec_bpf_loader.c +236 -0
250 lines not on this page · raw message
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 04/13] kexec_file: Implement decompress method for parser
Should this return ret instead of 0? When parser_cmd_decompress() fails, ret holds the error code, but the function discards it and returns success.
Quoted 4 lines
kernel/kexec_bpf_loader.c +0
-0
[ ... ]
Quoted 3 lines
kernel/kexec_bpf_loader.c +0
-0@@ -73,8 +74,243 @@ static int __init kexec_bpf_prog_run_init(void) }late_initcall (kexec_bpf_prog_run_init);
[ ... ]
Quoted 8 lines
static int
kexec_buff_parser(struct bpf_parser_context *parser){kernel/kexec_bpf_loader.c +6
-0+struct bpf_parser_buf *pbuf = parser->buf; +struct kexec_context *ctx = (struct kexec_context *)parser->data; +struct cmd_hdr *cmd = (struct cmd_hdr *)pbuf->buf; +char *decompressed_buf, *buf, *p; +unsigned long decompressed_sz; +int ret =0 ;
[ ... ]
Quoted 12 lines
kernel/kexec_bpf_loader.c +12
-0+case KEXEC_BPF_CMD_DECOMPRESS : + ret =parser_cmd_decompress (buf, cmd->payload_len, &decompressed_buf, + &decompressed_sz, ctx); +if (!ret) { +switch (cmd->subcmd) { +case KEXEC_BPF_SUBCMD_KERNEL : +vfree (ctx->kernel); + ctx->kernel = decompressed_buf; + ctx->kernel_sz = decompressed_sz; +break ; +default : +vfree (decompressed_buf);
kernel/kexec_bpf_loader.c static int __init kexec_bpf_prog_run_init(void) · line 315
Quoted 10 lines
kernel/kexec_bpf_loader.c +8
-0+break ; + } + } +break ; +default : +break ; + } +return 0 ; }
Should this return ret instead of 0? When parser_cmd_decompress() fails, ret holds the error code, but the function discards it and returns success.
bpf_buffer_parser() in bpf_buffer_parser.c propagates this return value back to the calling BPF program:
ret = context->func(context);
...
return ret;Returning 0 here means the BPF program sees success even when decompression failed. It would then proceed to send KEXEC_BPF_CMD_DONE, setting ctx->parsed = true, causing kexec to complete loading with a missing or undecompressed kernel image.
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
PATCH v7 5/13 kexec_file: Implement copy method for parser
In reply to Pingfan LiuCopying the bpf code parsing result to the proper place:image->kernel_buf, initrd_buf, cmdline_buf.
--- kernel/kexec_bpf_loader.c | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+)
kernel/kexec_bpf_loader.c +29 -0
@@ -78,6 +78,7 @@ late_initcall(kexec_bpf_prog_run_init);#define KEXEC_BPF_CMD_INVALID 0x0#define KEXEC_BPF_CMD_DONE 0x1#define KEXEC_BPF_CMD_DECOMPRESS 0x2 +#define KEXEC_BPF_CMD_COPY 0x3#define KEXEC_BPF_SUBCMD_INVALID 0x0#define KEXEC_BPF_SUBCMD_KERNEL 0x1
@@ -307,6 +308,34 @@ static int kexec_buff_parser(struct bpf_parser_context *parser) } }break ; +case KEXEC_BPF_CMD_COPY : + p =__vmalloc (cmd->payload_len,GFP_KERNEL | __GFP_ACCOUNT); +if (!p) +return -ENOMEM ; +memcpy (p, buf, cmd->payload_len); +switch (cmd->subcmd) { +case KEXEC_BPF_SUBCMD_KERNEL : +vfree (ctx->kernel); + ctx->kernel = p; + ctx->kernel_sz = cmd->payload_len; +break ; +/* Todo: allow the concatenation of multiple initrd */ +case KEXEC_BPF_SUBCMD_INITRD : +vfree (ctx->initrd); + ctx->initrd = p; + ctx->initrd_sz = cmd->payload_len; +break ; +/* Todo: allow the concatenation of multiple cmdline */ +case KEXEC_BPF_SUBCMD_CMDLINE : +vfree (ctx->cmdline); + ctx->cmdline = p; + ctx->cmdline_sz = cmd->payload_len; +break ; +default : +vfree (p); +break ; + } +break ;default :break ; }
Signature · 1 line
2.49.0
PATCH v7 6/13 kexec_file: Chain the stages into a pipeline
In reply to Pingfan LiuImages may consist of multiple layers, each with a distinct format. For example, an AArch64 UKI image typically embeds a zboot image in the .linux section. The parser therefore determines whether its output should be forwarded to the next stage.
Intermediate results are stored in next_parsing_buf and then promoted to parsing_buf for the subsequent stage.
--- kernel/kexec_bpf_loader.c | 47 ++++++++++++++++++++++++++++++++++++++- 1 file changed, 46 insertions(+), 1 deletion(-)
kernel/kexec_bpf_loader.c +46 -1
@@ -41,6 +41,8 @@ struct kexec_context {bool parsed;char *parsing_buf[MAX_PARSING_BUF_NUM ];unsigned long parsing_buf_sz[MAX_PARSING_BUF_NUM ]; +char *next_parsing_buf[MAX_PARSING_BUF_NUM ]; +unsigned long next_parsing_buf_sz[MAX_PARSING_BUF_NUM ];char *kernel;unsigned long kernel_sz;
@@ -278,8 +280,9 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)struct bpf_parser_buf *pbuf = parser->buf;struct kexec_context *ctx = (struct kexec_context *)parser->data;struct cmd_hdr *cmd = (struct cmd_hdr *)pbuf->buf; -char *decompressed_buf, *buf, *p; +char *decompressed_buf, *buf, *p, *pn;unsigned long decompressed_sz; +bool fill_pipeline = false;int ret =0 ; buf = pbuf->buf +sizeof (struct cmd_hdr );
@@ -288,6 +291,7 @@ static int kexec_buff_parser(struct bpf_parser_context *parser) cmd->payload_len, pbuf->size);return -EINVAL ; } + fill_pipeline = cmd->pipeline_flag &KEXEC_BPF_PIPELINE_FILL ;switch (cmd->cmd) {case KEXEC_BPF_CMD_DONE : ctx->parsed = true;
@@ -301,6 +305,23 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)vfree (ctx->kernel); ctx->kernel = decompressed_buf; ctx->kernel_sz = decompressed_sz; +if (fill_pipeline) { +int i; + +for (i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (ctx->next_parsing_buf[i]) +continue ; + ctx->next_parsing_buf[i] = decompressed_buf; + ctx->next_parsing_buf_sz[i] = decompressed_sz; +break ; + } +/* No enough parsing slot */ +if (i ==MAX_PARSING_BUF_NUM ) { + ctx->kernel =NULL ; +vfree (decompressed_buf); +return -ENOMEM ; + } + }break ;default :vfree (decompressed_buf);
@@ -313,6 +334,22 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)if (!p)return -ENOMEM ;memcpy (p, buf, cmd->payload_len); +if (fill_pipeline) { + pn =__vmalloc (cmd->payload_len,GFP_KERNEL | __GFP_ACCOUNT); +if (!pn) { +vfree (p); +return -ENOMEM ; + } +memcpy (pn, buf, cmd->payload_len); +for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (!ctx->next_parsing_buf[i]) { + ctx->next_parsing_buf[i] = pn; + ctx->next_parsing_buf_sz[i] = cmd->payload_len; +break ; + } + } + } +switch (cmd->subcmd) {case KEXEC_BPF_SUBCMD_KERNEL :vfree (ctx->kernel);
@@ -637,6 +674,14 @@ static int process_bpf_parsers_container(const char *elf_buf, size_t elf_sz, context->parsing_buf[i] =NULL ; context->parsing_buf_sz[i] =0 ; } +for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (!context->next_parsing_buf[i]) +break ; + context->parsing_buf[i] = context->next_parsing_buf[i]; + context->parsing_buf_sz[i] = context->next_parsing_buf_sz[i]; + context->next_parsing_buf[i] =NULL ; + context->next_parsing_buf_sz[i] =0 ; + }put_bpf_parser_context (bpf);/* If the bpf-prog success, it flags by KEXEC_BPF_CMD_DONE */
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 06/13] kexec_file: Chain the stages into a pipeline
After this, both ctx->kernel and ctx->next_parsing_buf[i] point to the same decompressed_buf allocation. When next_parsing_buf is later promoted to parsing_buf in process_bpf_parsers_container()…
Quoted 4 lines
kernel/kexec_bpf_loader.c +0
-0
[ ... ]
Quoted 4 lines
kernel/kexec_bpf_loader.c +0
-0@@ -301,6 +305,23 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)vfree (ctx->kernel); ctx->kernel = decompressed_buf; ctx->kernel_sz = decompressed_sz;
kernel/kexec_bpf_loader.c static int kexec_buff_parser(struct bpf_parser_context *parser) · line 317
Quoted 10 lines
kernel/kexec_bpf_loader.c +10
-0+if (fill_pipeline) { +int i; + +for (i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (ctx->next_parsing_buf[i]) +continue ; + ctx->next_parsing_buf[i] = decompressed_buf; + ctx->next_parsing_buf_sz[i] = decompressed_sz; +break ; + }
After this, both ctx->kernel and ctx->next_parsing_buf[i] point to the same decompressed_buf allocation. When next_parsing_buf is later promoted to parsing_buf in process_bpf_parsers_container(), there are two independent references to the same memory.
If the next BPF stage issues another KEXEC_BPF_CMD_DECOMPRESS for KEXEC_BPF_SUBCMD_KERNEL, vfree(ctx->kernel) frees the buffer while parsing_buf[i] still references it.
The KEXEC_BPF_CMD_COPY path avoids this by allocating a separate copy with __vmalloc(). Should the DECOMPRESS path do the same to prevent aliased ownership?
Quoted 8 lines
kernel/kexec_bpf_loader.c +7
-0+/* No enough parsing slot */ +if (i ==MAX_PARSING_BUF_NUM ) { + ctx->kernel =NULL ; +vfree (decompressed_buf); +return -ENOMEM ; + } + }break ;
[ ... ]
Quoted 9 lines
kernel/kexec_bpf_loader.c +5
-0@@ -313,6 +334,22 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)if (!p)return -ENOMEM ;memcpy (p, buf, cmd->payload_len); +if (fill_pipeline) { + pn =__vmalloc (cmd->payload_len,GFP_KERNEL | __GFP_ACCOUNT); +if (!pn) { +vfree (p); +return -ENOMEM ;
kernel/kexec_bpf_loader.c static int kexec_buff_parser(struct bpf_parser_context *parser) · line 351
Quoted 10 lines
kernel/kexec_bpf_loader.c +10
-0+ } +memcpy (pn, buf, cmd->payload_len); +for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (!ctx->next_parsing_buf[i]) { + ctx->next_parsing_buf[i] = pn; + ctx->next_parsing_buf_sz[i] = cmd->payload_len; +break ; + } + } + }
If all MAX_PARSING_BUF_NUM slots are already occupied, the loop completes without storing pn anywhere, and the allocation is leaked.
The DECOMPRESS path handles this case with an explicit check:
if (i == MAX_PARSING_BUF_NUM) {
ctx->kernel = NULL;
vfree(decompressed_buf);
return -ENOMEM;
}Is a similar overflow check missing here for the COPY path?
[ ... ]
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
[email protected]
AI reviewRe: [PATCHv7 06/13] kexec_file: Chain the stages into a pipeline
In reply to Pingfan LiuThank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 7 potential issue(s) to consider:
New issues:
- [High] Aliasing ctx->kernel and ctx->next_parsing_buf in KEXEC_BPF_CMD_DECOMPRESS leads to a Use-After-Free.
- [Medium] Memory leak of newly allocated buffer 'pn' in KEXEC_BPF_CMD_COPY when the pipeline array is full.
Pre-existing issues:
- [Critical] The BPF container decomposition stage completely bypasses KEXEC signature verification.
- [Critical] The bpf_buffer_parser kfunc lacks the required __sz suffix on its size argument, defeating the BPF verifier.
- [High] Memory leak of parsing buffers due to a double-negation logic error (!!context->parsing_buf[i]).
- [High] Severe memory leak of kexec_context dynamically allocated components on error and success paths.
- [High] vfree() is improperly used on memory allocated by kernel_read_file_from_fd().
--
--- Patch [6]: [PATCHv7 06/13] kexec_file: Chain the stages into a pipeline --- commit 8070ede2f761980c4a2de11a2d72fb8a5309bc74
Author: Pingfan Liu <[email protected]>
kexec_file: Chain the stages into a pipeline
This commit enables kexec stages to be chained into a pipeline. It promotes intermediate outputs from next_parsing_buf to parsing_buf for the subsequent BPF parsing stages. It also allows multiple layers with distinct formats to be parsed sequentially.
Quoted 4 lines
kernel/kexec_bpf_loader.c +0
-0
[ ... ]
Quoted 4 lines
kernel/kexec_bpf_loader.c +0
-0@@ -301,6 +305,23 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)vfree (ctx->kernel); ctx->kernel = decompressed_buf; ctx->kernel_sz = decompressed_sz;
kernel/kexec_bpf_loader.c static int kexec_buff_parser(struct bpf_parser_context *parser) · line 317
Quoted 10 lines
kernel/kexec_bpf_loader.c +10
-0+if (fill_pipeline) { +int i; + +for (i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (ctx->next_parsing_buf[i]) +continue ; + ctx->next_parsing_buf[i] = decompressed_buf; + ctx->next_parsing_buf_sz[i] = decompressed_sz; +break ; + }
[Severity: High]
Does this aliasing of decompressed_buf create a use-after-free risk?
If a nested BPF program parses a sub-kernel and issues another KEXEC_BPF_SUBCMD_KERNEL command, kexec_buff_parser() will unconditionally call vfree(ctx->kernel):
kexec_buff_parser()
case KEXEC_BPF_SUBCMD_KERNEL:
vfree(ctx->kernel);
Since ctx->kernel and ctx->next_parsing_buf[i] point to the exact same buffer, wouldn't this free the memory that the nested parser is actively reading from?
Quoted 8 lines
kernel/kexec_bpf_loader.c +7
-0+/* No enough parsing slot */ +if (i ==MAX_PARSING_BUF_NUM ) { + ctx->kernel =NULL ; +vfree (decompressed_buf); +return -ENOMEM ; + } + }break ;
[ ... ]
Quoted 9 lines
kernel/kexec_bpf_loader.c +5
-0@@ -313,6 +334,22 @@ static int kexec_buff_parser(struct bpf_parser_context *parser)if (!p)return -ENOMEM ;memcpy (p, buf, cmd->payload_len); +if (fill_pipeline) { + pn =__vmalloc (cmd->payload_len,GFP_KERNEL | __GFP_ACCOUNT); +if (!pn) { +vfree (p); +return -ENOMEM ;
kernel/kexec_bpf_loader.c static int kexec_buff_parser(struct bpf_parser_context *parser) · line 351
Quoted 10 lines
kernel/kexec_bpf_loader.c +10
-0+ } +memcpy (pn, buf, cmd->payload_len); +for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (!ctx->next_parsing_buf[i]) { + ctx->next_parsing_buf[i] = pn; + ctx->next_parsing_buf_sz[i] = cmd->payload_len; +break ; + } + } + }
[Severity: Medium]
If the pipeline array is fully exhausted and ctx->next_parsing_buf has no empty slots, the loop will complete without storing pn. Is there a missing check after the loop to free pn when it cannot be stored?
[ ... ]
kernel/kexec_bpf_loader.c static int process_bpf_parsers_container(const char *elf_buf, size_t elf_sz, · line 678
Quoted 6 lines
kernel/kexec_bpf_loader.c +0
-0@@ -637,6 +674,14 @@ static int process_bpf_parsers_container(const char *elf_buf, size_t elf_sz,/* Free the old parsing context, and reload the new */ for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) {if (!!context->parsing_buf[i])break ;vfree (context->parsing_buf[i]);
[Severity: High]
This is a pre-existing issue, but does this double negation logic incorrectly skip cleanup?
Because !!context->parsing_buf[i] evaluates to true for any non-NULL pointer, the loop will immediately break instead of freeing valid buffers.
[Severity: High]
This is a pre-existing issue, but is it safe to use vfree() here?
Since these buffers are originally populated by kernel_read_file_from_fd() which uses kvmalloc(), shouldn't kvfree() be used to avoid panics on kmalloc'd memory?
kernel/kexec_bpf_loader.c static int process_bpf_parsers_container(const char *elf_buf, size_t elf_sz, · line 680
Quoted 7 lines
kernel/kexec_bpf_loader.c +4
-0context->parsing_buf[i] =NULL ; context->parsing_buf_sz[i] =0 ; } +for (int i =0 ; i <MAX_PARSING_BUF_NUM ; i++) { +if (!context->next_parsing_buf[i]) +break ; + context->parsing_buf[i] = context->next_parsing_buf[i];
While reviewing this patch, I noticed a few pre-existing issues in other related areas:
kernel/kexec_bpf_loader.c:decompose_kexec_image() {
...
ret = process_bpf_parsers_container(parser_start, parser_sz, &ctx, 0);
if (!ret) {
...
vfree(ctx.cmdline);
}
return ret;
}[Severity: High]
This is a pre-existing issue, but does this function leak memory on the error path?
If process_bpf_parsers_container() returns an error, the function exits directly and returns ret without freeing ctx.kernel, ctx.initrd, ctx.cmdline, or the array of buffers in ctx.parsing_buf allocated by kernel_read_file_from_fd().
Also, on the success path (!ret), the ctx.parsing_buf array appears to be permanently leaked as well.
kernel/kexec_file.c:kimage_file_prepare_segments() {
...
if (IS_ENABLED(CONFIG_KEXEC_BPF)) {
/* Fill up image's kernel_buf, initrd_buf, cmdline_buf */
ret = decompose_kexec_image(image, initrd_fd);
switch (ret) {
case 0:
envelop = true;
...
#ifdef CONFIG_KEXEC_SIG
if (!envelop) {
ret = kimage_validate_signature(image);
if (ret)
goto out;
}#endif
...
}
[Severity: Critical]
This is a pre-existing issue, but doesn't skipping signature validation when envelop is true create a security regression?
If decompose_kexec_image() successfully extracts the kernel/initrd from a container via unverified BPF programs, could an attacker load an unsigned, untrusted kernel simply by wrapping it in an ELF container, completely defeating kernel signature enforcement and Lockdown?
kernel/bpf/bpf_buffer_parser.c:bpf_buffer_parser() {
...__bpf_kfunc int bpf_buffer_parser(char *buf, int buf_sz,
struct bpf_parser_context *context)
{
...
}
[Severity: Critical]
This is a pre-existing issue, but does the size parameter need the __sz suffix to be properly verified?
Because the parameter is named buf_sz instead of buf__sz, the BPF verifier treats it as a standard scalar and won't enforce bounds checking between the pointer and the size. Could an unprivileged BPF program supply a small valid pointer and an arbitrarily large buf_sz to cause an out-of-bounds read?
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=6
PATCH v7 7/13 kexec_file: Introduce a bpf-prog lskel to run a format parser
In reply to Pingfan LiuAnalague to kernel/bpf/preload/iterators/Makefile,
this Makefile is not invoked by the Kbuild system. It needs to be invoked manually when kexec_pe_parser_bpf.c is changed so that kexec_pe_parser_bpf.lskel.h can be re-generated by the command "bpftool gen skeleton -L kexec_pe_parser_bpf.o".
kexec_pe_parser_bpf.lskel.h is used directly by the kernel kexec code in later patch. For this patch, there are bpf bytecode contained in opts_data[] and opts_insn[] in kexec_pe_parser_bpf.lskel.h, but in the following patch, they will be removed and only the function API in kexec_pe_parser_bpf.lskel.h left.
As exposed in kexec_pe_parser_bpf.lskel.h, the interface between bpf-prog and the kernel are constituted by:
four maps:
struct bpf_map_desc ringbuf_1;
struct bpf_map_desc ringbuf_2;
struct bpf_map_desc ringbuf_3;
struct bpf_map_desc ringbuf_4;
four sections:
struct bpf_map_desc rodata;
struct bpf_map_desc data;
struct bpf_map_desc rodata_str1_1;
struct bpf_map_desc bss;one prog:
SEC("fentry.s/kexec_image_parser_anchor")
The interface of maps and sections are extracted in template.c, which should be included by any bpf-prog to interact with kexec bpf component
--- kernel/kexec_bpf/Makefile | 62 ++++ kernel/kexec_bpf/kexec_pe_parser_bpf.c | 12 + kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 371 +++++++++++++++++++ kernel/kexec_bpf/template.c | 72 ++++ 4 files changed, 517 insertions(+) create mode 100644 kernel/kexec_bpf/Makefile create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.c create mode 100644 kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h create mode 100644 kernel/kexec_bpf/template.c
kernel/kexec_bpf/Makefile new file +62 -0
@@ -0,0 +1,62 @@ +# SPDX-License-Identifier: GPL-2.0 +OUTPUT := .output +CLANG ?= clang +LLC ?= llc +LLVM_STRIP ?= llvm-strip +DEFAULT_BPFTOOL := $(OUTPUT)/sbin/bpftool +BPFTOOL ?= $(DEFAULT_BPFTOOL) +LIBBPF_SRC := $(abspath ../../tools/lib/bpf) +BPFOBJ := $(OUTPUT)/libbpf.a +BPF_INCLUDE := $(OUTPUT) +INCLUDES := -I$(OUTPUT) -I$(BPF_INCLUDE) -I$(abspath ../../tools/lib) \ + -I$(abspath ../../tools/include/uapi) +CFLAGS := -g -Wall + +srctree := $(patsubst %/kernel/kexec_bpf,%,$(CURDIR)) +VMLINUX = $(srctree)/vmlinux + +abs_out := $(abspath $(OUTPUT)) +ifeq ($(V),1) +Q = +msg = +else +Q = @ +msg = @printf ' %-8s %s%s\n' "$(1)" "$(notdir $(2))" "$(if $(3), $(3))"; +MAKEFLAGS += --no-print-directory +submake_extras := feature_display=0 +endif + +.DELETE_ON_ERROR: + +.PHONY: all clean + +all: $(OUTPUT) kexec_pe_parser_bpf.lskel.h + +clean: + $(call msg,CLEAN) + $(Q)rm -rf $(OUTPUT) kexec_pe_parser_bpf.lskel.h + +kexec_pe_parser_bpf.lskel.h: $(OUTPUT)/kexec_pe_parser_bpf.o | $(BPFTOOL) + $(call msg,GEN-SKEL,$@) + $(Q)$(BPFTOOL) gen skeleton -L $< > $@ + +$(OUTPUT)/vmlinux.h: $(VMLINUX) $(DEFAULT_BPFTOOL) $(BPFOBJ) | $(OUTPUT) + @$(BPFTOOL) btf dump file $(VMLINUX) format c > $(OUTPUT)/vmlinux.h + +$(OUTPUT)/kexec_pe_parser_bpf.o: kexec_pe_parser_bpf.c $(OUTPUT)/vmlinux.h $(BPFOBJ) | $(OUTPUT) + $(call msg,BPF,$@) + $(Q)$(CLANG) -g -O2 -target bpf $(INCLUDES) \ + -c $(filter %.c,$^) -o $@ && \ + $(LLVM_STRIP) -g $@ + +$(OUTPUT): + $(call msg,MKDIR,$@) + $(Q)mkdir -p $(OUTPUT) + +$(BPFOBJ): $(wildcard $(LIBBPF_SRC)/*.[ch] $(LIBBPF_SRC)/Makefile) | $(OUTPUT) + $(Q)$(MAKE) $(submake_extras) -C $(LIBBPF_SRC) \ + OUTPUT=$(abspath $(dir $@))/ $(abspath $@) + +$(DEFAULT_BPFTOOL): + $(Q)$(MAKE) $(submake_extras) -C ../../tools/bpf/bpftool \ + prefix= OUTPUT=$(abs_out)/ DESTDIR=$(abs_out) install
kernel/kexec_bpf/kexec_pe_parser_bpf.c new file +12 -0
@@ -0,0 +1,12 @@ +// SPDX-License-Identifier: GPL-2.0 +// +// Copyright (C) 2025, 2026 Red Hat, Inc + +#include "template.c" + +SEC("fentry.s/kexec_image_parser_anchor") +__attribute__((used))int BPF_PROG (parse_pe ,struct kexec_context *context, +unsigned long parser_id) +{ +return 0 ; +}
kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h new file +371 -0
371 lines not on this page · raw message
kernel/kexec_bpf/template.c new file +72 -0
72 lines not on this page · raw message
Signature · 1 line
2.49.0
PATCH v7 8/13 kexec_file: Factor out routine to find a symbol in ELF
In reply to Pingfan LiuThe routine to search a symbol in ELF can be shared, so split it out.
--- kernel/kexec_file.c | 61 +++++++++++++++++++++++++++++++++++++++++ kernel/kexec_internal.h | 1 + 2 files changed, 62 insertions(+)
kernel/kexec_file.c +61 -0
@@ -902,6 +902,51 @@ static int kexec_calculate_store_digests(struct kimage *image)return ret; } +#if defined(CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY ) || defined(CONFIG_KEXEC_BPF ) +const Elf_Sym *elf_find_symbol (const Elf_Ehdr *ehdr,const char *name) +{ +const Elf_Shdr *sechdrs; +const Elf_Sym *syms; +const char *strtab; +int i, k; + + sechdrs = (void *)ehdr + ehdr->e_shoff; + +for (i =0 ; i < ehdr->e_shnum; i++) { +if (sechdrs[i].sh_type !=SHT_SYMTAB ) +continue ; + +if (sechdrs[i].sh_link >= ehdr->e_shnum) +/* Invalid strtab section number */ +continue ; + strtab = (void *)ehdr + sechdrs[sechdrs[i].sh_link].sh_offset; + syms = (void *)ehdr + sechdrs[i].sh_offset; + +/* Go through symbols for a match */ +for (k =0 ; k < sechdrs[i].sh_size/sizeof (Elf_Sym); k++) { +if (ELF_ST_BIND (syms[k].st_info) !=STB_GLOBAL ) +continue ; + +if (strcmp (strtab + syms[k].st_name, name) !=0 ) +continue ; + +if (syms[k].st_shndx ==SHN_UNDEF || + syms[k].st_shndx >= ehdr->e_shnum) { +pr_debug ("Symbol: %s has bad section index %d.\n" , + name, syms[k].st_shndx); +return NULL ; + } + +/* Found the symbol we are looking for */ +return &syms[k]; + } + } + +return NULL ; +} + +#endif +#ifdef CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY /* * kexec_purgatory_find_symbol - find a symbol in the purgatory
@@ -1221,6 +1266,22 @@ int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf)return ret; } +/* +* kexec_purgatory_find_symbol - find a symbol in the purgatory +* @pi: Purgatory to search in. +* @name: Name of the symbol. +* +* Return: pointer to symbol in read-only symtab on success, NULL on error. +*/ +static const Elf_Sym *kexec_purgatory_find_symbol (struct purgatory_info *pi, +const char *name) +{ +if (!pi->ehdr) +return NULL ; + +return elf_find_symbol (pi->ehdr, name); +} +void *kexec_purgatory_get_symbol_addr (struct kimage *image,const char *name) {struct purgatory_info *pi = &image->purgatory_info;
kernel/kexec_internal.h +1 -0
@@ -40,6 +40,7 @@ void kimage_file_post_load_cleanup(struct kimage *image);extern char kexec_purgatory[];extern size_t kexec_purgatory_size;extern int decompose_kexec_image (struct kimage *image,int extended_fd); +extern const Elf_Sym *elf_find_symbol (const Elf_Ehdr *ehdr,const char *name);#else /* CONFIG_KEXEC_FILE */ static inline void kimage_file_post_load_cleanup (struct kimage *image) { }#endif /* CONFIG_KEXEC_FILE */
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 08/13] kexec_file: Factor out routine to find a symbol in ELF
This adds a new wrapper kexec_purgatory_find_symbol() here, but the original full implementation of kexec_purgatory_find_symbol() earlier in the file was not removed:
Quoted 3 lines
kernel/kexec_file.c +0
-0
[ ... ]
Quoted 9 lines
kernel/kexec_file.c +5
-0@@ -1221,6 +1266,22 @@ int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf)return ret; } +/* +* kexec_purgatory_find_symbol - find a symbol in the purgatory +* @pi: Purgatory to search in. +* @name: Name of the symbol. +*
kernel/kexec_file.c int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf) · line 1283
Quoted 10 lines
kernel/kexec_file.c +10
-0+* Return: pointer to symbol in read-only symtab on success, NULL on error. +*/ +static const Elf_Sym *kexec_purgatory_find_symbol (struct purgatory_info *pi, +const char *name) +{ +if (!pi->ehdr) +return NULL ; + +return elf_find_symbol (pi->ehdr, name); +}
This adds a new wrapper kexec_purgatory_find_symbol() here, but the original full implementation of kexec_purgatory_find_symbol() earlier in the file was not removed:
kernel/kexec_file.c:kexec_purgatory_find_symbol() {
...
ehdr = pi->ehdr;
sechdrs = (void *)ehdr + ehdr->e_shoff;
for (i = 0; i < ehdr->e_shnum; i++) {
...
}
return NULL;
}Both definitions are static and live inside the same #ifdef CONFIG_ARCH_SUPPORTS_KEXEC_PURGATORY block, so this will fail to compile on any architecture that selects that config (x86, s390, powerpc, riscv).
It looks like the old function body should have been replaced with the new elf_find_symbol() wrapper, as was done in v5 of this series. Was the deletion of the old body lost during a rebase?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
kernel test robot
build botRe: [PATCHv7 08/13] kexec_file: Factor out routine to find a symbol in ELF
In reply to Pingfan Liukernel test robot noticed the following build errors:
Hi Pingfan,
kernel test robot noticed the following build errors:
[auto build test ERROR on bpf-next/net]
[also build test ERROR on bpf-next/master bpf/master akpm-mm/mm-nonmm-unstable linus/master v7.0-rc5 next-20260320] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Pingfan-Liu/bpf-Introduce-kfuncs-to-parser-buffer-content/20260323-084500 base: https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git net patch link: https://lore.kernel.org/r/20260322014402.8815-9-piliu%40redhat.com patch subject: [PATCHv7 08/13] kexec_file: Factor out routine to find a symbol in ELF config: x86_64-kexec (https://download.01.org/0day-ci/archive/20260323/[email protected]/config) compiler: clang version 20.1.8 (https://github.com/llvm/llvm-project 87f0227cb60147a26a1eeb4fb06e3b505e9c7261) reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260323/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> kernel/kexec_file.c:1276:23: error: redefinition of 'kexec_purgatory_find_symbol'
1276 | static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
| ^
kernel/kexec_file.c:958:23: note: previous definition is here
958 | static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
| ^
1 error generated.
vim +/kexec_purgatory_find_symbol +1276 kernel/kexec_file.c
1268
1269 /*
1270 * kexec_purgatory_find_symbol - find a symbol in the purgatory
1271 * @pi: Purgatory to search in.
1272 * @name: Name of the symbol.
1273 *
1274 * Return: pointer to symbol in read-only symtab on success, NULL on error.
1275 */
> 1276 static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
1277 const char *name)
1278 {
1279 if (!pi->ehdr)
1280 return NULL;
1281
1282 return elf_find_symbol(pi->ehdr, name);
1283 }
1284
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
kernel test robot
build botRe: [PATCHv7 08/13] kexec_file: Factor out routine to find a symbol in ELF
In reply to Pingfan Liukernel test robot noticed the following build errors:
Hi Pingfan,
kernel test robot noticed the following build errors:
[auto build test ERROR on bpf-next/net]
[also build test ERROR on bpf-next/master bpf/master akpm-mm/mm-nonmm-unstable linus/master v7.0-rc5 next-20260320] [If your patch is applied to the wrong git tree, kindly drop us a note.
And when submitting patch, we suggest to use '--base' as documented in
https://git-scm.com/docs/git-format-patch#_base_tree_information]
url: https://github.com/intel-lab-lkp/linux/commits/Pingfan-Liu/bpf-Introduce-kfuncs-to-parser-buffer-content/20260323-084500 base: https://git.kernel.org/pub/scm/linux/kernel/git/bpf/bpf-next.git net patch link: https://lore.kernel.org/r/20260322014402.8815-9-piliu%40redhat.com patch subject: [PATCHv7 08/13] kexec_file: Factor out routine to find a symbol in ELF config: x86_64-randconfig-002-20260323 (https://download.01.org/0day-ci/archive/20260323/[email protected]/config) compiler: gcc-14 (Debian 14.2.0-19) 14.2.0 reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20260323/[email protected]/reproduce)
If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/
All errors (new ones prefixed by >>):
>> kernel/kexec_file.c:1276:23: error: redefinition of 'kexec_purgatory_find_symbol'
1276 | static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
kernel/kexec_file.c:958:23: note: previous definition of 'kexec_purgatory_find_symbol' with type 'const Elf64_Sym *(struct purgatory_info *, const char *)' {aka 'const struct elf64_sym *(struct purgatory_info *, const char *)'}
958 | static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~
vim +/kexec_purgatory_find_symbol +1276 kernel/kexec_file.c
1268
1269 /*
1270 * kexec_purgatory_find_symbol - find a symbol in the purgatory
1271 * @pi: Purgatory to search in.
1272 * @name: Name of the symbol.
1273 *
1274 * Return: pointer to symbol in read-only symtab on success, NULL on error.
1275 */
> 1276 static const Elf_Sym *kexec_purgatory_find_symbol(struct purgatory_info *pi,
1277 const char *name)
1278 {
1279 if (!pi->ehdr)
1280 return NULL;
1281
1282 return elf_find_symbol(pi->ehdr, name);
1283 }
1284
Signature · 2 lines
0-DAY CI Kernel Test Service https://github.com/intel/lkp-tests/wiki
PATCH v7 9/13 kexec_file: Integrate bpf light skeleton to load image with bpf-prog
In reply to Pingfan LiuAll kexec PE bpf prog should align with the interface exposed by the light skeleton
four maps:
struct bpf_map_desc ringbuf_1;
struct bpf_map_desc ringbuf_2;
struct bpf_map_desc ringbuf_3;
struct bpf_map_desc ringbuf_4;
four sections:
struct bpf_map_desc rodata;
struct bpf_map_desc data;
struct bpf_map_desc rodata_str1_1;
struct bpf_map_desc bss;
one prog:
SEC("fentry.s/kexec_image_parser_anchor")With the above presumption, the integration consists of two parts:
-1. Call API exposed by light skeleton from kexec
-2. The opts_insn[] and opts_data[] are bpf-prog dependent and
can be extracted and passed in from the user space. In the kexec_file_load design, a PE file has a .bpf section, which data content is a ELF, and the ELF contains opts_insn[] opts_data[]. As a bonus, BPF bytecode can be placed under the protection of the entire PE signature.
(Note, since opts_insn[] contains the information of the ringbuf
size, the bpf-prog writer can change its proper size according to the kernel image size without modifying the kernel code)
--- kernel/Makefile | 1 + kernel/kexec_bpf/Makefile | 8 + kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h | 249 +------------------ kernel/kexec_bpf_loader.c | 93 ++++++- 4 files changed, 105 insertions(+), 246 deletions(-)
kernel/Makefile +1 -0
@@ -145,6 +145,7 @@ obj-$(CONFIG_SYSCTL_KUNIT_TEST) += sysctl-test.o CFLAGS_kstack_erase.o += $(DISABLE_KSTACK_ERASE) CFLAGS_kstack_erase.o += $(call cc-option,-mgeneral-regs-only) +CFLAGS_kexec_bpf_loader.o += -I$(srctree)/tools/lib obj-$(CONFIG_KSTACK_ERASE) += kstack_erase.o KASAN_SANITIZE_kstack_erase.o := n KCSAN_SANITIZE_kstack_erase.o := n
kernel/kexec_bpf/Makefile +8 -0
@@ -39,6 +39,14 @@ clean: kexec_pe_parser_bpf.lskel.h: $(OUTPUT)/kexec_pe_parser_bpf.o | $(BPFTOOL) $(call msg,GEN-SKEL,$@) $(Q)$(BPFTOOL) gen skeleton -L $< > $@ + @# The following sed commands make opts_data[] and opts_insn[] visible in a file instead of only in a function. + @# And it removes the bytecode + $(Q) sed -i '/static const char opts_data\[\].*=/,/";$$/d' $@ + $(Q) sed -i '/static const char opts_insn\[\].*=/,/";$$/d' $@ + $(Q) sed -i \ + -e 's/opts\.data_sz = sizeof(opts_data) - 1;/opts.data_sz = opts_data_sz;/' \ + -e 's/opts\.insns_sz = sizeof(opts_insn) - 1;/opts.insns_sz = opts_insn_sz;/' $@ + $(Q) sed -i '7i static char *opts_data, *opts_insn;\nstatic unsigned int opts_data_sz, opts_insn_sz;' $@ $(OUTPUT)/vmlinux.h: $(VMLINUX) $(DEFAULT_BPFTOOL) $(BPFOBJ) | $(OUTPUT) @$(BPFTOOL) btf dump file $(VMLINUX) format c > $(OUTPUT)/vmlinux.h
kernel/kexec_bpf/kexec_pe_parser_bpf.lskel.h +4 -245
263 lines not on this page · raw message
kernel/kexec_bpf_loader.c +92 -1
106 lines not on this page · raw message
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 09/13] kexec_file: Integrate bpf light skeleton to load image with bpf-prog
The bounds check validates that sym->st_value falls within the section, but it does not validate that sym->st_value + sym->st_size also fits within the section (or the ELF buffer).
Quoted 4 lines
kernel/kexec_bpf_loader.c +0
-0
[ ... ]
Quoted 4 lines
kernel/kexec_bpf_loader.c +4
-0+static void *get_symbol_from_elf (const char *elf_data,size_t elf_size, +const char *symbol_name, +unsigned int *symbol_size) +{
[ ... ]
Quoted 5 lines
kernel/kexec_bpf_loader.c +5
-0+/* Check section data bounds */ +if (dst_shdr->sh_offset > elf_size || + dst_shdr->sh_offset + dst_shdr->sh_size > elf_size || + sym->st_value > dst_shdr->sh_size) { +pr_err ("Symbol data out of bounds\n" );
kernel/kexec_bpf_loader.c line 85
Quoted 10 lines
kernel/kexec_bpf_loader.c +10
-0+return NULL ; + } + + symbol_data = (void *)(elf_data + dst_shdr->sh_offset + sym->st_value); + +if (symbol_size) + *symbol_size = sym->st_size; + +return symbol_data; +}
The bounds check validates that sym->st_value falls within the section, but it does not validate that sym->st_value + sym->st_size also fits within the section (or the ELF buffer).
The caller arm_bpf_prog() passes the returned sym->st_size through to bpf_load_and_run() as opts.data_sz / opts.insns_sz, which controls how many bytes are copied from the pointer:
arm_bpf_prog()
opts_data = get_symbol_from_elf(..., &opts_data_sz);
-> *symbol_size = sym->st_size;
...
kexec_pe_parser_bpf__open_and_load()
kexec_pe_parser_bpf__load()
opts.data_sz = opts_data_sz;
bpf_load_and_run(&opts);
skel_map_update_elem(map_fd, &key, opts->data, 0);Since the ELF comes from userspace via the PE .bpf section, could a crafted ELF with a valid st_value but an oversized st_size cause a read beyond the buffer here? Something like:
if (sym->st_value + sym->st_size > dst_shdr->sh_size) ...
might be needed alongside the existing st_value check.
Quoted 3 lines
+ /* Load a ELF */
static intarm_bpf_prog(char *bpf_elf, unsigned long sz){
[ ... ]
kernel/kexec_bpf_loader.c line 118
Quoted 9 lines
kernel/kexec_bpf_loader.c +8
-0+ pe_parser =kexec_pe_parser_bpf__open_and_load (); +if (!pe_parser) { +pr_info ("Can not open and load bpf parser\n" ); +return -1 ; + } +kexec_pe_parser_bpf__attach (pe_parser); + +return 0 ; }
kexec_pe_parser_bpf__attach() returns an error code, but its return value is not checked here. If attach fails (e.g. skel_raw_tracepoint_open() returns an error), arm_bpf_prog() still returns 0.
The caller process_bpf_parsers_container() then proceeds to call kexec_image_parser_anchor(), which is a no-op without the fentry hook. context->parsed stays false, and every section appears to fail with "no BPF section succeeded" -- hiding the real cause.
Should the return value of kexec_pe_parser_bpf__attach() be checked, with the parser destroyed and an error returned on failure?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
PATCH v7 10/13 arm64/kexec: Select KEXEC_BPF to support UEFI-style kernel image
In reply to Pingfan LiuNow everything is ready for kexec PE image parser. Select it on arm64 for zboot and UKI image support.
--- arch/arm64/Kconfig | 1 + 1 file changed, 1 insertion(+)
arch/arm64/Kconfig +1 -0
@@ -1608,6 +1608,7 @@ config ARCH_SELECTS_KEXEC_FILE def_bool y depends on KEXEC_FILE select HAVE_IMA_KEXEC if IMA + select KEXEC_BPF if DEBUG_INFO_BTF && BPF_SYSCALL && KEEP_DECOMPRESSOR config ARCH_SUPPORTS_KEXEC_SIG def_bool y
Signature · 1 line
2.49.0
PATCH v7 11/13 tools/kexec: Introduce a bpf-prog to handle zboot image
In reply to Pingfan LiuThis BPF program aligns with the convention defined in the kernel file kexec_pe_parser_bpf.lskel.h. This can be easily achieved by include "template.c", which includes:
four maps:
struct bpf_map_desc ringbuf_1;
struct bpf_map_desc ringbuf_2;
struct bpf_map_desc ringbuf_3;
struct bpf_map_desc ringbuf_4;
four sections:
struct bpf_map_desc rodata;
struct bpf_map_desc data;
struct bpf_map_desc bss;
struct bpf_map_desc rodata_str1_1;The only left thing is to implement a prog SEC("fentry.s/kexec_image_parser_anchor")
int BPF_PROG(parse_pe, struct kexec_context *context, unsigned long parser_id)
This bpf-prog can handle two kinds of formats:
-1. vmlinuz.efi, the zboot format, it can be derived from UKI's .linux section.
-2. an envelop format, which is a ELF file holding three key sections:
.kernel, .initrd, .cmdline.
This BPF program only uses ringbuf_1, so it minimizes the size of the other three ringbufs to one byte. The size of ringbuf_1 is derived from the combined size of vmlinuz.efi, initramfs, and cmdline, which typically totals less than 128MB. With the help of the BPF kfunc bpf_buffer_parser(), the BPF program passes instructions to the kexec BPF component to perform the appropriate actions.
--- tools/kexec/Makefile | 162 +++++++++++++++ tools/kexec/template.c | 72 +++++++ tools/kexec/zboot_parser_bpf.c | 347 +++++++++++++++++++++++++++++++++ 3 files changed, 581 insertions(+) create mode 100644 tools/kexec/Makefile create mode 100644 tools/kexec/template.c create mode 100644 tools/kexec/zboot_parser_bpf.c
tools/kexec/Makefile new file +162 -0
@@ -0,0 +1,162 @@ +# SPDX-License-Identifier: GPL-2.0 + +# Ensure Kbuild variables are available +include ../scripts/Makefile.include + +srctree := $(patsubst %/tools/kexec,%,$(CURDIR)) +VMLINUX = $(srctree)/vmlinux +TOOLSDIR := $(srctree)/tools +LIBDIR := $(TOOLSDIR)/lib +BPFDIR := $(LIBDIR)/bpf +ARCH ?= $(shell uname -m | sed -e s/i.86/x86/ -e s/x86_64/x86/ -e s/aarch64.*/arm64/ -e s/riscv64/riscv/ -e s/loongarch.*/loongarch/) +# At present, zboot image format is used by arm64, riscv, loongarch +# And arch/$(ARCH)/boot/vmlinux.bin is the uncompressed file instead of arch/$(ARCH)/boot/Image +ifeq ($(ARCH),$(filter $(ARCH),arm64 riscv loongarch)) + EFI_IMAGE := $(srctree)/arch/$(ARCH)/boot/vmlinuz.efi + KERNEL_IMAGE := $(srctree)/arch/$(ARCH)/boot/vmlinux.bin +else + @echo "Unsupported architecture: $(ARCH)" + @exit 1 +endif + +CC = clang +CFLAGS = -O2 +BPF_PROG_CFLAGS = -g -fno-merge-all-constants -O2 -target bpf -Wall -I $(BPFDIR) -I . +BPFTOOL = bpftool + +# --------------------------------------------------------------------------- +# Shared generated headers (common to all targets) +# --------------------------------------------------------------------------- +HEADERS = vmlinux.h bpf_helper_defs.h image_size.h + +# --------------------------------------------------------------------------- +# Per-target artifact lists +# To add a new target (e.g. uki), append to BPF_TARGETS and define a +# <name>: phony rule below. All build rules are driven by pattern rules +# and require no further changes. +# +# Artifacts produced per prefix <P>: +# <P>_parser_bpf.o - compiled BPF object +# <P>_parser_bpf.lskel.h - light skeleton header +# <P>_bytecode.c - extracted opts_data / opts_insn arrays +# <P>_bytecode.o - compiled bytecode object +# <P>.bpf - final ELF wrapper with .bpf.1 section +# --------------------------------------------------------------------------- +BPF_TARGETS = zboot + +define BPF_ARTIFACTS +$(1)_parser_bpf.o $(1)_parser_bpf.lskel.h $(1)_bytecode.c $(1)_bytecode.o $(1).bpf +endef + +ALL_BPF_ARTIFACTS = $(foreach t,$(BPF_TARGETS),$(call BPF_ARTIFACTS,$(t))) + +# --------------------------------------------------------------------------- +# Top-level phony targets +# --------------------------------------------------------------------------- +zboot: $(HEADERS) $(call BPF_ARTIFACTS,zboot) build_zboot_image + +.PHONY: zboot clean + +# --------------------------------------------------------------------------- +# Shared header rules +# --------------------------------------------------------------------------- + +# Rule to generate vmlinux.h from vmlinux +vmlinux.h: $(VMLINUX) + @command -v $(BPFTOOL) >/dev/null 2>&1 || { echo >&2 "$(BPFTOOL) is required but not found. Please install it."; exit 1; } + @$(BPFTOOL) btf dump file $(VMLINUX) format c > vmlinux.h + +bpf_helper_defs.h: $(srctree)/tools/include/uapi/linux/bpf.h + @$(QUIET_GEN)$(srctree)/scripts/bpf_doc.py --header \ + --file $(srctree)/tools/include/uapi/linux/bpf.h > bpf_helper_defs.h + +# Default estimated size for initramfs (can be overridden by user) +INITRD_ESTIMATE_SIZE ?= 67108864 # 64MB + +# In worst case, this image includes vmlinuz.efi, initramfs and cmdline +image_size.h: $(KERNEL_IMAGE) + @{ \ + if [ ! -f "$(KERNEL_IMAGE)" ]; then \ + echo "Error: File '$(KERNEL_IMAGE)' does not exist"; \ + exit 1; \ + fi; \ + KERNEL_SIZE=$$(stat -c '%s' "$(KERNEL_IMAGE)" 2>/dev/null); \ + ELF_OVERHEAD=4096; \ + TOTAL_SIZE=$$((KERNEL_SIZE + $(INITRD_ESTIMATE_SIZE) + ELF_OVERHEAD)); \ + POWER=4096; \ + while [ $$POWER -le $$TOTAL_SIZE ]; do \ + POWER=$$((POWER * 2)); \ + done; \ + RINGBUF_SIZE=$$POWER; \ + echo "#define IMAGE_SIZE_POWER2_ALIGN $$RINGBUF_SIZE" > $@; \ + echo "#define IMAGE_SIZE $$TOTAL_SIZE" >> $@; \ + echo "#define KERNEL_SIZE $$KERNEL_SIZE" >> $@; \ + echo "#define INITRD_SIZE $(INITRD_ESTIMATE_SIZE)" >> $@; \ + } + +# --------------------------------------------------------------------------- +# Pattern rules: BPF build pipeline +# All rules below are prefix-agnostic; % matches zboot, uki, etc. +# --------------------------------------------------------------------------- + +%_parser_bpf.o: %_parser_bpf.c vmlinux.h bpf_helper_defs.h + @$(CC) $(BPF_PROG_CFLAGS) -c $< -o $@ + +%_parser_bpf.lskel.h: %_parser_bpf.o + @$(BPFTOOL) gen skeleton -L $< > $@ + +# Extract opts_data[] and opts_insn[] arrays from the skeleton header, +# stripping 'static' so the symbols are not optimized away by the compiler. +# This rule is intentionally generic: all parsers expose the same symbol names. +%_bytecode.c: %_parser_bpf.lskel.h + @sed -n '/static const char opts_data\[\]/,/;/p' $< | sed 's/static const/const/' > $@ + @sed -n '/static const char opts_insn\[\]/,/;/p' $< | sed 's/static const/const/' >> $@ + +%_bytecode.o: %_bytecode.c + @$(CC) $(CFLAGS) -c $< -o $@ + + +# Wrap the bytecode ELF object into a new ELF container as section .bpf.1 +# --------------------------------------------------------------------------- +# Per-target BPF section definitions +# Format: space-separated "sectionname:sourcefile" pairs +# --------------------------------------------------------------------------- +ZBOOT_BPF_MAPS := .bpf.1:zboot_bytecode.o + +# --------------------------------------------------------------------------- +# Helpers to build objcopy flags from a BPF_MAPS list +# --------------------------------------------------------------------------- +section_name = $(firstword $(subst :, ,$(1))) +source_file = $(lastword $(subst :, ,$(1))) + +only_section_flags = $(foreach m,$(1),--only-section=$(call section_name,$(m))) + +# --------------------------------------------------------------------------- +# Template: generates the %.bpf rule for a given target +# $(1) = lowercase target name, e.g. zboot +# $(2) = UPPER prefix for _BPF_MAPS variable, e.g. ZBOOT +# +# Sections are added one at a time in the order defined in $(2)_BPF_MAPS. +# objcopy does not guarantee section order when all --add-section flags are +# given in a single invocation, so we chain N calls through a .work.o file +# to preserve the declared order. +# --------------------------------------------------------------------------- +define BPF_WRAPPER_RULE +$(1).bpf: $(foreach m,$($(2)_BPF_MAPS),$(call source_file,$(m))) + @echo '' | $(CC) -x c - -c -o [email protected] + $(foreach m,$($(2)_BPF_MAPS),\ + @objcopy --add-section $(call section_name,$(m))=$(call source_file,$(m)) \ + --set-section-flags $(call section_name,$(m))=readonly,data \ + [email protected] [email protected] && mv [email protected] [email protected] + ) + @objcopy $(call only_section_flags,$($(2)_BPF_MAPS)) [email protected] $$@ + @rm -f [email protected] +endef + +$(eval $(call BPF_WRAPPER_RULE,zboot,ZBOOT)) + +# --------------------------------------------------------------------------- +# Clean +# --------------------------------------------------------------------------- +clean: + @rm -f $(HEADERS) $(ALL_BPF_ARTIFACTS) *.base.o
tools/kexec/template.c new file +72 -0
72 lines not on this page · raw message
tools/kexec/zboot_parser_bpf.c new file +347 -0
347 lines not on this page · raw message
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 11/13] tools/kexec: Introduce a bpf-prog to handle zboot image
The else branch uses recipe syntax (@echo, @exit) at top-level Makefile scope, outside of any rule. On unsupported architectures this would produce a confusing GNU Make parse error rather than the…
Quoted 3 lines
tools/kexec/Makefile new file +0
-0
[ ... ]
tools/kexec/Makefile line 20
Quoted 7 lines
tools/kexec/Makefile new file +7
-0+ifeq ($(ARCH),$(filter $(ARCH),arm64 riscv loongarch)) + EFI_IMAGE := $(srctree)/arch/$(ARCH)/boot/vmlinuz.efi + KERNEL_IMAGE := $(srctree)/arch/$(ARCH)/boot/vmlinux.bin +else + @echo "Unsupported architecture: $(ARCH)" + @exit 1 +endif
The else branch uses recipe syntax (@echo, @exit) at top-level Makefile scope, outside of any rule. On unsupported architectures this would produce a confusing GNU Make parse error rather than the intended message. Should this use $(error ...) instead?
Quoted 1 line
+zboot: $(HEADERS) $(call BPF_ARTIFACTS,zboot)
build_zboot_image
There is no rule or file for the build_zboot_image prerequisite in this Makefile. Will this cause "make zboot" to fail with "No rule to make target 'build_zboot_image'"?
[ ... ]
Quoted 3 lines
tools/kexec/zboot_parser_bpf.c new file +0
-0
[ ... ]
tools/kexec/zboot_parser_bpf.c line 16
Quoted 7 lines
tools/kexec/zboot_parser_bpf.c new file +7
-0+/* ringbuf 2,3,4 are useless */ +#define MIN_BUF_SIZE 1 +#define MAX_RECORD_SIZE (IMAGE_SIZE + 40960) +#define RINGBUF1_SIZE IMAGE_SIZE_POWER2_ALIGN +#define RINGBUF2_SIZE MIN_BUF_SIZE +#define RINGBUF3_SIZE MIN_BUF_SIZE +#define RINGBUF4_SIZE MIN_BUF_SIZE
ringbuf_map_alloc() in kernel/bpf/ringbuf.c requires max_entries to be both power-of-2 and PAGE_ALIGNED. With MIN_BUF_SIZE set to 1, ringbufs 2/3/4 will fail map creation with -EINVAL since PAGE_ALIGNED(1) is false. The minimum valid size would be PAGE_SIZE (typically 4096). Would the BPF program fail to load because of this?
[ ... ]
tools/kexec/zboot_parser_bpf.c line 69
Quoted 11 lines
tools/kexec/zboot_parser_bpf.c new file +11
-0+static int fill_cmd (char *buf,__u16 cmd,__u16 subcmd, +const char *src,__u32 data_len) +{ +struct cmd_hdr *hdr; +char *payload; + + hdr = (struct cmd_hdr *)buf; + hdr->cmd = cmd; + hdr->subcmd = subcmd; + hdr->payload_len = data_len; + hdr->num_chunks =0 ;
The struct cmd_hdr (in kernel/kexec_bpf_loader.c) also has a pipeline_flag field at offset 3:
struct cmd_hdr {
uint16_t cmd;
uint8_t subcmd;
uint8_t pipeline_flag;
uint32_t payload_len;
uint16_t num_chunks;
};This field is not initialized here, and bpf_ringbuf_reserve() does not zero the returned memory. The kernel's kexec_buff_parser() reads this field:
fill_pipeline = cmd->pipeline_flag & KEXEC_BPF_PIPELINE_FILL;
If the garbage byte happens to have bit 0x1 set, this would trigger unintended pipeline fill behavior, causing extra allocations and copies into next_parsing_buf[]. Should pipeline_flag be explicitly zeroed?
[ ... ]
Quoted 4 lines
tools/kexec/zboot_parser_bpf.c new file +4
-0+SEC("fentry.s/kexec_image_parser_anchor") +int BPF_PROG (parse_zboot ,struct kexec_context *context,unsigned long parser_id) +{ +kexec_sig_enforced sig_mode;
[ ... ]
tools/kexec/zboot_parser_bpf.c line 195
Quoted 1 line
tools/kexec/zboot_parser_bpf.c new file +1
-0+ sig_mode =BPF_CORE_READ (context, sig_mode);
The type kexec_sig_enforced does not appear to exist as a type (enum, typedef, or struct) anywhere in the kernel sources. The only related symbol is the function set_kexec_sig_enforced(). Similarly, struct kexec_context (in kernel/kexec_bpf_loader.c) has no sig_mode field.
Since the BPF program includes vmlinux.h generated from the kernel's BTF, it would fail to compile without this type, and the BPF_CORE_READ would fail CO-RE relocation without the struct field. Are these expected to be added by a patch not yet in this series?
---
AI reviewed your patch. Please fix the bug or email reply why it's not a bug.
See: https://github.com/kernel-patches/vmtest/blob/master/ci/claude/README.md
CI run summary: https://github.com/kernel-patches/bpf/actions/runs/23393379437
PATCH v7 12/13 tools/kexec: Introduce a bpf-prog to handle UKI image
In reply to Pingfan Liu--- tools/kexec/Makefile | 18 ++- tools/kexec/uki_parser_bpf.c | 235 +++++++++++++++++++++++++++++++++++ 2 files changed, 252 insertions(+), 1 deletion(-) create mode 100644 tools/kexec/uki_parser_bpf.c
tools/kexec/Makefile +17 -1
@@ -43,6 +43,7 @@ HEADERS = vmlinux.h bpf_helper_defs.h image_size.h # <P>.bpf - final ELF wrapper with .bpf.1 section # --------------------------------------------------------------------------- BPF_TARGETS = zboot +BPF_TARGETS += uki define BPF_ARTIFACTS $(1)_parser_bpf.o $(1)_parser_bpf.lskel.h $(1)_bytecode.c $(1)_bytecode.o $(1).bpf
@@ -54,8 +55,13 @@ ALL_BPF_ARTIFACTS = $(foreach t,$(BPF_TARGETS),$(call BPF_ARTIFACTS,$(t))) # Top-level phony targets # --------------------------------------------------------------------------- zboot: $(HEADERS) $(call BPF_ARTIFACTS,zboot) build_zboot_image +ifeq ($(ARCH),$(filter $(ARCH),arm64 riscv loongarch)) +uki: $(HEADERS) zboot.bpf $(call BPF_ARTIFACTS,uki) +else +uki: $(HEADERS) $(call BPF_ARTIFACTS,uki) +endif -.PHONY: zboot clean +.PHONY: zboot uki clean # --------------------------------------------------------------------------- # Shared header rules
@@ -123,6 +129,15 @@ image_size.h: $(KERNEL_IMAGE) # --------------------------------------------------------------------------- ZBOOT_BPF_MAPS := .bpf.1:zboot_bytecode.o +# uki.bpf sections depend on architecture: +# arm64/riscv/loongarch: .bpf.1 (uki bytecode) + .bpf.nested (zboot.bpf ELF) +# x86: .bpf.1 only. zboot format does not exist on x86 +ifeq ($(ARCH),$(filter $(ARCH),arm64 riscv loongarch)) +UKI_BPF_MAPS := .bpf.1:uki_bytecode.o .bpf.nested:zboot.bpf +else +UKI_BPF_MAPS := .bpf.1:uki_bytecode.o +endif + # --------------------------------------------------------------------------- # Helpers to build objcopy flags from a BPF_MAPS list # ---------------------------------------------------------------------------
@@ -154,6 +169,7 @@ $(1).bpf: $(foreach m,$($(2)_BPF_MAPS),$(call source_file,$(m))) endef $(eval $(call BPF_WRAPPER_RULE,zboot,ZBOOT)) +$(eval $(call BPF_WRAPPER_RULE,uki,UKI)) # --------------------------------------------------------------------------- # Clean
tools/kexec/uki_parser_bpf.c new file +235 -0
235 lines not on this page · raw message
Signature · 1 line
2.49.0
[email protected]
AI reviewRe: [PATCHv7 12/13] tools/kexec: Introduce a bpf-prog to handle UKI image
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
Thank you for your contribution! Sashiko AI review found 6 potential issue(s) to consider:
New issues:
- [High] Integer overflow in PE section bounds checks allows out-of-bounds kernel memory reads.
- [High] BPF Verifier rejection and runtime failure due to out-of-bounds stack read in section name comparison.
- [High] MAX_RECORD_SIZE rigidly restricts UKI size, erroneously rejecting almost all valid real-world UKI binaries.
- [Medium] Missing error handling for bpf_probe_read_kernel allows silent propagation of empty payloads.
- [Medium] PE parsing uses native endianness, breaking kexec UKI support on Big Endian architectures.
Pre-existing issues:
- [High] The bpf_buffer_parser kfunc lacks the required __sz annotation, causing verifier rejection. --
--- Patch [12]: [PATCHv7 12/13] tools/kexec: Introduce a bpf-prog to handle UKI image --- commit 0509f42d83cdb5ef64ae7388052bbc638cf2e7d6
Author: Pingfan Liu <[email protected]>
tools/kexec: Introduce a bpf-prog to handle UKI image
This commit adds a BPF program to parse Unified Kernel Image (UKI) PE files for kexec. It extracts the .linux, .initrd, and .cmdline sections from the PE file and passes them as commands to the kexec parser pipeline.
Quoted 6 lines
tools/kexec/uki_parser_bpf.c new file +0
-0@@ -0,0 +1,235 @@
[ ... ]
tools/kexec/uki_parser_bpf.c line 12
Quoted 3 lines
tools/kexec/uki_parser_bpf.c new file +3
-0+/* ringbuf 2,3,4 are useless */ +#define MIN_BUF_SIZE 1 +#define MAX_RECORD_SIZE (IMAGE_SIZE + 40960)
[Severity: High]
Does this 40KB margin over IMAGE_SIZE reject valid UKI images that contain standard initramfs payloads?
If a typical initramfs is 10MB to 50MB, will checking the file size or section size against MAX_RECORD_SIZE prevent almost all real-world UKI files from loading?
[ ... ]
Quoted 3 lines
tools/kexec/uki_parser_bpf.c new file +3
-0+static int fill_cmd (char *buf,__u32 cmd_word,__u32 pipeline_flag, +const char *src,__u32 data_len) +{
[ ... ]
tools/kexec/uki_parser_bpf.c line 65
Quoted 5 lines
tools/kexec/uki_parser_bpf.c new file +5
-0+if (!src || !data_len) +return sizeof (*hdr); +if (data_len >MAX_RECORD_SIZE -sizeof (struct cmd_hdr )) +return -EINVAL ; +bpf_probe_read_kernel (payload, data_len, src);
[Severity: Medium]
What happens if bpf_probe_read_kernel fails due to an unmapped page?
Since the return value is ignored, will it silently pass a zero-filled buffer as a successful payload instead of failing explicitly?
Quoted 6 lines
tools/kexec/uki_parser_bpf.c new file +6
-0+ +return sizeof (*hdr) + data_len; +} + +static int process_uki_pe (const char *pe_buf,__u32 pe_sz,char *scratch, +struct bpf_parser_context *bpf_ctx)
tools/kexec/uki_parser_bpf.c line 81
Quoted 10 lines
tools/kexec/uki_parser_bpf.c new file +10
-0+{ +__u32 pe_offset, pe_sig, section_table_off; +__u16 dos_magic, num_sections, opt_hdr_sz; +__u16 pipeline_flag =0 ; +int i, ret; + +if (pe_sz <64 ) +return -EINVAL ; +if (pe_sz >MAX_RECORD_SIZE ) +return -EINVAL ;
[Severity: High]
This check uses the same MAX_RECORD_SIZE that may reject valid UKI images containing typical initramfs sizes.
tools/kexec/uki_parser_bpf.c line 85
Quoted 4 lines
tools/kexec/uki_parser_bpf.c new file +4
-0+ +if (bpf_probe_read_kernel (&dos_magic,sizeof (dos_magic), pe_buf) <0 ) +return -EIO ; +if (dos_magic !=0x5A4D )
[Severity: Medium]
Will this endian-specific comparison fail on Big Endian machines?
Since the PE format is strictly Little Endian, should this use an endianness conversion helper to avoid rejecting valid PE files on Big Endian architectures?
tools/kexec/uki_parser_bpf.c line 91
Quoted 6 lines
tools/kexec/uki_parser_bpf.c new file +6
-0+return -EINVAL ; + +if (bpf_probe_read_kernel (&pe_offset,sizeof (pe_offset), + pe_buf +0x3c ) <0 ) +return -EIO ; +if (pe_offset +24 > pe_sz)
[Severity: High]
Is it possible for pe_offset + 24 to overflow 32-bit math?
If a maliciously crafted UKI provides a very large pe_offset, could the addition wrap around and bypass the pe_sz boundary check, allowing out-of-bounds kernel memory reads?
Quoted 5 lines
tools/kexec/uki_parser_bpf.c new file +5
-0+return -EINVAL ; + +if (bpf_probe_read_kernel (&pe_sig,sizeof (pe_sig), + pe_buf + pe_offset) <0 ) +return -EIO ;
[ ... ]
tools/kexec/uki_parser_bpf.c line 138
Quoted 12 lines
tools/kexec/uki_parser_bpf.c new file +12
-0+ pipeline_flag =0 ; +if (__builtin_memcmp (sec_name, linux_sect_name,sizeof (linux_sect_name)) ==0 ) { + subcmd =KEXEC_BPF_SUBCMD_KERNEL ; +/* +* .linux section may contain different format kernel, which should be +* passed to the next stage to handle +*/ + pipeline_flag =KEXEC_BPF_PIPELINE_FILL ; + } +else if (__builtin_memcmp (sec_name, initrd_sect_name,sizeof (initrd_sect_name)) ==0 ) + subcmd =KEXEC_BPF_SUBCMD_INITRD ; +else if (__builtin_memcmp (sec_name, cmdline_sect_name,sizeof (cmdline_sect_name)) ==0 )
[Severity: High]
Does this force a 9-byte read from the 8-byte sec_name array?
Since cmdline_sect_name is a null-terminated string, its sizeof is 9 bytes. However, sec_name is allocated as an 8-byte array on the stack. Will this cause the BPF verifier to reject the program due to an out-of-bounds stack read?
Also, the .cmdline section name in a valid PE file is exactly 8 bytes and lacks a null terminator, so would this comparison always fail at runtime?
tools/kexec/uki_parser_bpf.c line 150
Quoted 12 lines
tools/kexec/uki_parser_bpf.c new file +12
-0+ subcmd =KEXEC_BPF_SUBCMD_CMDLINE ; + else + continue; + +if (bpf_probe_read_kernel (&raw_size,sizeof (raw_size), + pe_buf + shdr_off +16 ) <0 ) +continue ; +if (bpf_probe_read_kernel (&raw_off,sizeof (raw_off), + pe_buf + shdr_off +20 ) <0 ) +continue ; + +if (!raw_size || raw_off + raw_size > pe_sz)
[Severity: High]
Is it possible for raw_off + raw_size to overflow 32-bit math?
Similar to pe_offset above, if raw_off is huge and raw_size is small, could it wrap around, bypass the > pe_sz check, and result in an arbitrary out-of-bounds kernel memory read in fill_cmd?
tools/kexec/uki_parser_bpf.c line 158
Quoted 8 lines
tools/kexec/uki_parser_bpf.c new file +8
-0+continue ; + + ret =fill_cmd (scratch, +MAKE_CMD (KEXEC_BPF_CMD_COPY , subcmd), + pipeline_flag, + pe_buf + raw_off, + raw_size); + ret =bpf_buffer_parser (scratch, ret, bpf_ctx);
[Severity: High]
This is a pre-existing issue, but does the bpf_buffer_parser kfunc need its size argument renamed to buf__sz to satisfy the BPF verifier?
The bpf_buffer_parser kfunc is defined with the argument name buf_sz. The verifier strictly requires memory buffer size arguments to end in __sz. Because it is named buf_sz, will the verifier fail to grant KF_ARG_PTR_TO_MEM semantics and reject the ringbuf memory passed here?
Quoted 6 lines
tools/kexec/uki_parser_bpf.c new file +6
-0+if (ret) +return ret; + } + +return 0 ; +}
Signature · 1 line
Sashiko AI review · https://sashiko.dev/#/patchset/[email protected]?part=12
PATCH v7 13/13 tools/kexec: Introduce a tool to build zboot envelop
In reply to Pingfan LiuThe new tool builds a ELF container around zboot image. It contains three key sections: .kernel, .initrd, .cmdline. Later zboot_bpf_parser will parse this container format.
--- tools/kexec/Makefile | 31 ++- tools/kexec/build_zboot_envelop.c | 362 ++++++++++++++++++++++++++++++ tools/kexec/zboot_envelop.h | 7 + tools/kexec/zboot_parser_bpf.c | 7 +- 4 files changed, 401 insertions(+), 6 deletions(-) create mode 100644 tools/kexec/build_zboot_envelop.c create mode 100644 tools/kexec/zboot_envelop.h
tools/kexec/Makefile +28 -3
@@ -21,9 +21,21 @@ endif CC = clang CFLAGS = -O2 -BPF_PROG_CFLAGS = -g -fno-merge-all-constants -O2 -target bpf -Wall -I $(BPFDIR) -I . +BPF_PROG_CFLAGS = -g -O2 -target bpf -Wall -I $(BPFDIR) -I . BPFTOOL = bpftool +# Host compiler for native tools (must not be the BPF clang cross-compiler) +HOSTCC ?= gcc +HOSTCFLAGS = -std=c11 -O2 -Wall -Wextra + +# --------------------------------------------------------------------------- +# zboot ELF image parameters +# INITRAMFS: path to the initramfs image (required) +# CMDLINE: kernel command line string (optional, defaults to empty) +# --------------------------------------------------------------------------- +INITRAMFS ?= +CMDLINE ?= + # --------------------------------------------------------------------------- # Shared generated headers (common to all targets) # ---------------------------------------------------------------------------
@@ -54,7 +66,7 @@ ALL_BPF_ARTIFACTS = $(foreach t,$(BPF_TARGETS),$(call BPF_ARTIFACTS,$(t))) # --------------------------------------------------------------------------- # Top-level phony targets # --------------------------------------------------------------------------- -zboot: $(HEADERS) $(call BPF_ARTIFACTS,zboot) build_zboot_image +zboot: $(HEADERS) $(call BPF_ARTIFACTS,zboot) build_zboot_envelop ifeq ($(ARCH),$(filter $(ARCH),arm64 riscv loongarch)) uki: $(HEADERS) zboot.bpf $(call BPF_ARTIFACTS,uki) else
@@ -171,8 +183,21 @@ endef $(eval $(call BPF_WRAPPER_RULE,zboot,ZBOOT)) $(eval $(call BPF_WRAPPER_RULE,uki,UKI)) +# --------------------------------------------------------------------------- +# Host tool: build_zboot_envelop +# Packs EFI_IMAGE (.kernel), INITRAMFS (.initrd) and CMDLINE (.cmdline) +# into a single ELF file consumed by the kexec loader. +# --------------------------------------------------------------------------- +build_zboot_envelop: build_zboot_envelop.c + @$(HOSTCC) $(HOSTCFLAGS) -o $@ $< + +zboot_image.elf: build_zboot_envelop $(EFI_IMAGE) $(INITRAMFS) + $(if $(INITRAMFS),,$(error INITRAMFS is not set. Usage: make INITRAMFS=<path> [CMDLINE="..."])) + @./build_zboot_envelop $(EFI_IMAGE) $(INITRAMFS) "$(CMDLINE)" + # --------------------------------------------------------------------------- # Clean # --------------------------------------------------------------------------- clean: - @rm -f $(HEADERS) $(ALL_BPF_ARTIFACTS) *.base.o + @rm -f $(HEADERS) $(ALL_BPF_ARTIFACTS) *.base.o \ + build_zboot_envelop zboot_image.elf
tools/kexec/build_zboot_envelop.c new file +362 -0
362 lines not on this page · raw message
tools/kexec/zboot_envelop.h new file +7 -0
@@ -0,0 +1,7 @@ +#ifndef ZBOOT_ENVELOP_H +#define ZBOOT_ENVELOP_H + +#define KERNEL_SECT_NAME ".kernel" +#define INITRD_SECT_NAME ".initrd" +#define CMDLINE_SECT_NAME ".cmdline" +#endif
tools/kexec/zboot_parser_bpf.c +4 -3
@@ -16,6 +16,7 @@#define RINGBUF4_SIZE MIN_BUF_SIZE#include "template.c" +#include "zboot_envelop.h" #define ELF_SCAN_MAX 8
@@ -43,9 +44,9 @@ struct linux_pe_zboot_header {unsigned int pe_header_offset; } __attribute__((packed)); -static const char linux_sect_name[] =".kernel" ; -static const char initrd_sect_name[] =".initrd" ; -static const char cmdline_sect_name[] =".cmdline" ; +static const char linux_sect_name[] =KERNEL_SECT_NAME ; +static const char initrd_sect_name[] =INITRD_SECT_NAME ; +static const char cmdline_sect_name[] =CMDLINE_SECT_NAME ;/* * fill_cmd - overwrite the cmd_hdr at the start of @buf and copy @data_len
Signature · 1 line
2.49.0
Andrew Morton
maintainerQuoted 25 lines · On Sun, 22 Mar 2026 09:43:49 +0800 Pingfan Liu <[email protected]> wrote:
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/ImageFor the first approach, I tried a purgatory-style emulator [1], but it encounters hardware scaling issues. For the second approach, both zboot-format [2] and UKI-format [3] parsers were rejected due to concerns that variant format parsers would bloat the kernel code. Additionally, for example in arm64, both UKI and zboot format parsers would need to be introduced and chained together to handle image loading. For the third approach, I attempted [4], but since zboot or UKI images already have signatures, upstream maintainers dislike the additional signature on the Image. Moreover, for secure boot UKI, this method cannot use signatures to protect the initramfs.
Quoted 4 lines
*** The approach in this series ***
This series introduces an approach that allows image formats to be parsed by BPF programs.
AI review has a ton of questions:
https://sashiko.dev/#/patchset/[email protected]
Coverage is partial because some patches didn't apply. Probably some of these questions are legitimate, others will be false positives - we're still figuring this out.
Quoted 33 lines · Andrew Morton
Quoted 25 lines · On Sun, 22 Mar 2026 09:43:49 +0800 Pingfan Liu <[email protected]> wrote:
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/ImageFor the first approach, I tried a purgatory-style emulator [1], but it encounters hardware scaling issues. For the second approach, both zboot-format [2] and UKI-format [3] parsers were rejected due to concerns that variant format parsers would bloat the kernel code. Additionally, for example in arm64, both UKI and zboot format parsers would need to be introduced and chained together to handle image loading. For the third approach, I attempted [4], but since zboot or UKI images already have signatures, upstream maintainers dislike the additional signature on the Image. Moreover, for secure boot UKI, this method cannot use signatures to protect the initramfs.
Quoted 4 lines
*** The approach in this series ***
This series introduces an approach that allows image formats to be parsed by BPF programs.
Quoted 7 lines
AI review has a ton of questions:
https://sashiko.dev/#/patchset/[email protected]Coverage is partial because some patches didn't apply. Probably some of these questions are legitimate, others will be false positives - we're still figuring this out.
Thank you, I will check them too.
Best Regards,
Pingfan
Quoted 9 lines · Pingfan Liu
*** The history ***
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
Quoted 4 lines
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/Image
I recently had an interesting discussion with Ard around DRTM for kexec and we sort of independently concluded that #1 would be the best (only?) option there.
All the implementations of DRTM today live in the EFI stub and intercept the boot process as it goes along. After ExitBootServices the DRTM implementation will launch the kernel in a different way. Even worse today's x86 version strongly requires EFI boot services to connect the Linux stub with a trampoline helper provided earlier in the boot chain.
A kexec flow that only works on decompressed vmlinux, with no option to run any EFI code, is going to be difficult to support. There is enough information and choices involved in DRTM that it is undesirable for the predecessor kernel to try and DRTM launch it on behalf of the successor, let alone trying to get the insane x86 trampolines into a kexec successor kernel.
Given those constraints entering the successor kernel through the normal EFI entry point is highly desirable. This would allow x86 to continue to provide the DRTM trampolines through an EFI mechanism and means the Linux EFI stub always handles the launch with identical code in all scenarios.
I reviewed the earlier threads and it wasn't clear why this was abandoned? The points Ard raised are legitimate, but I would respond to them:
https://lore.kernel.org/lkml/[email protected]/T/#m8519beebccb252861b257db390a1686686b27aeb
Quoted 1 line
1) Implementing UEFI entirely is intractable, and unnecessary.
Yes, I think that is the entire point of the general idea, that we should strive to have some limited EFI that is just useful enough to boot a UKI through to the kernel EFI entry point.
Quoted 1 line
2) Running the UEFI emulator on bare metal is not going to scale.
Well, I don't think everyone will have that choice. At least DRTM requires things like ARM SMCs, and x86 requires ACPI parsing, it would be really tricky to get those things into a userspace context.
I would recast this idea as "having the kernel community own a UEFI emulator for every kind of bare metal is not scalable"
Quoted 2 lines
3. We need to figure out how to support TPM and PCRs in the context of kexec.
AFAIK it doesn't really work today. DRTM significantly fixes it, and passing more PCR logs fixes it even more. Though I don't see that it has much to do with using the EFI entry point.. It is a good question what should systemd-shim do in a kexec case, or more generally when DRTM is being used. (for drtm it should probably not do anything with PCRs)
IMHO, the kernel shouldn't get involved. It shouldn't try to integrate an EFI emulator. The kexec path in the kernel should allow userspace to provide a signed executable which is the emulator it wants to use and let other people sort it out in their own projects. Distros can sign the emulators they like.
There are already two examples of emulators that can EFI Boot the kernel so there is definitely something achievable that many people can use. If someone wants to go crazy and support Grub, console, userspace EFI, etc, they can do that on their own git :)
Down this path the kernel work should simply be supporting a signed executable (not vmlinux), and a robust way to pass more information through a FDT to that executable. Such that userspace can get the EFI emulator, the UKI, side cars and anything else nicely organized and labeled in a FDT so the EFI emulator has an easy job.
In the current AI fueled world this looks much more tractable than it did in 2024 when this was last brought up.
Regards,
Jason
Hi Jason,
Thanks for chiming in.
Quoted 33 lines · Jason Gunthorpe
Quoted 9 lines · Pingfan Liu
*** The history ***
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
Quoted 4 lines
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/ImageI recently had an interesting discussion with Ard around DRTM for kexec and we sort of independently concluded that #1 would be the best (only?) option there.
All the implementations of DRTM today live in the EFI stub and intercept the boot process as it goes along. After ExitBootServices the DRTM implementation will launch the kernel in a different way. Even worse today's x86 version strongly requires EFI boot services to connect the Linux stub with a trampoline helper provided earlier in the boot chain.
A kexec flow that only works on decompressed vmlinux, with no option to run any EFI code, is going to be difficult to support. There is enough information and choices involved in DRTM that it is undesirable for the predecessor kernel to try and DRTM launch it on behalf of the successor, let alone trying to get the insane x86 trampolines into a kexec successor kernel.
Quoted 6 lines
Given those constraints entering the successor kernel through the normal EFI entry point is highly desirable. This would allow x86 to continue to provide the DRTM trampolines through an EFI mechanism and means the Linux EFI stub always handles the launch with identical code in all scenarios.
With some help from my friend Claude, I've prepared a prototype that reuses my efiloader Rust crate to boot EFI stub images (bare Image, zboot, UKI) in the kernel: the EFI boot phase is invoked at kexec load time, and runs under the preceding kernel up until the point where ExitBootServices() is called. Then, the actual kexec call will return from ExitBootServices() after shutting down the first kernel.
https://git.kernel.org/pub/scm/linux/kernel/git/ardb/linux.git/log/?h=efiloader-kexec
There are some limitations (4k pages only, CONTIG_ALLOC support required) but it seems to work as expected.
I haven't looked at measured boot or DRTM specifics.
Quoted 6 lines · Ard Biesheuvel
Quoted 5 lines
Given those constraints entering the successor kernel through the normal EFI entry point is highly desirable. This would allow x86 to continue to provide the DRTM trampolines through an EFI mechanism and means the Linux EFI stub always handles the launch with identical code in all scenarios.
Quoted 7 lines
With some help from my friend Claude, I've prepared a prototype that reuses my efiloader Rust crate to boot EFI stub images (bare Image, zboot, UKI) in the kernel: the EFI boot phase is invoked at kexec load time, and runs under the preceding kernel up until the point where
ExitBootServices()is called. Then, the actual kexec call will return fromExitBootServices()after shutting down the first kernel.
Running it inside a kthread is such a novel idea, I would have never thought to attempt that!
I've asked some folks here to take a look and try to test this with real DRTM capable HW. It seems very promising that it will work to me, and I surmize this is also close to boot a UKI?
Seems amazing! Thanks a lot for drafting it!
Jason
(removed some bouncing cc'ees)
Quoted 15 lines · Jason Gunthorpe
Quoted 6 lines · Ard Biesheuvel
Quoted 5 lines
Given those constraints entering the successor kernel through the normal EFI entry point is highly desirable. This would allow x86 to continue to provide the DRTM trampolines through an EFI mechanism and means the Linux EFI stub always handles the launch with identical code in all scenarios.
Quoted 7 lines
With some help from my friend Claude, I've prepared a prototype that reuses my efiloader Rust crate to boot EFI stub images (bare Image, zboot, UKI) in the kernel: the EFI boot phase is invoked at kexec load time, and runs under the preceding kernel up until the point where
ExitBootServices()is called. Then, the actual kexec call will return fromExitBootServices()after shutting down the first kernel.
Quoted 7 lines
Running it inside a kthread is such a novel idea, I would have never thought to attempt that!
I've asked some folks here to take a look and try to test this with real DRTM capable HW. It seems very promising that it will work to me, and I surmize this is also close to boot a UKI?
It already works for UKIs as well.
The next step is to run it deprivileged - I think the arm64 stub code is already very close to being runnable in that manner.
Quoted 8 lines · Ard Biesheuvel
Quoted 3 lines
I've asked some folks here to take a look and try to test this with real DRTM capable HW. It seems very promising that it will work to me, and I surmize this is also close to boot a UKI?
It already works for UKIs as well.
The next step is to run it deprivileged - I think the arm64 stub code is already very close to being runnable in that manner.
Abhishek was able to test it on some Grace hardware, and investigate the DRTM. He was able to show it works, using some FW debugging to the serial port and the post-kexec dmesg:
<kexec>
INFO: DRTM service handler: version INFO: DRTM service handler: get error INFO: ++ DRTM service handler: TPM features INFO: ++ DRTM service handler: Min. mem. requirement features INFO: ++ DRTM service handler: DMA protection features INFO: ++ DRTM service handler: Boot PE ID features INFO: DRTM service handler: dynamic launch
[..]
[ 10.655030] DRTM: launch completed
So this solution is absolutely viable for DRTM kexec. Great!
He had a couple of issues, I will try to summarize them as I understood them.
1) ARM DRTM requires that the executing CPU be the boot CPU when launching the kernel. My patches enforced this in the EFI stub assuming that the EFI stub will be the same CPU as after exit boot services. Since the kthread has no CPU assignment it picks something random and fails these checks:
[ 3219.695710] kexec_efi: EFI stub: ERROR: DRTM: boot PE 0x20000 does not match current PE 0x430000 [ 3219.695726] kexec_efi: EFI stub: WARNING: DRTM: preparation failed, continuing without DRTM [ 3219.732742] kexec_efi: EFI image suspended at ExitBootServices(), system table @ 0x1001bff00090
The kthread this runs in picks a random CPU so it doesn't work. Abhishek was able to put a kthread_bind() in to always use the boot CPU
2) Most of our systems use 64K page size, so the restriction in the series is not great. Abhishek used a 4k predecessor kernel and confirmed he could boot a 64k successor
3) Some compile glitches:
1. arch/arm64/kernel/kexec_efi.c:175:35: error: 'PTE_ADDR_HIGH' undeclared (first use in this function); did you mean 'PTE_ADDR_LOW'?
2. KEXEC_EFI_STUB declares depends on ARM64_4K_PAGES but nothing about PA_BITS, so a 4K + 48-bit-PA config does not compile.
3. With rustc 1.85.0, which is what scripts/min-tool-version.sh asks for on arm64, the link fails:
ld: arch/arm64/kernel/kexec_efi_glue.o: undefined reference to `__rust_no_alloc_shim_is_unstable'
ld: rust/alloc.o: undefined reference to `__rust_alloc_error_handler_should_panic'
He used rustc 1.96.0 instead and it builds fine.
Thanks,
Jason
Quoted 24 lines · Jason Gunthorpe
Quoted 8 lines · Ard Biesheuvel
Quoted 3 lines
I've asked some folks here to take a look and try to test this with real DRTM capable HW. It seems very promising that it will work to me, and I surmize this is also close to boot a UKI?
It already works for UKIs as well.
The next step is to run it deprivileged - I think the arm64 stub code is already very close to being runnable in that manner.
Abhishek was able to test it on some Grace hardware, and investigate the DRTM. He was able to show it works, using some FW debugging to the serial port and the post-kexec dmesg:
<kexec>
INFO: DRTM service handler: version INFO: DRTM service handler: get error INFO: ++ DRTM service handler: TPM features INFO: ++ DRTM service handler: Min. mem. requirement features INFO: ++ DRTM service handler: DMA protection features INFO: ++ DRTM service handler: Boot PE ID features INFO: DRTM service handler: dynamic launch
Quoted 6 lines
[..] [ 10.655030] DRTM: launch completedSo this solution is absolutely viable for DRTM kexec. Great!
Excellent news!
Quoted 14 lines
He had a couple of issues, I will try to summarize them as I understood them.
1) ARM DRTM requires that the executing CPU be the boot CPU when launching the kernel. My patches enforced this in the EFI stub assuming that the EFI stub will be the same CPU as after exit boot services. Since the kthread has no CPU assignment it picks something random and fails these checks:
[ 3219.695710] kexec_efi: EFI stub: ERROR: DRTM: boot PE 0x20000 does not match current PE 0x430000 [ 3219.695726] kexec_efi: EFI stub: WARNING: DRTM: preparation failed, continuing without DRTM [ 3219.732742] kexec_efi: EFI image suspended at ExitBootServices(),
Quoted 6 lines
system table @
0x1001bff00090The kthread this runs in picks a random CPU so it doesn't work. Abhishek was able to put a
kthread_bind()in to always use the boot CPU
Interesting. I'm not sure this is a reliable workaround, though, given that the return from ExitBootServices() occurs as a result of another syscall(), and the kthread is long gone by then.
I think the reliable approach here is taking down all the other cores before doing the kexec.
Quoted 4 lines
2) Most of our systems use 64K page size, so the restriction in the series is not great. Abhishek used a 4k predecessor kernel and confirmed he could boot a 64k successor
I've dropped that requirement already - the TTBR0 side can just switch to 4k pages.
Quoted 5 lines
3) Some compile glitches:
1.
arch/arm64/kernel/kexec_efi.c:175:35: error: 'PTE_ADDR_HIGH' undeclared (first use in this function); did you mean 'PTE_ADDR_LOW'?
That is only #define'd when CONFIG_ARM64_PA_BITS_52 is set. I don't think we should be using that directly, though - I'll investigate.
Quoted 3 lines
2.
KEXEC_EFI_STUBdeclares depends onARM64_4K_PAGESbut nothing aboutPA_BITS, so a 4K + 48-bit-PA config does not compile.
Same problem, I suppose?
Quoted 11 lines
3. With rustc 1.85.0, which is what
scripts/min-tool-version.shasks for on arm64, the link fails:ld:
arch/arm64/kernel/kexec_efi_glue.o: undefined reference to `__rust_no_alloc_shim_is_unstable'ld:
rust/alloc.o: undefined reference to
`__rust_alloc_error_handler_should_panic'He used rustc 1.96.0 instead and it builds fine.
I think this is related to the use of the 'alloc' API, which my efiloader crate uses but does not exist in the same way in the kernel. I'll look into this as well.
In other news, I've added some other features to the prototype: x86_64 support, support for UKIs including sidecars etc (the kexec image loader now accepts a cpio archive which can be presented as the ESP) and some other improvements. This is highly in flux so let's compare notes often so things do not diverge unnecessarily.
Quoted 6 lines · Ard Biesheuvel
Interesting. I'm not sure this is a reliable workaround, though, given that the return from
ExitBootServices()occurs as a result of anothersyscall(), and the kthread is long gone by then.I think the reliable approach here is taking down all the other cores before doing the kexec.
Yeah, both parts need this.
The DRTM spec requires invoking the launch SMC on the boot CPU and all other CPUs must be powered off. The firmware is supposed to check this.
Quoted 5 lines
In other news, I've added some other features to the prototype:
x86_64support, support for UKIs including sidecars etc (the kexec image loader now accepts a cpio archive which can be presented as the ESP) and some other improvements. This is highly in flux so let's compare notes often so things do not diverge unnecessarily.
This seems great, please ping again and we can retest it. I also was just told the UKI flow was demo'd through there too including DRTM. It seems like a little change is needed on the DRTM series for UKI, I ill remark separately.
I like the idea of cpio for of all the parts, that seems flexible. Presumably we can do a signing check of each part in the kernel for those that want that?
Also when you are ready to post it I can ask here for some rust reviewers, we have developed quite a deep bench of experience.
Thanks,
Jason
Quoted 53 lines · Ard Biesheuvel
Hi Jason,
Thanks for chiming in.
Quoted 33 lines · Jason Gunthorpe
Quoted 9 lines · Pingfan Liu
*** The history ***
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
Quoted 4 lines
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/ImageI recently had an interesting discussion with Ard around DRTM for kexec and we sort of independently concluded that #1 would be the best (only?) option there.
All the implementations of DRTM today live in the EFI stub and intercept the boot process as it goes along. After ExitBootServices the DRTM implementation will launch the kernel in a different way. Even worse today's x86 version strongly requires EFI boot services to connect the Linux stub with a trampoline helper provided earlier in the boot chain.
A kexec flow that only works on decompressed vmlinux, with no option to run any EFI code, is going to be difficult to support. There is enough information and choices involved in DRTM that it is undesirable for the predecessor kernel to try and DRTM launch it on behalf of the successor, let alone trying to get the insane x86 trampolines into a kexec successor kernel.
Quoted 6 lines
Given those constraints entering the successor kernel through the normal EFI entry point is highly desirable. This would allow x86 to continue to provide the DRTM trampolines through an EFI mechanism and means the Linux EFI stub always handles the launch with identical code in all scenarios.
With some help from my friend Claude, I've prepared a prototype that reuses my efiloader Rust crate to boot EFI stub images (bare Image, zboot, UKI) in the kernel: the EFI boot phase is invoked at kexec load time, and runs under the preceding kernel up until the point where
ExitBootServices()is called. Then, the actual kexec call will return fromExitBootServices()after shutting down the first kernel.
Sorry, I haven't had time to go through it yet. But I'm curious how you would address the portability issues, especially those related to the console, that you pointed out in my emulator implementation.
Thanks,
Pingfan
Quoted 6 lines
There are some limitations (4k pages only,
CONTIG_ALLOCsupport required) but it seems to work as expected.I haven't looked at measured boot or DRTM specifics.
Hi Jason,
Hi Ard,
let me add my 2 ct as well.
Quoted 53 lines · On Tue, 13 Oct 2026 21:19:28 +0200 "Ard Biesheuvel" <[email protected]> wrote:
Hi Jason,
Thanks for chiming in.
Quoted 33 lines · Jason Gunthorpe
Quoted 9 lines · Pingfan Liu
*** The history ***
Nowadays, UEFI PE bootable images are becoming increasingly popular among distributions. Currently, we have several kinds of image format parsers in user space (kexec-tools). However, this approach breaks the integrity protection of the images. To address this integrity protection concern, several approaches have been proposed to resolve this issue, but none of them have been accepted upstream yet.
Quoted 4 lines
The summary of those approaches:
-1. UEFI service emulator for UEFI stub
-2. PE format parser in kernel
-3. Signing the arm64/boot/ImageI recently had an interesting discussion with Ard around DRTM for kexec and we sort of independently concluded that #1 would be the best (only?) option there.
All the implementations of DRTM today live in the EFI stub and intercept the boot process as it goes along. After ExitBootServices the DRTM implementation will launch the kernel in a different way. Even worse today's x86 version strongly requires EFI boot services to connect the Linux stub with a trampoline helper provided earlier in the boot chain.
A kexec flow that only works on decompressed vmlinux, with no option to run any EFI code, is going to be difficult to support. There is enough information and choices involved in DRTM that it is undesirable for the predecessor kernel to try and DRTM launch it on behalf of the successor, let alone trying to get the insane x86 trampolines into a kexec successor kernel.
Quoted 6 lines
Given those constraints entering the successor kernel through the normal EFI entry point is highly desirable. This would allow x86 to continue to provide the DRTM trampolines through an EFI mechanism and means the Linux EFI stub always handles the launch with identical code in all scenarios.
With some help from my friend Claude, I've prepared a prototype that reuses my efiloader Rust crate to boot EFI stub images (bare Image, zboot, UKI) in the kernel: the EFI boot phase is invoked at kexec load time, and runs under the preceding kernel up until the point where
ExitBootServices()is called. Then, the actual kexec call will return fromExitBootServices()after shutting down the first kernel.
I only took a brief look and cannot claim to fully understand your solution, yet. Nevertheless I'm pretty impressed. I also agree that this approach is by far the best, if we can get it to work.
The reason why I and Pingfan abandoned this approach and went for eBPF instead was due to security concerns. Our premise is/was that the EFI stub must not be able to harm the running kernel. Be it intentional or not. That's a guarantee eBPF with its verifier can give but a simple file signature can't.
I believe the way Ard ties execution of the EFI stub to module signature verification solves the "intentionally malicious" case. In the end it doesn't make sense to try to prevent a malicious EFI stub to be executed when an attacker could also load a malicious kernel module.
But that still leaves the "unintentional malicious" case. Meaning, that someone tries to be "smart" and does weird stuff in the EFI stub he knows it won't do any harm during cold boot, but that will cause problems to the kernel running the efiloader. IIUC Ard's implementation cannot catch such problems. But I expect it will be a total pain to debug them. Especially when it is caused by some out-of-tree stub.
To be honest, I'm not sure how this could be solved. I'm not even sure if it's worth trying. Nevertheless I believe it's worth having some sort of tainted flag. At least that would give developers a hint that some untrusted code was run without them spending ours of debugging.
Two more comments with my distro head on.
First, kdump is extremely important to us. So the final solution needs to be able to load a crash kernel as well.
Second, implementing the efiloader in Rust is not ideal. This prevents us to support the feature in older streams that don't support Rust4Linux.
Anyway, thanks for bringing up the topic again. I'm looking forward to see the next version.
Thanks
Philipp
Quoted 7 lines
There are some limitations (4k pages only,
CONTIG_ALLOCsupport required) but it seems to work as expected.I haven't looked at measured boot or DRTM specifics.
Quoted 5 lines · Philipp Rudo
The reason why I and Pingfan abandoned this approach and went for eBPF instead was due to security concerns. Our premise is/was that the EFI stub must not be able to harm the running kernel. Be it intentional or not. That's a guarantee eBPF with its verifier can give but a simple file signature can't.
This seems too much to me, I think the approach of signature verification is sufficient. If you can load a module then you don't need to fiddle with some covoluted EFI attack. Distros should include their EFI signing key in the kernel keyring so a standard UKI passes the test.
The eBPF approach fails from my perspective because it never actually runs the stub code or using the EFI entry point. My interest is to actually use the EFI entry point, not just treat it as some convoluted zip file.
Quoted 2 lines
But that still leaves the "unintentional malicious" case. Meaning, that someone tries to be "smart" and does weird stuff in the EFI stub
Buggy modules exist too, it is up the signer to take a position on that, IMHO. How can you have an "out of tree stub" if the only things loaded are signed by the kernel builder?
Regardles, Ard's suggestion to move the execution from a kthread to a user thread could provide enough isolation to mititgate even this..
Quoted 4 lines
Two more comments with my distro head on.
First, kdump is extremely important to us. So the final solution needs to be able to load a crash kernel as well.
And you want this to be a UKI too?
I'm not sure it is so good for crash robustness to have so much more complexity in the boot path..
Though I wonder if you can run the EFI flow when initially loading and staging the crash kernel? Then stop at the exit boot services and wait for a crash before jumping back into the flow.
Jason