git: 4b0c6fa0dcea - main - truss: Make control message header parsing more robust

From: Mark Johnston <markj_at_FreeBSD.org>
Date: Tue, 14 Jun 2022 16:01:12 UTC
The branch main has been updated by markj:

URL: https://cgit.FreeBSD.org/src/commit/?id=4b0c6fa0dceac797f43dffd5642c1aed727c6ea6

commit 4b0c6fa0dceac797f43dffd5642c1aed727c6ea6
Author:     Mark Johnston <markj@FreeBSD.org>
AuthorDate: 2022-06-14 15:34:57 +0000
Commit:     Mark Johnston <markj@FreeBSD.org>
CommitDate: 2022-06-14 16:00:59 +0000

    truss: Make control message header parsing more robust
    
    print_cmsg() was assuming that the control message chain is well-formed,
    but that isn't necessarily the case for sendmsg(2).  In particular, if
    cmsg_len is zero, print_cmsg() will loop forever.  Check for truncated
    headers and try to recover if possible.
    
    Reviewed by:    tuexen
    MFC after:      2 weeks
    Sponsored by:   The FreeBSD Foundation
    Differential Revision:  https://reviews.freebsd.org/D35476
---
 usr.bin/truss/syscalls.c | 10 ++++++++++
 1 file changed, 10 insertions(+)

diff --git a/usr.bin/truss/syscalls.c b/usr.bin/truss/syscalls.c
index 171bed54edb0..0a3f616294af 100644
--- a/usr.bin/truss/syscalls.c
+++ b/usr.bin/truss/syscalls.c
@@ -1480,6 +1480,16 @@ print_cmsgs(FILE *fp, pid_t pid, bool receive, struct msghdr *msghdr)
 	for (cmsghdr = CMSG_FIRSTHDR(msghdr);
 	   cmsghdr != NULL;
 	   cmsghdr = CMSG_NXTHDR(msghdr, cmsghdr)) {
+		if (cmsghdr->cmsg_len < sizeof(*cmsghdr)) {
+			fprintf(fp, "{<invalid cmsg, len=%u>}",
+			    cmsghdr->cmsg_len);
+			if (cmsghdr->cmsg_len == 0) {
+				/* Avoid looping forever. */
+				break;
+			}
+			continue;
+		}
+
 		level = cmsghdr->cmsg_level;
 		type = cmsghdr->cmsg_type;
 		len = cmsghdr->cmsg_len;