From f99b6fce390b594bad336bdbd61b8ca5024c38f6 Mon Sep 17 00:00:00 2001
From: Jakub Hrozek <jhrozek@redhat.com>
Date: Wed, 20 Sep 2017 22:26:20 +0200
Subject: [PATCH] GPO: Don't use freed LDAPURLDesc if domain for AD DC cannot
 be found

If a referral returned during AD GPO processing cannot be assigned to a
known domain, at the moment SSSD accesses memory that was freed
previously with ldap_free_urldesc().

This patch moves the ldap_free_urldesc() call to both the error handler
and the success branch after we are done working with the LDAPURLDesc
instance.
---
 src/providers/ad/ad_gpo.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/providers/ad/ad_gpo.c b/src/providers/ad/ad_gpo.c
index 2ee284bdc..a5237f6fa 100644
--- a/src/providers/ad/ad_gpo.c
+++ b/src/providers/ad/ad_gpo.c
@@ -4354,7 +4354,7 @@ ad_gpo_get_sd_referral_send(TALLOC_CTX *mem_ctx,
     struct tevent_req *req;
     struct ad_gpo_get_sd_referral_state *state;
     struct tevent_req *subreq;
-    LDAPURLDesc *lud;
+    LDAPURLDesc *lud = NULL;
 
     req = tevent_req_create(mem_ctx, &state,
                             struct ad_gpo_get_sd_referral_state);
@@ -4390,15 +4390,18 @@ ad_gpo_get_sd_referral_send(TALLOC_CTX *mem_ctx,
      */
     state->ref_domain = find_domain_by_name(state->host_domain,
                                             lud->lud_host, true);
-    ldap_free_urldesc(lud);
     if (!state->ref_domain) {
         DEBUG(SSSDBG_CRIT_FAILURE,
               "Could not find domain matching [%s]\n",
               lud->lud_host);
+        ldap_free_urldesc(lud);
         ret = EIO;
         goto done;
     }
 
+    ldap_free_urldesc(lud);
+    lud = NULL;
+
     state->conn = ad_get_dom_ldap_conn(state->access_ctx->ad_id_ctx,
                                        state->ref_domain);
     if (!state->conn) {
