From 14e0247ea55b510dec8923c950b200f883adb788 Mon Sep 17 00:00:00 2001
From: Qualys Security Advisory <qsa@qualys.com>
Date: Thu, 1 Jan 1970 00:00:00 +0000
Subject: [PATCH] ps/output.c: Enforce a safe range for max_rightward.

Enforce a maximum max_rightward of OUTBUF_SIZE-1, because it is used in
constructs such as "snprintf(outbuf, max_rightward+1," (we could remove
the extra check at the beginning of forest_helper() now, but we decided
to leave it, as a precaution and reminder).

The minimum max_rightward check is not strictly needed, because it is
unsigned. However, we decided to add it anyway:

- most of the other variables are signed;

- make it visually clear that this case is properly handled;

- ideally, the minimum max_rightward should be 1, not 0 (to prevent
  integer overflows such as "max_rightward-1"), but this might change
  the behavior/output of ps, so we decided against it, for now.

Instead, we fixed the only function that overflows if max_rightward is
0. Also, enforce the same safe range for max_leftward, although it is
never used throughout the code-base.
---
 ps/output.c | 11 ++++++++---
 1 file changed, 8 insertions(+), 3 deletions(-)

diff --git a/ps/output.c b/ps/output.c
index f375441e..14174b18 100644
--- a/ps/output.c
+++ b/ps/output.c
@@ -80,8 +80,8 @@
 
 #define COLWID 240 /* satisfy snprintf, which is faster than sprintf */
 
-static unsigned max_rightward = 0x12345678; /* space for RIGHT stuff */
-static unsigned max_leftward = 0x12345678; /* space for LEFT stuff */
+static unsigned max_rightward = OUTBUF_SIZE-1; /* space for RIGHT stuff */
+static unsigned max_leftward = OUTBUF_SIZE-1; /* space for LEFT stuff */
 
 
 
@@ -1142,7 +1142,7 @@ static int do_pr_name(char *restrict const outbuf, const char *restrict const na
       return len;  /* returns number of cells */
 
     // only use '+' when not on a multi-byte char, else show uid
-    if ((unsigned)outbuf[max_rightward-1] < 127) {
+    if (max_rightward >= 1 && (unsigned)outbuf[max_rightward-1] < 127) {
       len = max_rightward-1;
       outbuf[len++] = '+';
       outbuf[len] = 0;
@@ -2036,7 +2036,12 @@ void show_one_proc(const proc_t *restrict const p, const format_node *restrict f
 	max_rightward = active_cols - ( (correct>actual) ? correct : actual );
       }
     }
+    if(max_rightward <= 0) max_rightward = 0;
+    else if(max_rightward >= OUTBUF_SIZE) max_rightward = OUTBUF_SIZE-1;
+
     max_leftward  = fmt->width + actual - correct; /* TODO check this */
+    if(max_leftward <= 0) max_leftward = 0;
+    else if(max_leftward >= OUTBUF_SIZE) max_leftward = OUTBUF_SIZE-1;
 
 //    fprintf(stderr, "cols: %d, max_rightward: %d, max_leftward: %d, actual: %d, correct: %d\n",
 //		    active_cols, max_rightward, max_leftward, actual, correct);