Subject: Re: bug#32592: heap-use-after-free in regex module

From: Assaf Gordon <[email-masked]>
Date: Wed, 5 Sep 2018 19:28:14 -0600

Bruno alerted me off-list:

On 05/09/18 07:19 PM, Bruno Haible wrote:
 > Is the ChangeLog entry up-to-date?
 >
 > +	* regexec.c (get_subexp): Update 'buf' after call to get_subexp_sub.
 > +	Additionally, check for allocation errors and bail out if needed.
 >
 > I don't see a code change for
 > "check for allocation errors and bail out if needed".

Thanks!

I initially had a check for REG_NOERROR there, but removed it.

Attached an updated patch without the outdated comment.

-assaf

>From 3e6bc87d1a8dc6e22c6d60d06aef0b0b6cb03a49 Mon Sep 17 00:00:00 2001
From: Assaf Gordon <[email-masked]>
Date: Wed, 5 Sep 2018 17:40:28 -0600
Subject: [PATCH] regex: fix heap-use-after-free error

Problem reported by Saito Takaaki <[email-masked]> in
https://debbugs.gnu.org/32592
Calling get_subexp() -> get_subexp_sub() -> clean_state_log_if_needed() may
call extend_buffers() which reallocates the re_string_t's internal buffer.
Local variable 'buf' was not updated in such case, resulting in
use-after-free.
* regexec.c (get_subexp): Update 'buf' after calling get_subexp_sub.
---
 ChangeLog     | 11 +++++++++++
 lib/regexec.c |  1 +
 2 files changed, 12 insertions(+)

diff --git a/ChangeLog b/ChangeLog
index 23689545a..e3c01c644 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,14 @@
+2018-09-05  Assaf Gordon <[email-masked]>
+
+	regex: fix heap-use-after-free error
+	Problem reported by Saito Takaaki <[email-masked]> in
+	https://debbugs.gnu.org/32592
+	Call stack get_subexp->get_subexp_sub->clean_state_log_if_needed may
+	call extend_buffers which reallocates the re_string_t internal buffer.
+	Local variable 'buf' was not updated in such case, resulting in
+	use-after-free.
+	* regexec.c (get_subexp): Update 'buf' after call to get_subexp_sub.
+
 2018-09-05  Eric Blake  <[email-masked]>
 
 	doc: mention environ pitfall
diff --git a/lib/regexec.c b/lib/regexec.c
index 73644c234..61a4ea26d 100644
--- a/lib/regexec.c
+++ b/lib/regexec.c
@@ -2777,6 +2777,7 @@ get_subexp (re_match_context_t *mctx, Idx bkref_node, Idx bkref_str_idx)
 	    return REG_ESPACE;
 	  err = get_subexp_sub (mctx, sub_top, sub_last, bkref_node,
 				bkref_str_idx);
+	  buf = (const char *) re_string_get_buffer (&mctx->input);
 	  if (err == REG_NOMATCH)
 	    continue;
 	}
-- 
2.11.0