From 3f702a4e94f4fcc63cda3103b43fd5c166cc180e Mon Sep 17 00:00:00 2001
From: Daniel Gustafsson <daniel@yesql.se>
Date: Fri, 16 Oct 2020 13:32:42 +0200
Subject: [PATCH] Guard against errors in digest context allocation

Even though we know that the digest algorithm exists when we reach
the second call, we must check the returnvalue from each call to
px_find_digest to handle allocation errors. Depending on which lib
is backing pgcrypto, px_find_digest may perform resource allocation
which can fail individually.
---
 contrib/pgcrypto/crypt-md5.c | 11 ++++++++++-
 1 file changed, 10 insertions(+), 1 deletion(-)

diff --git a/contrib/pgcrypto/crypt-md5.c b/contrib/pgcrypto/crypt-md5.c
index b6466d3e31..6ce6d13236 100644
--- a/contrib/pgcrypto/crypt-md5.c
+++ b/contrib/pgcrypto/crypt-md5.c
@@ -65,11 +65,20 @@ px_crypt_md5(const char *pw, const char *salt, char *passwd, unsigned dstlen)
 	/* get the length of the true salt */
 	sl = ep - sp;
 
-	/* */
+	/*
+	 * While we know from the first call if the algorithm is found, we still
+	 * need to test the second call for errors as px_find_digest may allocate
+	 * resources which in turn may fai which in turn may fail.
+	 */
 	err = px_find_digest("md5", &ctx);
 	if (err)
 		return NULL;
 	err = px_find_digest("md5", &ctx1);
+	if (err)
+	{
+		px_md_free(ctx);
+		return NULL;
+	}
 
 	/* The password first, since that is what is most unknown */
 	px_md_update(ctx, (const uint8 *) pw, strlen(pw));
-- 
2.21.1 (Apple Git-122.3)

