From 264326de571e0eff1d8003f882bad4cdf1a9230d Mon Sep 17 00:00:00 2001
From: "Todd C. Miller" <Todd.Miller@sudo.ws>
Date: Thu, 10 Nov 2022 14:55:56 -0700
Subject: [PATCH] Fix a potential use-after-free bug with cvtsudoers filtering.
 In role_to_sudoers() when merging a privilege to the previous one where the
 runas lists are the same we need to re-use the runas lists of the last
 command in the previous privilege, not the first. Otherwise, the check in
 free_cmndspec() will not notice the re-used runas lists.  Reported/analyzed
 by Sohom Datta.  GitHub issue #198.

---
 plugins/sudoers/parse_ldif.c | 8 ++++----
 1 file changed, 4 insertions(+), 4 deletions(-)

diff --git a/plugins/sudoers/parse_ldif.c b/plugins/sudoers/parse_ldif.c
index 5d2a79163..2b7109294 100644
--- a/plugins/sudoers/parse_ldif.c
+++ b/plugins/sudoers/parse_ldif.c
@@ -432,11 +432,11 @@ role_to_sudoers(struct sudoers_parse_tree *parse_tree, struct sudo_role *role,
 	struct privilege *prev_priv = TAILQ_LAST(&us->privileges, privilege_list);
 	if (reuse_runas) {
 	    /* Runas users and groups same if as in previous privilege. */
-	    struct member_list *runasuserlist =
-		TAILQ_FIRST(&prev_priv->cmndlist)->runasuserlist;
-	    struct member_list *runasgrouplist =
-		TAILQ_FIRST(&prev_priv->cmndlist)->runasgrouplist;
 	    struct cmndspec *cmndspec = TAILQ_FIRST(&priv->cmndlist);
+	    const struct cmndspec *prev_cmndspec =
+		TAILQ_LAST(&prev_priv->cmndlist, cmndspec_list);
+	    struct member_list *runasuserlist = prev_cmndspec->runasuserlist;
+	    struct member_list *runasgrouplist = prev_cmndspec->runasgrouplist;
 
 	    /* Free duplicate runas lists. */
 	    if (cmndspec->runasuserlist != NULL) {
-- 
2.27.0

