From 6fd9cc8ce3958092a1aae11f1f2e911b2747732d Mon Sep 17 00:00:00 2001
From: Jakub Jelen <jjelen@redhat.com>
Date: Tue, 15 Apr 2025 11:41:24 +0200
Subject: CVE-2025-4877 base64: Prevent integer overflow and potential OOB

Set maximum input to 256MB to have safe margin to the 1GB trigger point
for 32b arch.

The OOB should not be reachable by any internal code paths as most of
the buffers and strings we use as input for this operation already have
similar limit and none really allows this much of data.

Signed-off-by: Jakub Jelen <jjelen@redhat.com>
Reviewed-by: Andreas Schneider <asn@cryptomilk.org>
(cherry picked from commit 00f09acbec55962839fc7837ef14c56fb8fbaf72)

CVE: CVE-2025-4877
Upstream-Status: Backport [https://git.libssh.org/projects/libssh.git/commit/?id=6fd9cc8ce3958092a1aae11f1f2e911b2747732d]
Signed-off-by: Hitendra Prajapati <hprajapati@mvista.com>
---
 src/base64.c | 13 ++++++++++++-
 1 file changed, 12 insertions(+), 1 deletion(-)

diff --git a/src/base64.c b/src/base64.c
index 372dc65f..7bb8efb1 100644
--- a/src/base64.c
+++ b/src/base64.c
@@ -29,6 +29,9 @@
 #include "libssh/priv.h"
 #include "libssh/buffer.h"
 
+/* Do not allow encoding more than 256MB of data */
+#define BASE64_MAX_INPUT_LEN 256 * 1024 * 1024
+
 static char alphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                          "abcdefghijklmnopqrstuvwxyz"
                          "0123456789+/";
@@ -269,7 +272,15 @@ static void _bin_to_base64(unsigned char *dest, const unsigned char source[3],
 unsigned char *bin_to_base64(const unsigned char *source, int len) {
   unsigned char *base64;
   unsigned char *ptr;
-  int flen = len + (3 - (len % 3)); /* round to upper 3 multiple */
+  int flen = 0;
+
+ /* Set the artificial upper limit for the input. Otherwise on 32b arch, the
+  * following line could overflow for sizes larger than SIZE_MAX / 4 */
+  if (len > BASE64_MAX_INPUT_LEN) {
+      return NULL;
+  }
+
+  flen = len + (3 - (len % 3)); /* round to upper 3 multiple */
   flen = (4 * flen) / 3 + 1;
 
   base64 = malloc(flen);
-- 
2.50.1

