From c07e961d40942635ef4b6e75e8da8b101865c148 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Ond=C5=99ej=20Kuzn=C3=ADk?= <ondra@mistotebe.net>
Date: Thu, 7 Jul 2022 16:42:10 +0100
Subject: [PATCH] ITS#9876 Some more leaks plugged

---
 clients/tools/ldapsearch.c |  7 ++++---
 libraries/libldap/deref.c  | 15 ++++-----------
 2 files changed, 8 insertions(+), 14 deletions(-)

diff --git a/clients/tools/ldapsearch.c b/clients/tools/ldapsearch.c
index a0ca0d79f..02b49bd1c 100644
--- a/clients/tools/ldapsearch.c
+++ b/clients/tools/ldapsearch.c
@@ -1866,12 +1866,13 @@ again:
 			if ( ldapsync && sync_slimit != -1 &&
 					nresponses_psearch >= sync_slimit ) {
 				BerElement *msgidber = NULL;
-				struct berval *msgidvalp = NULL;
+				struct berval msgidval;
 				msgidber = ber_alloc_t(LBER_USE_DER);
 				ber_printf(msgidber, "{i}", msgid);
-				ber_flatten(msgidber, &msgidvalp);
+				ber_flatten2( msgidber, &msgidval, 0 );
 				ldap_extended_operation(ld, LDAP_EXOP_CANCEL,
-					msgidvalp, NULL, NULL, &cancel_msgid);
+					&msgidval, NULL, NULL, &cancel_msgid);
+				ber_free( msgidber, 1 );
 				nresponses_psearch = -1;
 			}
 		}
diff --git a/libraries/libldap/deref.c b/libraries/libldap/deref.c
index 7d3471ad3..f187a9fd4 100644
--- a/libraries/libldap/deref.c
+++ b/libraries/libldap/deref.c
@@ -160,7 +160,8 @@ ldap_parse_derefresponse_control(
 	LDAPControl	*ctrl,
 	LDAPDerefRes	**drp2 )
 {
-	BerElement *ber;
+	BerElementBuffer berbuf;
+	BerElement *ber = (BerElement *)&berbuf;
 	ber_tag_t tag;
 	ber_len_t len;
 	char *last;
@@ -172,13 +173,8 @@ ldap_parse_derefresponse_control(
 		return LDAP_PARAM_ERROR;
 	}
 
-	/* Create a BerElement from the berval returned in the control. */
-	ber = ber_init( &ctrl->ldctl_value );
-
-	if ( ber == NULL ) {
-		ld->ld_errno = LDAP_NO_MEMORY;
-		return ld->ld_errno;
-	}
+	/* Set up a BerElement from the berval returned in the control. */
+	ber_init2( ber, &ctrl->ldctl_value, 0 );
 
 	/* Extract the count and cookie from the control. */
 	drp = &drhead;
@@ -193,7 +189,6 @@ ldap_parse_derefresponse_control(
 		dr = LDAP_CALLOC( 1, sizeof(LDAPDerefRes) );
 		if ( dr == NULL ) {
 			ldap_derefresponse_free( drhead );
-			ber_free( ber, 1 );
 			*drp2 = NULL;
 			ld->ld_errno = LDAP_NO_MEMORY;
 			return ld->ld_errno;
@@ -244,8 +239,6 @@ ldap_parse_derefresponse_control(
 	tag = 0;
 
 done:;
-        ber_free( ber, 1 );
-
 	if ( tag == LBER_ERROR ) {
 		if ( drhead != NULL ) {
 			ldap_derefresponse_free( drhead );
-- 
2.33.0

