From: Ubuntu Developers <ubuntu-devel-discuss@lists.ubuntu.com>
Date: Sat, 14 May 2022 02:52:50 +0800
Subject: _commonio_group_shadow

Goal: save the [g]shadow files with the 'shadow' group and mode 0440
Fixes: #166793
---
 lib/commonio.c | 12 ++++++++++++
 lib/sgroupio.c |  2 +-
 lib/shadowio.c |  2 +-
 3 files changed, 14 insertions(+), 2 deletions(-)

diff --git a/lib/commonio.c b/lib/commonio.c
index 16fa7e7..9f6ceca 100644
--- a/lib/commonio.c
+++ b/lib/commonio.c
@@ -44,6 +44,7 @@
 #include <errno.h>
 #include <stdio.h>
 #include <signal.h>
+#include <grp.h>
 #include "nscd.h"
 #include "sssd.h"
 #ifdef WITH_TCB
@@ -986,12 +987,23 @@ int commonio_close (struct commonio_db *db)
 			goto fail;
 		}
 	} else {
+		struct group *grp;
 		/*
 		 * Default permissions for new [g]shadow files.
 		 */
 		sb.st_mode = db->st_mode;
 		sb.st_uid = db->st_uid;
 		sb.st_gid = db->st_gid;
+
+		/*
+		 * Try to retrieve the shadow's GID, and fall back to GID 0.
+		 */
+		if (sb.st_gid == 0) {
+			if ((grp = getgrnam("shadow")) != NULL)
+				sb.st_gid = grp->gr_gid;
+			else
+				sb.st_gid = 0;
+		}
 	}
 
 	snprintf (buf, sizeof buf, "%s+", db->filename);
diff --git a/lib/sgroupio.c b/lib/sgroupio.c
index ffbdb26..688e71c 100644
--- a/lib/sgroupio.c
+++ b/lib/sgroupio.c
@@ -229,7 +229,7 @@ static struct commonio_db gshadow_db = {
 #ifdef WITH_SELINUX
 	NULL,			/* scontext */
 #endif
-	0400,                   /* st_mode */
+	0440,                   /* st_mode */
 	0,                      /* st_uid */
 	0,                      /* st_gid */
 	NULL,			/* head */
diff --git a/lib/shadowio.c b/lib/shadowio.c
index 676b1f1..1cd42a7 100644
--- a/lib/shadowio.c
+++ b/lib/shadowio.c
@@ -105,7 +105,7 @@ static struct commonio_db shadow_db = {
 #ifdef WITH_SELINUX
 	NULL,			/* scontext */
 #endif				/* WITH_SELINUX */
-	0400,                   /* st_mode */
+	0440,                   /* st_mode */
 	0,                      /* st_uid */
 	0,                      /* st_gid */
 	NULL,			/* head */
