[PATCH 2/2] lib/ucs2_string.c: fix out-of-bounds read in ucs2_strnlen()

From: Vincent Mailhol

Date: Wed Jul 22 2026 - 17:06:11 EST


ucs2_strnlen() checks the current character before checking whether the
caller-provided maximum length has been reached. If the input is not
NUL-terminated within that bound, the loop can read one ucs2_char_t past
the limit.

Test the length before dereferencing to prevent an off-by-one
out-of-bounds read.

Fixes: 1da177e4c3f4 ("Linux-2.6.12-rc2")
Signed-off-by: Vincent Mailhol <mailhol@xxxxxxxxxx>
---
Concerning the Fixes: tag, the ucs2_strnlen() function can be traced as
follow:

- commit 0635eb8a54cf ("Move utf16 functions to kernel core and
rename") renames it from utf16_strnlen() to ucs2_strnlen() as we
know it today.

- commit a2940908391f ("efivars: String functions") renames
utf8_strlen() to utf16_strnlen().

- utf8_strlen() is present since the begining of the git history in
commit 1da177e4c3f4 ("Linux-2.6.12-rc2")

And that of-by-one issue was present since the beginning and survived
all the renamings. This is why I picked 1da177e4c3f4 in the Fixes tag.
---
lib/ucs2_string.c | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/lib/ucs2_string.c b/lib/ucs2_string.c
index f07fcdad764b..1f7dd4eb640a 100644
--- a/lib/ucs2_string.c
+++ b/lib/ucs2_string.c
@@ -8,7 +8,7 @@ ucs2_strnlen(const ucs2_char_t *s, size_t maxlength)
{
unsigned long length = 0;

- while (*s++ != 0 && length < maxlength)
+ while (length < maxlength && *s++ != 0)
length++;
return length;
}

--
2.54.0