From e806a902cc90a0b87da00854de8d5fd8222540fc Mon Sep 17 00:00:00 2001
From: Pavel Kopylov <pkopylov@>
Date: Wed, 17 May 2023 11:33:45 +0200
Subject: [PATCH] Fix an overflow which is still possible for some values.

Upstream-Status: Backport [https://github.com/sysstat/sysstat/commit/954ff2e2673c]
CVE: CVE-2023-33204

Signed-off-by: Xiangyu Chen <xiangyu.chen@...>
Signed-off-by: Sanjay Chitroda <schitrod@...>
Signed-off-by: Hitendra Prajapati <hprajapati@mvista.com>
---
 common.c    | 18 ++++++++++--------
 common.h    |  2 +-
 sa_common.c |  4 ++--
 3 files changed, 13 insertions(+), 11 deletions(-)

diff --git a/common.c b/common.c
index db9b0ed..e05c5bb 100644
--- a/common.c
+++ b/common.c
@@ -1640,17 +1640,19 @@ int parse_values(char *strargv, unsigned char bitmap[], int max_val, const char
  * @val3	Third value.
  ***************************************************************************
  */
-void check_overflow(size_t val1, size_t val2, size_t val3)
+void check_overflow(unsigned int val1, unsigned int val2,
+		    unsigned int val3)
 {
-	if ((unsigned long long) val1 *
-	    (unsigned long long) val2 *
-	    (unsigned long long) val3 > UINT_MAX) {
+	if ((val1 != 0) && (val2 != 0) && (val3 != 0) &&
+	    (((unsigned long long) UINT_MAX / (unsigned long long) val1 <
+	      (unsigned long long) val2) ||
+	     ((unsigned long long) UINT_MAX / ((unsigned long long) val1 * (unsigned long long) val2) <
+	      (unsigned long long) val3))) {
 #ifdef DEBUG
-		fprintf(stderr, "%s: Overflow detected (%llu). Aborting...\n",
-			__FUNCTION__,
-			(unsigned long long) val1 * (unsigned long long) val2 *	(unsigned long long) val3);
+		fprintf(stderr, "%s: Overflow detected (%u,%u,%u). Aborting...\n",
+			__FUNCTION__, val1, val2, val3);
 #endif
-	exit(4);
+		exit(4);
 	}
 }
 
diff --git a/common.h b/common.h
index 0ac5896..b2ffe9f 100644
--- a/common.h
+++ b/common.h
@@ -256,7 +256,7 @@ int check_dir
 
 #ifndef SOURCE_SADC
 void check_overflow
-	(size_t, size_t, size_t);
+	(unsigned int, unsigned int, unsigned int);
 int count_bits
 	(void *, int);
 int count_csvalues
diff --git a/sa_common.c b/sa_common.c
index 1b8fcaa..1144cfe 100644
--- a/sa_common.c
+++ b/sa_common.c
@@ -452,8 +452,8 @@ void allocate_structures(struct activity *act[])
 		if (act[i]->nr_ini > 0) {
 
 			/* Look for a possible overflow */
-			check_overflow((size_t) act[i]->msize, (size_t) act[i]->nr_ini,
-				       (size_t) act[i]->nr2);
+			check_overflow((unsigned int) act[i]->msize, (unsigned int) act[i]->nr_ini,
+				       (unsigned int) act[i]->nr2);
 
 			for (j = 0; j < 3; j++) {
 				SREALLOC(act[i]->buf[j], void,
-- 
2.25.1

