git: 3532d9c66ece - stable/13 - pw: Ensure group membership is not duplicated

From: Dag-Erling Smørgrav <des_at_FreeBSD.org>
Date: Thu, 09 May 2024 13:16:52 UTC
The branch stable/13 has been updated by des:

URL: https://cgit.FreeBSD.org/src/commit/?id=3532d9c66ecefd356ec670f014e4647537b59ef1

commit 3532d9c66ecefd356ec670f014e4647537b59ef1
Author:     Naman Sood <mail@nsood.in>
AuthorDate: 2023-07-19 12:44:21 +0000
Commit:     Dag-Erling Smørgrav <des@FreeBSD.org>
CommitDate: 2024-05-09 11:04:30 +0000

    pw: Ensure group membership is not duplicated
    
    Fix the following problem:
    
    1. A nonexistent user, someuser, is added to somegroup in /etc/group.
    2. someuser is then created with membership in somegroup.
    
    The entry for somegroup in /etc/group will then contain
    
        somegroup:*:12345:someuser,someuser
    
    With this fix, the entry will be
    
        somegroup:*:12345:someuser
    
    PR:             238995
    Reviewed by:    bapt, jrm
    Sponsored by:   The FreeBSD Foundation
    Differential Revision:  https://reviews.freebsd.org/D41076
    
    (cherry picked from commit 17839f45d86e79065a65ad3e2522dd69b29a652c)
---
 usr.sbin/pw/pw.h       | 2 ++
 usr.sbin/pw/pw_group.c | 2 +-
 usr.sbin/pw/pw_user.c  | 3 +++
 3 files changed, 6 insertions(+), 1 deletion(-)

diff --git a/usr.sbin/pw/pw.h b/usr.sbin/pw/pw.h
index 54a49f3d691a..5de333ce5e71 100644
--- a/usr.sbin/pw/pw.h
+++ b/usr.sbin/pw/pw.h
@@ -112,3 +112,5 @@ extern const char *Which[];
 
 uintmax_t strtounum(const char * __restrict, uintmax_t, uintmax_t,
     const char ** __restrict);
+
+bool grp_has_member(struct group *grp, const char *name);
diff --git a/usr.sbin/pw/pw_group.c b/usr.sbin/pw/pw_group.c
index 91300afe3c23..32dec769fb1a 100644
--- a/usr.sbin/pw/pw_group.c
+++ b/usr.sbin/pw/pw_group.c
@@ -413,7 +413,7 @@ pw_group_del(int argc, char **argv, char *arg1)
 	return (EXIT_SUCCESS);
 }
 
-static bool
+bool
 grp_has_member(struct group *grp, const char *name)
 {
 	int j;
diff --git a/usr.sbin/pw/pw_user.c b/usr.sbin/pw/pw_user.c
index 78cdfc98c447..ac04dc2fa89b 100644
--- a/usr.sbin/pw/pw_user.c
+++ b/usr.sbin/pw/pw_user.c
@@ -1454,6 +1454,9 @@ pw_user_add(int argc, char **argv, char *arg1)
 	if (cmdcnf->groups != NULL) {
 		for (i = 0; i < cmdcnf->groups->sl_cur; i++) {
 			grp = GETGRNAM(cmdcnf->groups->sl_str[i]);
+			/* gr_add doesn't check if new member is already in group */
+			if (grp_has_member(grp, pwd->pw_name))
+				continue;
 			grp = gr_add(grp, pwd->pw_name);
 			/*
 			 * grp can only be NULL in 2 cases: