[PATCH] awk: fix use-after-free in awk_sub()

Sanghyun Park via busybox <[email protected]> Tue, 16 Jun 2026 12:18:43 +0900
Newsgroups gmane.linux.busybox
Message-ID <[email protected]>
awk_sub() receives the replacement text as a pointer into awk variable
storage. Evaluating the regular expression argument can change that
storage through as_regex(), leaving the replacement pointer dangling
before strlen() and the replacement loop use it.

Copy the replacement string before calling as_regex() so substitution
uses stable storage for the duration of the operation.

Signed-off-by: Sanghyun Park <[email protected]>
---
 editors/awk.c | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/editors/awk.c b/editors/awk.c
index f15832b..8a51827 100644
--- a/editors/awk.c
+++ b/editors/awk.c
@@ -2555,6 +2555,7 @@ static char *awk_printf(node *n, size_t *len)
 static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,int subexp*/)
 {
 	char *resbuf;
+	char *repl_copy;
 	const char *sp;
 	int match_no, residx, replen, resbufsize;
 	int regexec_flags;
@@ -2572,7 +2573,9 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
 	resbuf = NULL;
 	residx = 0;
 	match_no = 0;
+	repl_copy = xstrdup(repl);
 	regex = as_regex(rn, &sreg);
+	repl = repl_copy;
 	sp = getvar_s(src ? src : intvar[F0]);
 #if defined(REG_STARTEND)
 	src_string = sp;
@@ -2662,6 +2665,7 @@ static int awk_sub(node *rn, const char *repl, int nm, var *src, var *dest /*,in
 	setvar_p(dest ? dest : intvar[F0], resbuf);
 	if (regex == &sreg)
 		regfree(regex);
+	free(repl_copy);
 	return match_no;
 }
 
-- 
2.48.1