From 9c4eaf150662ad40607923389d4519bc83b93540 Mon Sep 17 00:00:00 2001
From: Sebastien <seb@fedora-2.home>
Date: Sat, 15 Oct 2022 14:24:22 +0200
Subject: [PATCH] Fix size_t overflow in sa_common.c (GHSL-2022-074)

allocate_structures function located in sa_common.c insufficiently
checks bounds before arithmetic multiplication allowing for an
overflow in the size allocated for the buffer representing system
activities.

This patch checks that the post-multiplied value is not greater than
UINT_MAX.

Signed-off-by: Sebastien <seb@fedora-2.home>
---
 common.c    | 25 +++++++++++++++++++++++++
 common.h    |  2 ++
 sa_common.c |  6 ++++++
 3 files changed, 33 insertions(+)

diff --git a/common.c b/common.c
index 81c77624..1a84b052 100644
--- a/common.c
+++ b/common.c
@@ -1655,4 +1655,29 @@ int parse_values(char *strargv, unsigned char bitmap[], int max_val, const char
 
 	return 0;
 }
+
+/*
+ ***************************************************************************
+ * Check if the multiplication of the 3 values may be greater than UINT_MAX.
+ *
+ * IN:
+ * @val1	First value.
+ * @val2	Second value.
+ * @val3	Third value.
+ ***************************************************************************
+ */
+void check_overflow(size_t val1, size_t val2, size_t val3)
+{
+	if ((unsigned long long) val1 *
+	    (unsigned long long) val2 *
+	    (unsigned long long) val3 > UINT_MAX) {
+#ifdef DEBUG
+		fprintf(stderr, "%s: Overflow detected (%llu). Aborting...\n",
+			__FUNCTION__,
+			(unsigned long long) val1 * (unsigned long long) val2 *	(unsigned long long) val3);
+#endif
+	exit(4);
+	}
+}
+
 #endif /* SOURCE_SADC undefined */
diff --git a/common.h b/common.h
index 55b6657d..e8ab98ab 100644
--- a/common.h
+++ b/common.h
@@ -260,6 +260,8 @@ int check_dir
 	(char *);
 
 #ifndef SOURCE_SADC
+void check_overflow
+	(size_t, size_t, size_t);
 int count_bits
 	(void *, int);
 int count_csvalues
diff --git a/sa_common.c b/sa_common.c
index 3699a840..b2cec4ad 100644
--- a/sa_common.c
+++ b/sa_common.c
@@ -459,7 +459,13 @@ void allocate_structures(struct activity *act[])
 	int i, j;
 
 	for (i = 0; i < NR_ACT; i++) {
+
 		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);
+
 			for (j = 0; j < 3; j++) {
 				SREALLOC(act[i]->buf[j], void,
 						(size_t) act[i]->msize * (size_t) act[i]->nr_ini * (size_t) act[i]->nr2);


