From 0aec82c2b686f0b1793deed43b46524fe2e8b5a7 Mon Sep 17 00:00:00 2001
From: Giuseppe Scrivano <gscrivan@redhat.com>
Date: Tue, 4 Feb 2025 10:19:07 +0100
Subject: [PATCH] krun: fix CVE-2025-24965

make sure the opened .krun_config.json is below the rootfs directory
and we don't follow any symlink.

Signed-off-by: Giuseppe Scrivano <gscrivan@redhat.com>

[vlefebvre: Adapt patch for 1.14]
---
 src/libcrun/handlers/krun.c | 10 +++++++++-
 1 file changed, 9 insertions(+), 1 deletion(-)

Index: crun-1.14/src/libcrun/handlers/krun.c
===================================================================
--- crun-1.14.orig/src/libcrun/handlers/krun.c
+++ crun-1.14/src/libcrun/handlers/krun.c
@@ -43,6 +43,8 @@
 /* libkrun has a hard-limit of 8 vCPUs per microVM. */
 #define LIBKRUN_MAX_VCPUS 8
 
+#define KRUN_CONFIG_FILE ".krun_config.json"
+
 struct krun_config
 {
   void *handle;
@@ -193,6 +195,7 @@ libkrun_configure_container (void *cooki
       cleanup_free char *origin_config_path = NULL;
       cleanup_free char *state_dir = NULL;
       cleanup_free char *config = NULL;
+      cleanup_close int fd = -1;
       size_t config_size;
 
       state_dir = libcrun_get_state_directory (context->state_root, context->id);
@@ -207,9 +210,15 @@ libkrun_configure_container (void *cooki
       if (UNLIKELY (ret < 0))
         return ret;
 
-      ret = write_file_at (rootfsfd, ".krun_config.json", config, config_size, err);
+      /* CVE-2025-24965: the content below rootfs cannot be trusted because it is controlled by the user.  We
+         must ensure the file is opened below the rootfs directory.  */
+      fd = safe_openat (rootfsfd, rootfs, strlen(rootfs), KRUN_CONFIG_FILE, WRITE_FILE_DEFAULT_FLAGS | O_NOFOLLOW, 0700, err);
+      if (UNLIKELY (fd < 0))
+        return fd;
+
+      ret = safe_write (fd, config, config_size);
       if (UNLIKELY (ret < 0))
-        return ret;
+        return crun_make_error (err, errno, "writing file `%s`", KRUN_CONFIG_FILE);
     }
 
   if (phase != HANDLER_CONFIGURE_AFTER_MOUNTS)
Index: crun-1.14/src/libcrun/utils.h
===================================================================
--- crun-1.14.orig/src/libcrun/utils.h
+++ crun-1.14/src/libcrun/utils.h
@@ -55,6 +55,8 @@
 #define LIKELY(x) __builtin_expect ((x), 1)
 #define UNLIKELY(x) __builtin_expect ((x), 0)
 
+#define WRITE_FILE_DEFAULT_FLAGS (O_CLOEXEC | O_CREAT | O_TRUNC | O_WRONLY)
+
 __attribute__ ((malloc)) static inline void *
 xmalloc (size_t size)
 {
