From 044cdf5835e93df01aa7b3ca439ab4740997fbe9 Mon Sep 17 00:00:00 2001
From: Jacob Champion <jacob.champion@enterprisedb.com>
Date: Thu, 22 Aug 2024 09:53:57 -0700
Subject: [PATCH] pg_utf8_string_len: honor null terminators

Callers of pg_utf8_is_legal() must verify that there's enough length
remaining in the string, and pg_utf8_string_len() wasn't doing that, so
SASLprep could jump slightly past the end of the provided password.
---
 src/common/saslprep.c | 6 ++++--
 1 file changed, 4 insertions(+), 2 deletions(-)

diff --git a/src/common/saslprep.c b/src/common/saslprep.c
index 315ccacd7c..78f6fcbd80 100644
--- a/src/common/saslprep.c
+++ b/src/common/saslprep.c
@@ -1004,15 +1004,17 @@ pg_utf8_string_len(const char *source)
 	const unsigned char *p = (const unsigned char *) source;
 	int			l;
 	int			num_chars = 0;
+	size_t		len = strlen(source);
 
-	while (*p)
+	while (len)
 	{
 		l = pg_utf_mblen(p);
 
-		if (!pg_utf8_islegal(p, l))
+		if (len < l || !pg_utf8_islegal(p, l))
 			return -1;
 
 		p += l;
+		len -= l;
 		num_chars++;
 	}
 
-- 
2.34.1

