From 5e3d207d5b7dba28ca248475188a029570766bc1 Mon Sep 17 00:00:00 2001
From: Paul Eggert <eggert@cs.ucla.edu>
Date: Mon, 30 May 2022 17:03:26 -0700
Subject: [PATCH] grep: sanity-check GREP_COLOR

This patch closes a longstanding security issue with GREP_COLOR that I
just noticed, where if the attacker has control over GREP_COLOR's
settings the attacker can trash the victim's terminal or have 'grep'
generate misleading output.  For example, without the patch
the shell command:
GREP_COLOR="$(printf '31m\33[2J\33[31')" grep --color=always PATTERN
mucks with the screen, leaving behind only the trailing part of
the last matching line.  With the patch, this GREP_COLOR is ignored.
* src/grep.c (main): Sanity-check GREP_COLOR contents the same way
GREP_COLORS values are checked, to not trash the user's terminal.
This follows up the recent fix to Bug#55641.

Reference:https://git.savannah.gnu.org/cgit/grep.git/commit?id=5e3d207d5b7dba28ca248475188a029570766bc1
Conflict:delete NEWS
---
 src/grep.c | 7 ++++++-
 1 file changed, 6 insertions(+), 1 deletion(-)

diff --git a/src/grep.c b/src/grep.c
index edefac6..59d3431 100644
--- a/src/grep.c
+++ b/src/grep.c
@@ -2911,7 +2911,12 @@ main (int argc, char **argv)
       /* Legacy.  */
       char *userval = getenv ("GREP_COLOR");
       if (userval != NULL && *userval != '\0')
-        selected_match_color = context_match_color = userval;
+        for (char *q = userval; *q == ';' || c_isdigit (*q); q++)
+          if (!q[1])
+            {
+              selected_match_color = context_match_color = userval;
+              break;
+            }
 
       /* New GREP_COLORS has priority.  */
       parse_grep_colors ();
-- 
2.27.0

