[PATCH v2025.09.y 43/49] lib: base64: Fix out-of-bounds potential by respecting dst_len

Ahmad Fatoum a.fatoum at pengutronix.de
Fri Dec 19 01:21:19 PST 2025


From: Jonas Rebmann <jre at pengutronix.de>

__decode_base64 generally writes the input in 3 bytes increments,
corresponding to 4 bytes increments in the base64 input buffer. This
means that in order to respect dst_len as the size of the output buffer,
the case of exceeding dst_len within a loop iteration must be
considered.

In such a case, refrain from writing the last one or two bytes if that
write would be past dst_len.

Signed-off-by: Jonas Rebmann <jre at pengutronix.de>
Link: https://lore.barebox.org/20251202-base64-bounds-v2-1-34d3716c3f55@pengutronix.de
Signed-off-by: Sascha Hauer <s.hauer at pengutronix.de>
(cherry picked from commit c99102d34c2d8f8c79cfaecf8968581031cbffef)
Signed-off-by: Ahmad Fatoum <a.fatoum at pengutronix.de>
---
 lib/base64.c | 10 +++++-----
 1 file changed, 5 insertions(+), 5 deletions(-)

diff --git a/lib/base64.c b/lib/base64.c
index d5ab217528db..3e29f0a56c45 100644
--- a/lib/base64.c
+++ b/lib/base64.c
@@ -163,19 +163,19 @@ static int __decode_base64(char *p_dst, int dst_len, const char *src, bool url)
 		 */
 		if (count > 1)
 			*dst++ = six_bit[0] << 2 | six_bit[1] >> 4;
-		if (count > 2)
+		if (count > 2 && dst_len > 1)
 			*dst++ = six_bit[1] << 4 | six_bit[2] >> 2;
-		if (count > 3)
+		if (count > 3 && dst_len > 2)
 			*dst++ = six_bit[2] << 6 | six_bit[3];
+		/* last character was "=" */
+		if (count != 0)
+			length += min(count - 1, dst_len);
 		/*
 		 * Note that if we decode "AA==" and ate first '=',
 		 * we just decoded one char (count == 2) and now we'll
 		 * do the loop once more to decode second '='.
 		 */
 		dst_len -= count-1;
-		/* last character was "=" */
-		if (count != 0)
-			length += count - 1;
 	}
 ret:
 	p_dst = dst;
-- 
2.47.3




More information about the barebox mailing list