CVE-2023-48706: Use After Free (CWE-416)
value: Vim is a UNIX editor that, prior to version 9.0.2121, has a heap-use-after-free vulnerability. When executing a `:s` command for the very first time and using a sub-replace-special atom inside the substitution part, it is possible that the recursive `:s` call causes free-ing of memory which may later then be accessed by the initial `:s` command. The user must intentionally execute the payload and the whole process is a bit tricky to do since it seems to work only reliably for the very first :s command. It may also cause a crash of Vim. Version 9.0.2121 contains a fix for this issue.
CWE description: The product reuses or references memory after it has been freed. At some point afterward, the memory may be allocated again and saved in another pointer, while the original pointer references a location somewhere within the new allocation. Any operations using the original pointer are no longer valid because the memory "belongs" to the code that operates on the new pointer.
CVSS v3 base score: 4.7
Published: 2023-11-22T22:15Z
Repository: https://github.com/vim/vim
Language: C
Files changed: src/ex_cmds.c, src/testdir/test_substitute.vim, src/version.c
Commit date: 2023-11-22 21:52:45 +0100
Commit message: patch 9.0.2121: [security]: use-after-free in ex_substitute

Problem:  [security]: use-after-free in ex_substitute
Solution: always allocate memory

closes: #13552

A recursive :substitute command could cause a heap-use-after free in Vim
(CVE-2023-48706).

The whole reproducible test is a bit tricky, I can only reproduce this
reliably when no previous substitution command has been used yet
(which is the reason, the test needs to run as first one in the
test_substitute.vim file) and as a combination of the `:~` command
together with a :s command that contains the special substitution atom `~\=`
which will make use of a sub-replace special atom and calls a vim script
function.

There was a comment in the existing :s code, that already makes the
`sub` variable allocate memory so that a recursive :s call won't be able
to cause any issues here, so this was known as a potential problem
already.  But for the current test-case that one does not work, because
the substitution does not start with `\=` but with `~\=` (and since
there does not yet exist a previous substitution atom, Vim will simply
increment the `sub` pointer (which then was not allocated dynamically)
and later one happily use a sub-replace special expression (which could
then free the `sub` var).

The following commit fixes this, by making the sub var always using
allocated memory, which also means we need to free the pointer whenever
we leave the function. Since sub is now always an allocated variable,
we also do no longer need the sub_copy variable anymore, since this one
was used to indicated when sub pointed to allocated memory (and had
therefore to be freed on exit) and when not.

Github Security Advisory:
https://github.com/vim/vim/security/advisories/GHSA-c8qm-x72m-q53q

Signed-off-by: Christian Brabandt <cb@256bit.org>

Diff: diff --git a/src/ex_cmds.c b/src/ex_cmds.c
index c5f912e7ee57..a08682b071fb 100644
--- a/src/ex_cmds.c
+++ b/src/ex_cmds.c
@@ -3735,17 +3735,17 @@ ex_substitute(exarg_T *eap)
     subflags_T	subflags_save;
 #endif
     int		save_do_all;		// remember user specified 'g' flag
     int		save_do_ask;		// remember user specified 'c' flag
     char_u	*pat = NULL, *sub = NULL;	// init for GCC
-    char_u	*sub_copy = NULL;
     int		delimiter;
     int		sublen;
     int		got_quit = FALSE;
     int		got_match = FALSE;
     int		which_pat;
     char_u	*cmd;
+    char_u	*p;
     int		save_State;
     linenr_T	first_line = 0;		// first changed line
     linenr_T	last_line= 0;		// below last changed line AFTER the
 					// change
     linenr_T	old_line_count = curbuf->b_ml.ml_line_count;
@@ -3825,30 +3825,42 @@ ex_substitute(exarg_T *eap)
 
 	/*
 	 * Small incompatibility: vi sees '\n' as end of the command, but in
 	 * Vim we want to use '\n' to find/substitute a NUL.
 	 */
-	sub = cmd;	    // remember the start of the substitution
+	p = cmd;	    // remember the start of the substitution
 	cmd = skip_substitute(cmd, delimiter);
+	sub = vim_strsave(p);
+	if (sub == NULL)
+	    // out of memory
+	    return;
 
 	if (!eap->skip)
 	{
 	    // In POSIX vi ":s/pat/%/" uses the previous subst. string.
 	    if (STRCMP(sub, "%") == 0
 				 && vim_strchr(p_cpo, CPO_SUBPERCENT) != NULL)
 	    {
 		if (old_sub == NULL)	// there is no previous command
 		{
 		    emsg(_(e_no_previous_substitute_regular_expression));
+		    vim_free(sub);
 		    return;
 		}
-		sub = old_sub;
+		vim_free(sub);
+		sub = vim_strsave(old_sub);
+		if (sub == NULL)
+		    // out of memory
+		    return;
 	    }
 	    else
 	    {
 		vim_free(old_sub);
 		old_sub = vim_strsave(sub);
+		if (old_sub == NULL)
+		    // out of memory
+		    return;
 	    }
 	}
     }
     else if (!eap->skip)	// use previous pattern and substitution
     {
@@ -3856,11 +3868,11 @@ ex_substitute(exarg_T *eap)
 	{
 	    emsg(_(e_no_previous_substitute_regular_expression));
 	    return;
 	}
 	pat = NULL;		// search_regcomp() will use previous pattern
-	sub = old_sub;
+	sub = vim_strsave(old_sub);
 
 	// Vi compatibility quirk: repeating with ":s" keeps the cursor in the
 	// last column after using "$".
 	endcolumn = (curwin->w_curswant == MAXCOL);
     }
@@ -3875,11 +3887,14 @@ ex_substitute(exarg_T *eap)
 					     || *cmd == 'p' || *cmd == '#'))))
     {
 	linenr_T    joined_lines_count;
 
 	if (eap->skip)
+	{
+	    vim_free(sub);
 	    return;
+	}
 	curwin->w_cursor.lnum = eap->line1;
 	if (*cmd == 'l')
 	    eap->flags = EXFLAG_LIST;
 	else if (*cmd == '#')
 	    eap->flags = EXFLAG_NR;
@@ -3902,10 +3917,11 @@ ex_substitute(exarg_T *eap)
 
 	if ((cmdmod.cmod_flags & CMOD_KEEPPATTERNS) == 0)
 	    save_re_pat(RE_SUBST, pat, magic_isset());
 	// put pattern in history
 	add_to_history(HIST_SEARCH, pat, TRUE, NUL);
+	vim_free(sub);
 
 	return;
     }
 
     /*
@@ -3989,17 +4005,19 @@ ex_substitute(exarg_T *eap)
     {
 	i = getdigits(&cmd);
 	if (i <= 0 && !eap->skip && subflags.do_error)
 	{
 	    emsg(_(e_positive_count_required));
+	    vim_free(sub);
 	    return;
 	}
 	else if (i >= INT_MAX)
 	{
 	    char	buf[20];
 	    vim_snprintf(buf, sizeof(buf), "%ld", i);
 	    semsg(_(e_val_too_large), buf);
+	    vim_free(sub);
 	    return;
 	}
 	eap->line1 = eap->line2;
 	eap->line2 += i - 1;
 	if (eap->line2 > curbuf->b_ml.ml_line_count)
@@ -4014,28 +4032,34 @@ ex_substitute(exarg_T *eap)
     {
 	set_nextcmd(eap, cmd);
 	if (eap->nextcmd == NULL)
 	{
 	    semsg(_(e_trailing_characters_str), cmd);
+	    vim_free(sub);
 	    return;
 	}
     }
 
     if (eap->skip)	    // not executing commands, only parsing
+    {
+	vim_free(sub);
 	return;
+    }
 
     if (!subflags.do_count && !curbuf->b_p_ma)
     {
 	// Substitution is not allowed in non-'modifiable' buffer
 	emsg(_(e_cannot_make_changes_modifiable_is_off));
+	vim_free(sub);
 	return;
     }
 
     if (search_regcomp(pat, NULL, RE_SUBST, which_pat, SEARCH_HIS, &regmatch) == FAIL)
     {
 	if (subflags.do_error)
 	    emsg(_(e_invalid_command));
+	vim_free(sub);
 	return;
     }
 
     // the 'i' or 'I' flag overrules 'ignorecase' and 'smartcase'
     if (subflags.do_ic == 'i')
@@ -4052,24 +4076,24 @@ ex_substitute(exarg_T *eap)
      * pattern.  We do it here once to avoid it to be replaced over and over
      * again.
      */
     if (sub[0] == '\\' && sub[1] == '=')
     {
-	sub = vim_strsave(sub);
-	if (sub == NULL)
+	p = vim_strsave(sub);
+	vim_free(sub);
+	if (p == NULL)
 	    return;
-	sub_copy = sub;
+	sub = p;
     }
     else
     {
-	char_u *newsub = regtilde(sub, magic_isset());
+	p = regtilde(sub, magic_isset());
 
-	if (newsub != sub)
+	if (p != sub)
 	{
-	    // newsub was allocated, free it later.
-	    sub_copy = newsub;
-	    sub = newsub;
+	    vim_free(sub);
+	    sub = p;
 	}
     }
 
     /*
      * Check for a match on each line.
@@ -4963,11 +4987,11 @@ outofmem:
 	// Cursor position may require updating
 	changed_window_setting();
 #endif
 
     vim_regfree(regmatch.regprog);
-    vim_free(sub_copy);
+    vim_free(sub);
 
     // Restore the flag values, they can be used for ":&&".
     subflags.do_all = save_do_all;
     subflags.do_ask = save_do_ask;
 }
diff --git a/src/testdir/test_substitute.vim b/src/testdir/test_substitute.vim
index 3ed159799f5c..7c2bbb476770 100644
--- a/src/testdir/test_substitute.vim
+++ b/src/testdir/test_substitute.vim
@@ -2,10 +2,36 @@
 
 source shared.vim
 source check.vim
 source screendump.vim
 
+" NOTE: This needs to be the first test to be
+"       run in the file, since it depends on
+"       that the previous substitution atom
+"       was not yet set.
+"
+" recursive call of :s and sub-replace special
+" (did cause heap-use-after free in < v9.0.2121)
+func Test_aaaa_substitute_expr_recursive_special()
+  func R()
+    " FIXME: leaving out the 'n' flag leaks memory, why?
+    %s/./\='.'/gn
+  endfunc
+  new Xfoobar_UAF
+  put ='abcdef'
+  let bufnr = bufnr('%')
+  try
+    silent! :s/./~\=R()/0
+    "call assert_fails(':s/./~\=R()/0', 'E939:')
+    let @/='.'
+    ~g
+  catch /^Vim\%((\a\+)\)\=:E565:/
+  endtry
+  delfunc R
+  exe bufnr .. "bw!"
+endfunc
+
 func Test_multiline_subst()
   enew!
   call append(0, ["1 aa",
 	      \ "bb",
 	      \ "cc",
@@ -145,11 +171,10 @@ func Test_substitute_repeat()
   split Xsubfile
   s/^/x
   call feedkeys("Qsc\<CR>y", 'tx')
   bwipe!
 endfunc
-
 " Test %s/\n// which is implemented as a special case to use a
 " more efficient join rather than doing a regular substitution.
 func Test_substitute_join()
   new
 
@@ -1445,13 +1470,32 @@ func Test_substitute_expr_switch_win()
     wincmd x
     return 'XXXX'
   endfunc
   new Xfoobar
   let bufnr = bufnr('%')
-  put ="abcdef"
+  put ='abcdef'
   silent! s/\%')/\=R()
   call assert_fails(':%s/./\=R()/g', 'E565:')
   delfunc R
   exe bufnr .. "bw!"
 endfunc
 
+" recursive call of :s using test-replace special
+func Test_substitute_expr_recursive()
+  func Q()
+    %s/./\='foobar'/gn
+    return "foobar"
+  endfunc
+  func R()
+    %s/./\=Q()/g
+  endfunc
+  new Xfoobar_UAF
+  let bufnr = bufnr('%')
+  put ='abcdef'
+  silent! s/./\=R()/g
+  call assert_fails(':%s/./\=R()/g', 'E565:')
+  delfunc R
+  delfunc Q
+  exe bufnr .. "bw!"
+endfunc
+
 " vim: shiftwidth=2 sts=2 expandtab
diff --git a/src/version.c b/src/version.c
index edf6b576fe2a..642da01d8b2f 100644
--- a/src/version.c
+++ b/src/version.c
@@ -702,10 +702,12 @@ static char *(features[]) =
 	NULL
 };
 
 static int included_patches[] =
 {   /* Add new patch number below this line */
+/**/
+    2121,
 /**/
     2120,
 /**/
     2119,
 /**/

Vulnerable code:     char_u	*sub_copy = NULL;
	sub = cmd;	    // remember the start of the substitution
		sub = old_sub;
	sub = old_sub;
	sub = vim_strsave(sub);
	if (sub == NULL)
	sub_copy = sub;
	char_u *newsub = regtilde(sub, magic_isset());
	if (newsub != sub)
	    // newsub was allocated, free it later.
	    sub_copy = newsub;
	    sub = newsub;
    vim_free(sub_copy);

  put ="abcdef"
Fixed code:     char_u	*p;
	p = cmd;	    // remember the start of the substitution
	sub = vim_strsave(p);
	if (sub == NULL)
	    // out of memory
	    return;
		    vim_free(sub);
		vim_free(sub);
		sub = vim_strsave(old_sub);
		if (sub == NULL)
		    // out of memory
		    return;
		if (old_sub == NULL)
		    // out of memory
		    return;
	sub = vim_strsave(old_sub);
	{
	    vim_free(sub);
	}
	vim_free(sub);
	    vim_free(sub);
	    vim_free(sub);
	    vim_free(sub);
    {
	vim_free(sub);
    }
	vim_free(sub);
	vim_free(sub);
	p = vim_strsave(sub);
	vim_free(sub);
	if (p == NULL)
	sub = p;
	p = regtilde(sub, magic_isset());
	if (p != sub)
	    vim_free(sub);
	    sub = p;
    vim_free(sub);
" NOTE: This needs to be the first test to be
"       run in the file, since it depends on
"       that the previous substitution atom
"       was not yet set.
"
" recursive call of :s and sub-replace special
" (did cause heap-use-after free in < v9.0.2121)
func Test_aaaa_substitute_expr_recursive_special()
  func R()
    " FIXME: leaving out the 'n' flag leaks memory, why?
    %s/./\='.'/gn
  endfunc
  new Xfoobar_UAF
  put ='abcdef'
  let bufnr = bufnr('%')
  try
    silent! :s/./~\=R()/0
    "call assert_fails(':s/./~\=R()/0', 'E939:')
    let @/='.'
    ~g
  catch /^Vim\%((\a\+)\)\=:E565:/
  endtry
  delfunc R
  exe bufnr .. "bw!"
endfunc

  put ='abcdef'
" recursive call of :s using test-replace special
func Test_substitute_expr_recursive()
  func Q()
    %s/./\='foobar'/gn
    return "foobar"
  endfunc
  func R()
    %s/./\=Q()/g
  endfunc
  new Xfoobar_UAF
  let bufnr = bufnr('%')
  put ='abcdef'
  silent! s/./\=R()/g
  call assert_fails(':%s/./\=R()/g', 'E565:')
  delfunc R
  delfunc Q
  exe bufnr .. "bw!"
endfunc

/**/
    2121,