autofs-5.1.8 - fix possible use after free in handle_mounts_exit()

From: Ian Kent <raven@themaw.net>

Don't free the submount map entry until it's no longer used.

Signed-off-by: Ian Kent <raven@themaw.net>
---
 CHANGELOG          |    1 +
 daemon/automount.c |   20 ++++++++++----------
 2 files changed, 11 insertions(+), 10 deletions(-)

diff --git a/CHANGELOG b/CHANGELOG
index e611b677..81c4d0c9 100644
--- a/CHANGELOG
+++ b/CHANGELOG
@@ -85,6 +85,7 @@
 - change to use printf functions in amd parser.
 - dont call umount_subtree_mounts() on parent at umount.
 - dont take parent source lock at mount shutdown.
+- fix possible use after free in handle_mounts_exit().
 
 19/10/2021 autofs-5.1.8
 - add xdr_exports().
diff --git a/daemon/automount.c b/daemon/automount.c
index d12625d8..beb552f5 100644
--- a/daemon/automount.c
+++ b/daemon/automount.c
@@ -1787,16 +1787,6 @@ static void handle_mounts_cleanup(void *arg)
 
 	info(logopt, "shut down path %s", ap->path);
 
-	/*
-	 * Submounts are detached threads and don't belong to the
-	 * master map entry list so we need to free their resources
-	 * here.
-	 */
-	if (submount) {
-		master_free_mapent_sources(ap->entry, 1);
-		master_free_mapent(ap->entry);
-	}
-
 	if (clean) {
 		if (rmdir(ap->path) == -1) {
 			char *estr = strerror_r(errno, buf, MAX_ERR_BUF);
@@ -1808,6 +1798,16 @@ static void handle_mounts_cleanup(void *arg)
 	master_remove_mapent(ap->entry);
 	master_source_unlock(ap->entry);
 
+	/*
+	 * Submounts are detached threads and don't belong to the
+	 * master map entry list so we need to free their resources
+	 * here.
+	 */
+	if (submount) {
+		master_free_mapent_sources(ap->entry, 1);
+		master_free_mapent(ap->entry);
+	}
+
 	/*
 	 * If we are not a submount send a signal to the signal handler
 	 * so it can join with any completed handle_mounts() threads and