Fix CVE-2026-42007 (Dovecot Security Advisory 3/2026, Sieve editheader
use-after-free and heap over-read)

From 69bac9cd6d4ac09100ee50c98052be1437f1da29 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Date: Tue, 14 Apr 2026 12:58:08 +0200
Subject: [PATCH] lib-sieve: util: edit-mail - Fix writing to freed memory

From a44ba381619a06416ce3f34eae9765de46ece5d9 Mon Sep 17 00:00:00 2001
From: Timo Sirainen <timo.sirainen@open-xchange.com>
Date: Fri, 1 May 2026 06:28:33 +0000
Subject: [PATCH] lib-sieve: edit_mail_headers_parse() - Fix info leak via
 NUL-truncated header copy

Index: src/lib-sieve/util/edit-mail.c
--- src/lib-sieve/util/edit-mail.c.orig
+++ src/lib-sieve/util/edit-mail.c
@@ -550,8 +550,9 @@ edit_mail_header_field_create(struct edit_mail *edmail
 					      &field->body_offset);
 
 		/* Copy to new field */
-		field->data = i_strndup(str_data(data), str_len(data));
 		field->size = str_len(data);
+		field->data = i_malloc(field->size + 1);
+		memcpy(field->data, str_data(data), field->size);
 		field->virtual_size = (edmail->crlf ?
 				       field->size : field->size + lines);
 		field->lines = lines;
@@ -828,8 +829,9 @@ static int edit_mail_headers_parse(struct edit_mail *e
 
 			field->size = str_len(hdr_data);
 			field->virtual_size = field->size + vsize_diff;
-			field->data = i_strndup(str_data(hdr_data),
-						field->size);
+			field->data = i_malloc(field->size + 1);
+			memcpy(field->data, str_data(hdr_data),
+			       field->size);
 			field->offset = offset;
 			field->lines = lines;
 
@@ -887,7 +889,17 @@ static int edit_mail_headers_parse(struct edit_mail *e
 		}
 	}
 
-	/* Rebuild header index */
+	/* Rebuild header index. Reset first pointers before rebuilding so that
+	   the actual first occurrence in the final list is used. Without this,
+	   a snapshot's pre-set first pointer may refer to an appended field
+	   that sits later in the list than a parsed field with the same header,
+	   causing deleteheader to miss the parsed fields while still freeing
+	   the header_index — leaving stale field_idx->header pointers. */
+	struct _header_index *hidx = edmail->headers_head;
+	while (hidx != NULL) {
+		hidx->first = NULL;
+		hidx = hidx->next;
+	}
 	current = edmail->header_fields_head;
 	while (current != NULL) {
 		if (current->header->first == NULL)
