From d594243fbbdabc73fdee50886f6dd11867b5cfab Mon Sep 17 00:00:00 2001
From: Iker Pedrosa <ipedrosa@redhat.com>
Date: Thu, 18 Nov 2021 16:48:26 +0100
Subject: [PATCH] lib: check NULL before freeing passwd data

Add an additional NULL check condition in spw_free() and pw_free() to
avoid freeing an already empty pointer.

Signed-off-by: Iker Pedrosa <ipedrosa@redhat.com>

Conflict: NA
Reference: https://github.com/shadow-maint/shadow/commit/d594243fbbdabc73fdee50886f6dd11867b5cfab

---
 lib/pwmem.c     | 18 ++++++++++--------
 lib/shadowmem.c | 12 +++++++-----
 2 files changed, 17 insertions(+), 13 deletions(-)

diff --git a/lib/pwmem.c b/lib/pwmem.c
index 17d2eb219..9f184d5e1 100644
--- a/lib/pwmem.c
+++ b/lib/pwmem.c
@@ -93,14 +93,16 @@
 
 void pw_free (/*@out@*/ /*@only@*/struct passwd *pwent)
 {
-	free (pwent->pw_name);
-	if (pwent->pw_passwd) {
-		memzero (pwent->pw_passwd, strlen (pwent->pw_passwd));
-		free (pwent->pw_passwd);
+	if (pwent != NULL) {
+		free (pwent->pw_name);
+		if (pwent->pw_passwd) {
+			memzero (pwent->pw_passwd, strlen (pwent->pw_passwd));
+			free (pwent->pw_passwd);
+		}
+		free (pwent->pw_gecos);
+		free (pwent->pw_dir);
+		free (pwent->pw_shell);
+		free (pwent);
 	}
-	free (pwent->pw_gecos);
-	free (pwent->pw_dir);
-	free (pwent->pw_shell);
-	free (pwent);
 }
 
diff --git a/lib/shadowmem.c b/lib/shadowmem.c
index 8989598f8..1d047cc04 100644
--- a/lib/shadowmem.c
+++ b/lib/shadowmem.c
@@ -79,11 +79,13 @@
 
 void spw_free (/*@out@*/ /*@only@*/struct spwd *spent)
 {
-	free (spent->sp_namp);
-	if (NULL != spent->sp_pwdp) {
-		memzero (spent->sp_pwdp, strlen (spent->sp_pwdp));
-		free (spent->sp_pwdp);
+	if (spent != NULL) {
+		free (spent->sp_namp);
+		if (NULL != spent->sp_pwdp) {
+			memzero (spent->sp_pwdp, strlen (spent->sp_pwdp));
+			free (spent->sp_pwdp);
+		}
+		free (spent);
 	}
-	free (spent);
 }
 
