Subject: bug#39165: [PATCH] sed: handle very long execution lines

From: Tobias Stoeckmann <[email-masked]>
Date: Fri, 17 Jan 2020 20:49:33 +0100

If sed is called with an excessively long execution line, then it is
prone to an out of boundary memory access.

The problem is that the length of the execution line, which is a
size_t, is temporarily stored in an int. This means that on systems
which have a 64 bit size_t and a 32 bit int (e.g. linux amd64) an
execution line which exceeds 2 GB will overflow int. If it is just
slightly larger than 2 GB, the negative int value is used as an
array index to finish the execution line string with '\0' which
therefore triggers the out of boundary access.

This problem is probably never triggered in reality, but can be
provoked like this (given that 'e' support is compiled in):

$ dd if=/dev/zero bs=1M count=2049 | tr '\0' 'e' > e-command.txt
$ sed -f e-command.txt /etc/fstab
Segmentation fault (core dumped)
$ _

While at it, I also adjusted another int/size_t conversion, even
though it is a purely cosmetical change, because it can never be
larger than 4096.

Signed-off-by: Tobias Stoeckmann <[email-masked]>
---
 sed/execute.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/sed/execute.c b/sed/execute.c
index c5f07cc..8f43f2e 100644
--- a/sed/execute.c
+++ b/sed/execute.c
@@ -1347,7 +1347,7 @@ execute_program (struct vector *vec, struct input *input)
               panic (_("`e' command not supported"));
 #else
               FILE *pipe_fp;
-              int cmd_length = cur_cmd->x.cmd_txt.text_length;
+              size_t cmd_length = cur_cmd->x.cmd_txt.text_length;
               line_reset (&s_accum, NULL);
 
               if (!cmd_length)
@@ -1367,7 +1367,7 @@ execute_program (struct vector *vec, struct input *input)
 
               {
                 char buf[4096];
-                int n;
+                size_t n;
                 while (!feof (pipe_fp))
                   if ((n = fread (buf, sizeof (char), 4096, pipe_fp)) > 0)
                     {
-- 
2.25.0