From 8e7c09895b2d8dc0d65980d757926351ad6817e8 Mon Sep 17 00:00:00 2001
From: rpm-build <rpm-build>
Date: Mon, 14 Aug 2023 14:12:41 +0200
Subject: [PATCH] ps buffer overflow

Resolves: bz#2230186
---
 local/xalloc.h  |  2 +-
 src/ps/parser.c | 11 ++++++-----
 2 files changed, 7 insertions(+), 6 deletions(-)

diff --git a/local/xalloc.h b/local/xalloc.h
index 8b4d368..a804689 100644
--- a/local/xalloc.h
+++ b/local/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/src/ps/parser.c b/src/ps/parser.c
index 248aa74..c46855c 100644
--- a/src/ps/parser.c
+++ b/src/ps/parser.c
@@ -189,8 +189,8 @@ static const char *parse_list(const char *arg, const char *(*parse_fn)(char *, s
   const char *err;       /* error code that could or did happen */
   /*** prepare to operate ***/
   node = xmalloc(sizeof(selection_node));
-  node->u = xmalloc(strlen(arg)*sizeof(sel_union)); /* waste is insignificant */
   node->n = 0;
+  node->u = NULL;
   buf = strdup(arg);
   /*** sanity check and count items ***/
   need_item = 1; /* true */
@@ -204,12 +204,13 @@ 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);
   if(need_item) goto parse_error;
   node->n = items;
+  node->u = xcalloc(items, sizeof(sel_union));
   /*** actually parse the list ***/
   walk = buf;
   while(items--){
@@ -1050,15 +1051,15 @@ static const char *parse_trailing_pids(void){
   thisarg = ps_argc - 1;   /* we must be at the end now */
 
   pidnode = xmalloc(sizeof(selection_node));
-  pidnode->u = xmalloc(i*sizeof(sel_union)); /* waste is insignificant */
+  pidnode->u = xcalloc(i, sizeof(sel_union)); /* waste is insignificant */
   pidnode->n = 0;
 
   grpnode = xmalloc(sizeof(selection_node));
-  grpnode->u = xmalloc(i*sizeof(sel_union)); /* waste is insignificant */
+  grpnode->u = xcalloc(i,sizeof(sel_union)); /* waste is insignificant */
   grpnode->n = 0;
 
   sidnode = xmalloc(sizeof(selection_node));
-  sidnode->u = xmalloc(i*sizeof(sel_union)); /* waste is insignificant */
+  sidnode->u = xcalloc(i, sizeof(sel_union)); /* waste is insignificant */
   sidnode->n = 0;
 
   while(i--){
-- 
2.40.1

