[PATCH] libsemanage: direct_api: clamp write length in ERR_CHLD_STDERR()

Stephen Smalley <[email protected]>
Newsgroups org.kernel.vger.selinux
Message-ID <[email protected]>
snprintf() returns the number of bytes it would have written on
truncation, which can exceed the buffer size, and can potentially
return < 0 on other error conditions. Clamp the write length to the
buffer size less the terminator and only write if snprintf() actually
wrote bytes to the buffer.

Signed-off-by: Stephen Smalley <[email protected]>
---
 libsemanage/src/direct_api.c | 12 ++++++++++--
 1 file changed, 10 insertions(+), 2 deletions(-)

diff --git a/libsemanage/src/direct_api.c b/libsemanage/src/direct_api.c
index b87b87e7..6c84b23c 100644
--- a/libsemanage/src/direct_api.c
+++ b/libsemanage/src/direct_api.c
@@ -618,11 +618,19 @@ static int read_from_pipe_to_data(semanage_handle_t *sh, size_t initial_len,
 				  "libsemanage.semanage_pipe_data: ",          \
 				  strlen("libsemanage.semanage_pipe_data: ")); \
 		n = snprintf(buf, sizeof(buf), __VA_ARGS__);                   \
-		(void)!write_full(err_fd[PIPE_WRITE], buf, n);                 \
+		if (n > 0) {                                                   \
+			if ((size_t)n >= sizeof(buf))                          \
+				n = sizeof(buf) - 1;                           \
+			(void)!write_full(err_fd[PIPE_WRITE], buf, (size_t)n); \
+		}                                                              \
 		if (errsv) {                                                   \
 			errno = errsv;                                         \
 			n = snprintf(buf, sizeof(buf), " (%m).");              \
-			(void)!write_full(err_fd[PIPE_WRITE], buf, n);         \
+			if (n > 0) {                                           \
+				if ((size_t)n >= sizeof(buf))                  \
+					n = sizeof(buf) - 1;                   \
+				(void)!write_full(err_fd[PIPE_WRITE], buf, n); \
+			}                                                      \
 		}                                                              \
 		(void)!write_full(err_fd[PIPE_WRITE], "\n", strlen("\n"));     \
 		(void)!fsync(err_fd[PIPE_WRITE]);                              \
-- 
2.55.0
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.