[RFC v2 1/5] kexec_file: allow to place kexec_buf randomly

From: Coiby Xu
Date: Fri Nov 04 2022 - 07:31:24 EST


Currently, kexec_buf is placed in order which means for the same
machine, the info in the kexec_buf is always located at the same
position each time the machine is booted. This may cause a risk for
sensitive information like LUKS volume key. Now struct kexec_buf has a
new field random which indicates it's supposed to be placed in a random
position.

Suggested-by: Jan Pazdziora <jpazdziora@xxxxxxxxxx>
Signed-off-by: Coiby Xu <coxu@xxxxxxxxxx>
---
include/linux/kexec.h | 2 ++
kernel/kexec_file.c | 15 +++++++++++++++
2 files changed, 17 insertions(+)

diff --git a/include/linux/kexec.h b/include/linux/kexec.h
index 13e6c4b58f07..c0edb64bf6c4 100644
--- a/include/linux/kexec.h
+++ b/include/linux/kexec.h
@@ -171,6 +171,7 @@ int kexec_image_post_load_cleanup_default(struct kimage *image);
* @buf_min: The buffer can't be placed below this address.
* @buf_max: The buffer can't be placed above this address.
* @top_down: Allocate from top of memory.
+ * @random: Place the buffer at a random position.
*/
struct kexec_buf {
struct kimage *image;
@@ -182,6 +183,7 @@ struct kexec_buf {
unsigned long buf_min;
unsigned long buf_max;
bool top_down;
+ bool random;
};

int kexec_load_purgatory(struct kimage *image, struct kexec_buf *kbuf);
diff --git a/kernel/kexec_file.c b/kernel/kexec_file.c
index a7b411c22f19..ed9fcc369312 100644
--- a/kernel/kexec_file.c
+++ b/kernel/kexec_file.c
@@ -25,6 +25,7 @@
#include <linux/elfcore.h>
#include <linux/kernel.h>
#include <linux/kernel_read_file.h>
+#include <linux/prandom.h>
#include <linux/syscalls.h>
#include <linux/vmalloc.h>
#include "kexec_internal.h"
@@ -412,6 +413,16 @@ SYSCALL_DEFINE5(kexec_file_load, int, kernel_fd, int, initrd_fd,
return ret;
}

+static unsigned long kexec_random_start(unsigned long start, unsigned long end)
+{
+ unsigned long temp_start;
+ unsigned short i;
+
+ get_random_bytes(&i, sizeof(unsigned short));
+ temp_start = start + (end - start) / USHRT_MAX * i;
+ return temp_start;
+}
+
static int locate_mem_hole_top_down(unsigned long start, unsigned long end,
struct kexec_buf *kbuf)
{
@@ -420,6 +431,8 @@ static int locate_mem_hole_top_down(unsigned long start, unsigned long end,

temp_end = min(end, kbuf->buf_max);
temp_start = temp_end - kbuf->memsz;
+ if (kbuf->random)
+ temp_start = kexec_random_start(temp_start, temp_end);

do {
/* align down start */
@@ -457,6 +470,8 @@ static int locate_mem_hole_bottom_up(unsigned long start, unsigned long end,
unsigned long temp_start, temp_end;

temp_start = max(start, kbuf->buf_min);
+ if (kbuf->random)
+ temp_start = kexec_random_start(temp_start, end);

do {
temp_start = ALIGN(temp_start, kbuf->buf_align);
--
2.37.3