From 8d1baba54668972641eb158981f11d780999f589 Mon Sep 17 00:00:00 2001 From: Robert Stepanek Date: Thu, 2 May 2024 10:21:58 +0200 Subject: [PATCH] message.c: do not read past header buffer when patching CTE header --- imap/message.c | 26 ++++++++++++++++++++------ 1 file changed, 20 insertions(+), 6 deletions(-) diff --git a/imap/message.c b/imap/message.c index 0c91fbee17..a5b633e190 100644 --- a/imap/message.c +++ b/imap/message.c @@ -950,12 +950,26 @@ static int message_parse_headers(struct msg *msg, struct body *body, /* If we're encoding binary, replace "binary" with "base64" in CTE header body */ - if (msg->encode && - !strcmpsafe(body->encoding, "BINARY")) { - char *p = (char*) - stristr(msg->base + body->header_offset + - (next - headers.s) + 26, - "binary"); + if (msg->encode && !strcmpsafe(body->encoding, "BINARY")) { + // Determine the start and end of the CTE header value + const char *hdr_val = msg->base + body->header_offset + + (next - headers.s) + 26; + const char *hdr_end = hdr_val; + const char *msghdr_end = + msg->base + body->header_offset + body->header_size; + for (; hdr_end < msghdr_end; hdr_end++) { + if (hdr_end[0] == '\r') { + if (hdr_end + 2 < msghdr_end && + hdr_end[1] == '\n' && + hdr_end[2] != ' ' && hdr_end[2] != '\t') { + hdr_end += 2; + break; + } + } + } + // Replace header value + char *p = + (char *)strinstr(hdr_val, hdr_end - hdr_val, "binary"); if (p) memcpy(p, "base64", 6); else