From cee82f83cfe883f4e24132a0cf02f5989ffc281e Mon Sep 17 00:00:00 2001 From: Tobias Stoeckmann Date: Wed, 26 Mar 2025 15:51:22 +0100 Subject: [PATCH] libkmod: fix buffer-overflow in weakdep_to_char Fix another buffer overflow which can happen if no weak dependencies exist. Use the same logic as found in softdep_to_char to cover this case as well. Signed-off-by: Tobias Stoeckmann Link: https://github.com/kmod-project/kmod/pull/327 Signed-off-by: Lucas De Marchi (cherry picked from commit bb8aa10a73eb274aec7401f2384dbabb98810820) --- libkmod/libkmod-config.c | 16 +++++++++------- .../etc/modprobe.d/dumb-weakdep.conf | 1 + .../rootfs-pristine/test-weakdep/modprobe-c.txt | 1 + 3 files changed, 11 insertions(+), 7 deletions(-) diff --git a/libkmod/libkmod-config.c b/libkmod/libkmod-config.c index e52aae77..ee1cb946 100644 --- a/libkmod/libkmod-config.c +++ b/libkmod/libkmod-config.c @@ -574,28 +574,30 @@ static char *softdep_to_char(struct kmod_softdep *dep) static char *weakdep_to_char(struct kmod_weakdep *dep) { - size_t sz; + size_t sz = 1; /* at least '\0' */ + size_t sz_weak; const char *start, *end; char *s, *itr; /* Rely on the fact that dep->weak[] is a strv that points to a contiguous buffer */ if (dep->n_weak > 0) { start = dep->weak[0]; - end = dep->weak[dep->n_weak - 1] + strlen(dep->weak[dep->n_weak - 1]) + 1; - sz = end - start; + end = dep->weak[dep->n_weak - 1] + strlen(dep->weak[dep->n_weak - 1]); + sz_weak = end - start; + sz += sz_weak; } else - sz = 0; + sz_weak = 0; itr = s = malloc(sz); if (s == NULL) return NULL; - if (sz) { + if (sz_weak) { char *p; /* include last '\0' */ - memcpy(itr, dep->weak[0], sz); - for (p = itr; p < itr + sz - 1; p++) { + memcpy(itr, dep->weak[0], sz_weak); + for (p = itr; p < itr + sz_weak; p++) { if (*p == '\0') *p = ' '; } diff --git a/testsuite/rootfs-pristine/test-weakdep/etc/modprobe.d/dumb-weakdep.conf b/testsuite/rootfs-pristine/test-weakdep/etc/modprobe.d/dumb-weakdep.conf index 181714ab..6fa8355d 100644 --- a/testsuite/rootfs-pristine/test-weakdep/etc/modprobe.d/dumb-weakdep.conf +++ b/testsuite/rootfs-pristine/test-weakdep/etc/modprobe.d/dumb-weakdep.conf @@ -1 +1,2 @@ +weakdep mod-loop-a weakdep mod-loop-b mod-loop-a mod-simple diff --git a/testsuite/rootfs-pristine/test-weakdep/modprobe-c.txt b/testsuite/rootfs-pristine/test-weakdep/modprobe-c.txt index 82485a61..b34699fd 100644 --- a/testsuite/rootfs-pristine/test-weakdep/modprobe-c.txt +++ b/testsuite/rootfs-pristine/test-weakdep/modprobe-c.txt @@ -1,3 +1,4 @@ +weakdep mod_loop_a weakdep mod_loop_b mod-loop-a mod-simple weakdep mod_weakdep mod-simple -- 2.47.2