From 93bb86a37a0cf7b9c71e374f3c9aac7dbfe2953a Mon Sep 17 00:00:00 2001
From: Jinfeng Wang <jinfeng.wang.cn@windriver.com>
Date: Fri, 27 Sep 2024 14:22:32 +0800
Subject: [PATCH] procps: patch CVE-2023-4016

ps/parser: parse_list(): int overflow for large arg, free() of uninit. ptr

* ps/parser.c:parse_list(): Regression (2c933ecb): node->u is uninitialized at
  free(node->u) when reached before node->u=xcalloc().
* ps/parser.c:parse_list(): When "arg" is very long, CVE-2023-4016 is triggered.
  2c933ecb handles the multiplication issue, but there is still the possibility
  of int overflow when incrementing "items".

CVE: CVE-2023-4016

Upstream-Status: Backport [https://gitlab.com/procps-ng/procps/-/commit/f5f843e257daeceaac2504b8957e84f4bf87a8f2]

Signed-off-by: Jinfeng Wang <jinfeng.wang.cn@windriver.com>
---
 include/xalloc.h | 2 +-
 ps/parser.c      | 3 ++-
 2 files changed, 3 insertions(+), 2 deletions(-)

diff --git a/include/xalloc.h b/include/xalloc.h
index 8b4d368f..a8046892 100644
--- a/include/xalloc.h
+++ b/include/xalloc.h
@@ -42,7 +42,7 @@ void *xcalloc(const size_t nelems, const size_t size)
 {
 	void *ret = calloc(nelems, size);
 	if (!ret && size && nelems)
-		xerrx(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", size);
+		xerrx(XALLOC_EXIT_CODE, "cannot allocate %zu bytes", nelems*size);
 	return ret;
 }
 
diff --git a/ps/parser.c b/ps/parser.c
index 5c92fce4..a94b49ff 100644
--- a/ps/parser.c
+++ b/ps/parser.c
@@ -185,6 +185,7 @@ static const char *parse_list(const char *arg, const char *(*parse_fn)(char *, s
   /*** prepare to operate ***/
   node = malloc(sizeof(selection_node));
   node->n = 0;
+  node->u = NULL;
   buf = strdup(arg);
   /*** sanity check and count items ***/
   need_item = 1; /* true */
@@ -198,7 +199,7 @@ static const char *parse_list(const char *arg, const char *(*parse_fn)(char *, s
       need_item=1;
       break;
     default:
-      if(need_item) items++;
+      if(need_item && items<INT_MAX) items++;
       need_item=0;
     }
   } while (*++walk);
-- 
2.34.1

