From 75008b3055306224ca0272cc04d48f0a96caee79 Mon Sep 17 00:00:00 2001
From: =?UTF-8?q?Deuc=D0=B5?= <shurd@sasktel.net>
Date: Sat, 28 Sep 2024 02:13:12 -0400
Subject: [PATCH] Fix a couple use-after-free bugs in RIP

This likely is the cause of bug 140.

The first one, the LCF flag is copied out of the cterm struct
after cterm_end() is called (which frees the struct).  Copy moved
to before cterm_end().

The second one is trickier... it's executing the commands in a mouse
button, and one of the commands is to delete all the mouse button
commands.  This ends up free()ing the string that's currently being
parsed while it's being parsed.  We now use a strdup() of the string
which we free at the end of the function.
---
 src/syncterm/ripper.c | 7 +++++--
 1 file changed, 5 insertions(+), 2 deletions(-)

diff --git a/src/syncterm/ripper.c b/src/syncterm/ripper.c
index c72ca783cd..f1f88c55e7 100644
--- a/src/syncterm/ripper.c
+++ b/src/syncterm/ripper.c
@@ -9897,11 +9897,13 @@ handle_command_str(const char *incmd)
 {
 	const char *p, *p2, *p3, *p4;
 	char        str[2];
+	char *indup;
 
 	if (incmd == NULL)
 		return;
+	indup = strdup(incmd);
 
-	for (p = incmd; *p; p++) {
+	for (p = indup; *p; p++) {
                 // TODO: No way to send a ^ or a $ or a [
 		if ((*p == '^') || (*p == '`')) { // CTRL char
 			p++;
@@ -9957,6 +9959,7 @@ handle_command_str(const char *incmd)
 		ripbuf_pos = 0;
 		ripbufpos = 0;
 	}
+	free(indup);
 }
 
 static void
@@ -10082,6 +10085,7 @@ reinit_screen(uint8_t *font, int fx, int fy)
 	hold_update = 0;
 	cterm->logfile = NULL;
 	cterm->log = CTERM_LOG_NONE;
+	lcf = cterm->last_column_flag;
 	cterm_end(cterm, 0);
 	normal_palette();
 
@@ -10124,7 +10128,6 @@ reinit_screen(uint8_t *font, int fx, int fy)
 	clrscr();
 	get_term_win_size(&term.width, &term.height, NULL, NULL, &term.nostatus);
 	term.width = cols;
-	lcf = cterm->last_column_flag;
 	cterm = cterm_init(rows + (term.nostatus ? 0 : -1),
 	        cols,
 	        oldcterm.x,
-- 
GitLab