From 3ddd9a35cebc28f2b1a5693c27dcfff58218674a Mon Sep 17 00:00:00 2001
From: Stefan Weil <sw@weilnetz.de>
Date: Sun, 3 May 2020 16:14:20 +0200
Subject: [PATCH] Fix heap buffer overflow in selReadStream

selio_reg triggers a heap buffer overflow when sscanf tries to write 201 bytes into a 24 byte string.
It can be detected when the code is compiled with the address sanitizer:

    ==19856==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x603000001288 at pc 0x00000044462b bp 0x7fffffffddf0 sp 0x7fffffffd5a0
    WRITE of size 201 at 0x603000001288 thread T0
    0x603000001288 is located 0 bytes to the right of 24-byte region [0x603000001270,0x603000001288)

Signed-off-by: Stefan Weil <sw@weilnetz.de>
---
 src/sel1.c | 6 +-----
 1 file changed, 1 insertion(+), 5 deletions(-)

diff --git a/src/sel1.c b/src/sel1.c
index 9c6ccf1e..5f61570b 100644
--- a/src/sel1.c
+++ b/src/sel1.c
@@ -1418,7 +1418,7 @@ SEL   *sel;
 SEL  *
 selReadStream(FILE  *fp)
 {
-char    *selname;
+char     selname[256];
 char     linebuf[256];
 l_int32  sy, sx, cy, cx, i, j, version, ignore;
 SEL     *sel;
@@ -1435,17 +1435,14 @@ SEL     *sel;
 
     if (fgets(linebuf, sizeof(linebuf), fp) == NULL)
         return (SEL *)ERROR_PTR("error reading into linebuf", procName, NULL);
-    selname = stringNew(linebuf);
     sscanf(linebuf, "  ------  %200s  ------", selname);
 
     if (fscanf(fp, "  sy = %d, sx = %d, cy = %d, cx = %d\n",
             &sy, &sx, &cy, &cx) != 4) {
-        LEPT_FREE(selname);
         return (SEL *)ERROR_PTR("dimensions not read", procName, NULL);
     }
 
     if ((sel = selCreate(sy, sx, selname)) == NULL) {
-        LEPT_FREE(selname);
         return (SEL *)ERROR_PTR("sel not made", procName, NULL);
     }
     selSetOrigin(sel, cy, cx);
@@ -1458,7 +1455,6 @@ SEL     *sel;
     }
     ignore = fscanf(fp, "\n");
 
-    LEPT_FREE(selname);
     return sel;
 }
 
