From d4d11afa436f1a0b4e4defc021c24e5992b0645f Mon Sep 17 00:00:00 2001 From: Oskari Pirhonen Date: Sun, 6 Aug 2023 19:58:11 -0500 Subject: egetcwd: fix some edge cases - Ensure all potentially 21 chars + NUL from "/proc/%i/cwd" fit in its buffer - Use snprintf(3) instead of sprintf(3) to fill in the buffer - readlink(2) does not add a NUL terminator, so ensure it only writes up to the allocated length - 1 - Use a more descriptive name for the return value of readlink(2) Signed-off-by: Oskari Pirhonen Closes: https://github.com/gentoo/sandbox/pull/24 Signed-off-by: Mike Gilbert --- libsandbox/libsandbox.c | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/libsandbox/libsandbox.c b/libsandbox/libsandbox.c index 6a7368c..9705db1 100644 --- a/libsandbox/libsandbox.c +++ b/libsandbox/libsandbox.c @@ -349,14 +349,14 @@ char *egetcwd(char *buf, size_t size) /* If tracing a child, our cwd may not be the same as the child's */ if (trace_pid) { - char proc[20]; - sprintf(proc, "/proc/%i/cwd", trace_pid); - ssize_t ret = readlink(proc, buf, size); - if (ret == -1) { + char proc[22]; + snprintf(proc, sizeof(proc), "/proc/%i/cwd", trace_pid); + ssize_t link_len = readlink(proc, buf, size - 1); + if (link_len == -1) { errno = ESRCH; return NULL; } - buf[ret] = '\0'; + buf[link_len] = '\0'; return buf; } -- cgit v1.2.3-65-gdbad