From 0b958460c108542eba1765c9438c8f5a8361a509 Mon Sep 17 00:00:00 2001
From: Joseph Sutton <josephsutton@catalyst.net.nz>
Date: Thu, 17 Feb 2022 11:13:38 +1300
Subject: [PATCH 17/18] CVE-2022-32745 s4/dsdb/util: Don't call memcpy() with a
 NULL pointer

Doing so is undefined behaviour.

BUG: https://bugzilla.samba.org/show_bug.cgi?id=15008

Signed-off-by: Joseph Sutton <josephsutton@catalyst.net.nz>
---
 source4/dsdb/samdb/ldb_modules/util.c | 12 ++++++++----
 1 file changed, 8 insertions(+), 4 deletions(-)

diff --git a/source4/dsdb/samdb/ldb_modules/util.c b/source4/dsdb/samdb/ldb_modules/util.c
index 5d418efcd52..af412f55f98 100644
--- a/source4/dsdb/samdb/ldb_modules/util.c
+++ b/source4/dsdb/samdb/ldb_modules/util.c
@@ -1546,15 +1546,19 @@ int dsdb_get_expected_new_values(TALLOC_CTX *mem_ctx,
 
 	for (i = 0; i < msg->num_elements; i++) {
 		if (ldb_attr_cmp(msg->elements[i].name, attr_name) == 0) {
+			const struct ldb_message_element *tmp_el = &msg->elements[i];
 			if ((operation == LDB_MODIFY) &&
-			    (LDB_FLAG_MOD_TYPE(msg->elements[i].flags)
+			    (LDB_FLAG_MOD_TYPE(tmp_el->flags)
 						== LDB_FLAG_MOD_DELETE)) {
 				continue;
 			}
+			if (tmp_el->values == NULL || tmp_el->num_values == 0) {
+				continue;
+			}
 			memcpy(v,
-			       msg->elements[i].values,
-			       msg->elements[i].num_values);
-			v += msg->elements[i].num_values;
+			       tmp_el->values,
+			       tmp_el->num_values);
+			v += tmp_el->num_values;
 		}
 	}
 
-- 
2.35.0