From e5c1a7366b92c6646361cb35284ee929be3be825 Mon Sep 17 00:00:00 2001
From: Martijn Dekker <martijn@inlv.org>
Date: Wed, 8 Jan 2025 23:01:39 +0000
Subject: [PATCH] edit.c: fix out of bounds write in output buffer

When allocating the output buffer, the pointer to the last byte,
ep->e_outlast, is set to one past the end of the buffer. This can
cause an out of bounds write in ed_putbyte()/ed_putchar() while
setting the terminating zero byte. Fix this by setting it to the
last byte of the buffer instead.
---
 src/cmd/ksh93/edit/edit.c | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)

diff --git a/src/cmd/ksh93/edit/edit.c b/src/cmd/ksh93/edit/edit.c
index f0d4672a9e59..e87d21bbe6a4 100644
--- a/src/cmd/ksh93/edit/edit.c
+++ b/src/cmd/ksh93/edit/edit.c
@@ -535,13 +535,13 @@ void	ed_setup(Edit_t *ep, int fd, int reedit)
 		if(!buff)
 			buff = (char*)sh_malloc(MAXLINE);
 		ep->e_outbase = ep->e_outptr = buff;
-		ep->e_outlast = ep->e_outptr + MAXLINE;
+		ep->e_outlast = ep->e_outptr + MAXLINE - 1;
 		return;
 	}
 	qlen = sfset(sfstderr,SFIO_READ,0);
 	/* make sure SFIO_READ not on */
 	ep->e_outbase = ep->e_outptr = (char*)sfreserve(sfstderr,SFIO_UNBOUND,SFIO_LOCKR);
-	ep->e_outlast = ep->e_outptr + sfvalue(sfstderr);
+	ep->e_outlast = ep->e_outptr + sfvalue(sfstderr) - 1;
 	if(qlen)
 		sfset(sfstderr,SFIO_READ,1);
 	sfwrite(sfstderr,ep->e_outptr,0);