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

Dmitry Klochkov via busybox <[email protected]> Fri, 24 Jul 2026 16:45:38 +0300
Newsgroups gmane.linux.busybox
Message-ID <o422rqpjhwfqttegd7akc4aqssjl6qrlx5hidju36vddyorjaq@2sq5h3wu5rc3>
Hi Sanghyun,

On Tue, Jun 16, 2026 at 12:18:43PM +0900, Sanghyun Park via busybox wrote:
> 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.

Could you please explain where exactly as_regex() can change the awk
variable storage? This is not obvious to me.

Thanks,
Dmitry

> 
> 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
> _______________________________________________
> busybox mailing list
> [email protected]
> https://lists.busybox.net/mailman/listinfo/busybox