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

From: Assaf Gordon <[email-masked]>
Date: Wed, 5 Sep 2018 18:04:03 -0600

Hello,

> On Wed, Sep 5, 2018 at 12:32 AM Assaf Gordon <[email-masked]> wrote: >>>> On 04/09/18 07:02 PM, Saito Takaaki wrote:>>> 
https://ideone.com/Sq5xJX>>>>>> I hope this helps even a bit.>>>> The 
linked snippet you provided exposed a heap-use-after-free bug
>> in gnulib's regex module (possibly in glibc as well).

Please find the attached patch as a suggested fix.

Comments and review very welcomed,
  - assaf
>From d58391ad0377f0fde07e8f555583bff8125772d3 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     | 12 ++++++++++++
 lib/regexec.c |  1 +
 2 files changed, 13 insertions(+)

diff --git a/ChangeLog b/ChangeLog
index 23689545a..3cafe2177 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -1,3 +1,15 @@
+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.
+	Additionally, check for allocation errors and bail out if needed.
+
 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