From ced2c7394aafdc90fb7845e09b3a3fee23d48cb1 Mon Sep 17 00:00:00 2001
From: Christian Brabandt <cb@256bit.org>
Date: Sat, 2 Sep 2023 21:15:52 +0200
Subject: [PATCH 23/52] patch 9.0.1848: [security] buffer-overflow in
 vim_regsub_both()

Problem:  buffer-overflow in vim_regsub_both()
Solution: Check remaining space

Signed-off-by: Christian Brabandt <cb@256bit.org>
---
 src/ex_cmds.c                     |  3 +++
 src/regexp.c                      |  3 ++-
 2 files changed, 5 insertions(+), 1 deletions(-)

diff --git a/src/ex_cmds.c b/src/ex_cmds.c
index c30b6fddf..53c7bb5a3 100644
--- a/src/ex_cmds.c
+++ b/src/ex_cmds.c
@@ -4542,6 +4542,9 @@ ex_substitute(exarg_T *eap)
 		mch_memmove(new_end, sub_firstline + copycol, (size_t)copy_len);
 		new_end += copy_len;
 
+		if (new_start_len - copy_len < sublen)
+		    sublen = new_start_len - copy_len - 1;
+
 #ifdef FEAT_EVAL
 		++textlock;
 #endif
diff --git a/src/regexp.c b/src/regexp.c
index 9c576c689..edd1293a5 100644
--- a/src/regexp.c
+++ b/src/regexp.c
@@ -2007,7 +2007,8 @@ vim_regsub_both(
 	// "flags & REGSUB_COPY" != 0.
 	if (copy)
 	{
-	    if (eval_result[nested] != NULL)
+	    if (eval_result[nested] != NULL &&
+		    STRLEN(eval_result[nested]) < destlen)
 	    {
 		STRCPY(dest, eval_result[nested]);
 		dst += STRLEN(eval_result[nested]);
