]> git.ipfire.org Git - thirdparty/libcgroup.git/commitdiff
api: Fix unsafe call to strncat in cgroup_get_procs() and cgroup_get_threads()
authorTom Hromatka <tom.hromatka@oracle.com>
Mon, 12 Jan 2026 16:41:47 +0000 (09:41 -0700)
committerKamalesh Babulal <kamalesh.babulal@oracle.com>
Tue, 10 Mar 2026 16:38:03 +0000 (22:08 +0530)
TJH - the text below was autogenerated by Copilot.

In general, when using strncat, the third argument must reflect the
remaining space in the destination buffer minus one byte to keep room
for the terminating NUL. The correct upper bound is therefore
sizeof(dest) - strlen(dest) - 1. This ensures strncat cannot write past
the end of the buffer, even including the terminator it always appends.

For this code, the minimal, behavior-preserving fix is to adjust the
strncat calls that append constant suffixes to cgroup_path.
Specifically:

In cgroup_get_procs, change FILENAME_MAX - strlen(cgroup_path) to
FILENAME_MAX - strlen(cgroup_path) - 1.
In cgroup_get_threads, make the same adjustment.
No other logic needs to change; the functions will still append the same
suffixes, but the maximum number of characters strncat is allowed to
copy will correctly reserve one byte for the NUL terminator. If
cg_build_path already fills nearly the entire buffer, the new limit
prevents overflow and may result in a truncated path; if such truncation
should be handled explicitly, additional error checks on
strlen(cgroup_path) relative to FILENAME_MAX could be added, but that
would go beyond the minimal fix requested.

These changes are all within src/api.c, in the region containing
cgroup_get_procs and cgroup_get_threads, and do not require any new
includes or helper functions.

Co-authored-by: Copilot Autofix powered by AI <62310815+github-advanced-security[bot]@users.noreply.github.com>
Signed-off-by: Tom Hromatka <tom.hromatka@oracle.com>
Signed-off-by: Kamalesh Babulal <kamalesh.babulal@oracle.com>
src/api.c

index f23044a2595beb5857b2f46d956d1a8425e950f8..e1f593bf0a29d0fec31b58c2b41bc6fe197a56f0 100644 (file)
--- a/src/api.c
+++ b/src/api.c
@@ -6391,7 +6391,7 @@ int cgroup_get_procs(const char *name, const char *controller, pid_t **pids, int
        char cgroup_path[FILENAME_MAX];
 
        cg_build_path(name, cgroup_path, controller);
-       strncat(cgroup_path, "/cgroup.procs", FILENAME_MAX-strlen(cgroup_path));
+       strncat(cgroup_path, "/cgroup.procs", FILENAME_MAX - strlen(cgroup_path) - 1);
 
        return read_pids(cgroup_path, pids, size);
 }
@@ -6401,7 +6401,7 @@ int cgroup_get_threads(const char *name, const char *controller, pid_t **pids, i
        char cgroup_path[FILENAME_MAX];
 
        cg_build_path(name, cgroup_path, controller);
-       strncat(cgroup_path, "/cgroup.threads", FILENAME_MAX-strlen(cgroup_path));
+       strncat(cgroup_path, "/cgroup.threads", FILENAME_MAX - strlen(cgroup_path) - 1);
 
        return read_pids(cgroup_path, pids, size);
 }