From 2fbd22984f3074e55646f08bdaedbef4fe4d14f4 Mon Sep 17 00:00:00 2001 From: Peter Hutterer Date: Wed, 30 Aug 2023 08:41:53 +1000 Subject: [PATCH] util: fix iobuf_append_fd OOB when we have too many fds Cannot happen in deploymentts since we never have more than one anyway. Fixes #43 --- src/util-io.c | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/src/util-io.c b/src/util-io.c index c873c02..0fd7ae7 100644 --- a/src/util-io.c +++ b/src/util-io.c @@ -281,7 +281,7 @@ int iobuf_append_fd(struct iobuf *buf, int fd) { /* Array must remain terminated by -1 */ - for (size_t idx = 0; idx < sizeof(buf->fds) - 1; idx ++) { + for (size_t idx = 0; idx < ARRAY_LENGTH(buf->fds) - 1; idx ++) { if (buf->fds[idx] == -1) { int f = dup(fd); if (f == -1) @@ -629,6 +629,29 @@ MUNIT_TEST(test_iobuf_append_fd) return MUNIT_OK; } +MUNIT_TEST(test_iobuf_append_fd_too_many) +{ + _cleanup_fclose_ FILE *fp = tmpfile(); + int fd = fileno(fp); + + _cleanup_iobuf_ struct iobuf *buf = iobuf_new(20); + const size_t nfds = ARRAY_LENGTH(buf->fds); + int *last_fd = &buf->fds[nfds - 1]; /* always -1 */ + int err = 0; + size_t count = 0; + + /* 32 fds hardcoded in the struct, last one is always -1 */ + for (count = 0; err == 0 && count < nfds + 1; count++) { + err = iobuf_append_fd(buf, fd); + munit_assert_int(*last_fd, ==, -1); + } + + munit_assert_int(count, ==, 32); + munit_assert_int(err, ==, -ENOMEM); + + return MUNIT_OK; +} + MUNIT_TEST(test_iobuf_recv_fd) { int fds[2];