f925fa
From c031e3ec7c713077659f5f7dc6638d926c69d7b2 Mon Sep 17 00:00:00 2001
f925fa
From: Hugo van der Sanden <hv@crypt.org>
f925fa
Date: Sat, 11 Apr 2020 14:10:24 +0100
f925fa
Subject: [PATCH v528 3/3] study_chunk: avoid mutating regexp program within
f925fa
 GOSUB
f925fa
f925fa
gh16947 and gh17743: studying GOSUB may restudy in an inner call
f925fa
(via a mix of recursion and enframing) something that an outer call
f925fa
is in the middle of looking at.  Let the outer frame deal with it.
f925fa
f925fa
(CVE-2020-12723)
f925fa
---
f925fa
 embed.fnc  |  2 +-
f925fa
 embed.h    |  2 +-
f925fa
 proto.h    |  2 +-
f925fa
 regcomp.c  | 48 ++++++++++++++++++++++++++++++++----------------
f925fa
 t/re/pat.t | 26 +++++++++++++++++++++++++-
f925fa
 5 files changed, 60 insertions(+), 20 deletions(-)
f925fa
f925fa
diff --git a/embed.fnc b/embed.fnc
f925fa
index cf89277163..4b1ba28277 100644
f925fa
--- a/embed.fnc
f925fa
+++ b/embed.fnc
f925fa
@@ -2397,7 +2397,7 @@ Es	|SSize_t|study_chunk	|NN RExC_state_t *pRExC_state \
f925fa
 				|NULLOK struct scan_data_t *data \
f925fa
                                 |I32 stopparen|U32 recursed_depth \
f925fa
 				|NULLOK regnode_ssc *and_withp \
f925fa
-				|U32 flags|U32 depth
f925fa
+				|U32 flags|U32 depth|bool was_mutate_ok
f925fa
 EsRn	|U32	|add_data	|NN RExC_state_t* const pRExC_state \
f925fa
 				|NN const char* const s|const U32 n
f925fa
 rs	|void	|re_croak2	|bool utf8|NN const char* pat1|NN const char* pat2|...
f925fa
diff --git a/embed.h b/embed.h
f925fa
index 886551ce5c..50fcabc140 100644
f925fa
--- a/embed.h
f925fa
+++ b/embed.h
f925fa
@@ -1075,7 +1075,7 @@
f925fa
 #define ssc_is_cp_posixl_init	S_ssc_is_cp_posixl_init
f925fa
 #define ssc_or(a,b,c)		S_ssc_or(aTHX_ a,b,c)
f925fa
 #define ssc_union(a,b,c)	S_ssc_union(aTHX_ a,b,c)
f925fa
-#define study_chunk(a,b,c,d,e,f,g,h,i,j,k)	S_study_chunk(aTHX_ a,b,c,d,e,f,g,h,i,j,k)
f925fa
+#define study_chunk(a,b,c,d,e,f,g,h,i,j,k,l)	S_study_chunk(aTHX_ a,b,c,d,e,f,g,h,i,j,k,l)
f925fa
 #  endif
f925fa
 #  if defined(PERL_IN_REGCOMP_C) || defined (PERL_IN_DUMP_C)
f925fa
 #define _invlist_dump(a,b,c,d)	Perl__invlist_dump(aTHX_ a,b,c,d)
f925fa
diff --git a/proto.h b/proto.h
f925fa
index d3f8802c1d..e276f69bd1 100644
f925fa
--- a/proto.h
f925fa
+++ b/proto.h
f925fa
@@ -5258,7 +5258,7 @@ PERL_STATIC_INLINE void	S_ssc_union(pTHX_ regnode_ssc *ssc, SV* const invlist, c
f925fa
 #define PERL_ARGS_ASSERT_SSC_UNION	\
f925fa
 	assert(ssc); assert(invlist)
f925fa
 #endif
f925fa
-STATIC SSize_t	S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, SSize_t *minlenp, SSize_t *deltap, regnode *last, struct scan_data_t *data, I32 stopparen, U32 recursed_depth, regnode_ssc *and_withp, U32 flags, U32 depth);
f925fa
+STATIC SSize_t	S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp, SSize_t *minlenp, SSize_t *deltap, regnode *last, struct scan_data_t *data, I32 stopparen, U32 recursed_depth, regnode_ssc *and_withp, U32 flags, U32 depth, bool was_mutate_ok);
f925fa
 #define PERL_ARGS_ASSERT_STUDY_CHUNK	\
f925fa
 	assert(pRExC_state); assert(scanp); assert(minlenp); assert(deltap); assert(last)
f925fa
 #endif
f925fa
diff --git a/regcomp.c b/regcomp.c
f925fa
index 0a9c6a8085..e66032a16a 100644
f925fa
--- a/regcomp.c
f925fa
+++ b/regcomp.c
f925fa
@@ -110,6 +110,7 @@ typedef struct scan_frame {
f925fa
     regnode *next_regnode;      /* next node to process when last is reached */
f925fa
     U32 prev_recursed_depth;
f925fa
     I32 stopparen;              /* what stopparen do we use */
f925fa
+    bool in_gosub;              /* this or an outer frame is for GOSUB */
f925fa
     U32 is_top_frame;           /* what flags do we use? */
f925fa
 
f925fa
     struct scan_frame *this_prev_frame; /* this previous frame */
f925fa
@@ -4102,7 +4103,7 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
 			I32 stopparen,
f925fa
                         U32 recursed_depth,
f925fa
 			regnode_ssc *and_withp,
f925fa
-			U32 flags, U32 depth)
f925fa
+			U32 flags, U32 depth, bool was_mutate_ok)
f925fa
 			/* scanp: Start here (read-write). */
f925fa
 			/* deltap: Write maxlen-minlen here. */
f925fa
 			/* last: Stop before this one. */
f925fa
@@ -4179,6 +4180,10 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
                                    node length to get a real minimum (because
f925fa
                                    the folded version may be shorter) */
f925fa
 	bool unfolded_multi_char = FALSE;
f925fa
+        /* avoid mutating ops if we are anywhere within the recursed or
f925fa
+         * enframed handling for a GOSUB: the outermost level will handle it.
f925fa
+         */
f925fa
+        bool mutate_ok = was_mutate_ok && !(frame && frame->in_gosub);
f925fa
 	/* Peephole optimizer: */
f925fa
         DEBUG_STUDYDATA("Peep:", data, depth);
f925fa
         DEBUG_PEEP("Peep", scan, depth);
f925fa
@@ -4189,7 +4194,8 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
          * parsing code, as each (?:..) is handled by a different invocation of
f925fa
          * reg() -- Yves
f925fa
          */
f925fa
-        JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
f925fa
+        if (mutate_ok)
f925fa
+            JOIN_EXACT(scan,&min_subtract, &unfolded_multi_char, 0);
f925fa
 
f925fa
 	/* Follow the next-chain of the current node and optimize
f925fa
 	   away all the NOTHINGs from it.  */
f925fa
@@ -4238,7 +4244,7 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
              * NOTE we dont use the return here! */
f925fa
             (void)study_chunk(pRExC_state, &scan, &minlen,
f925fa
                               &deltanext, next, &data_fake, stopparen,
f925fa
-                              recursed_depth, NULL, f, depth+1);
f925fa
+                              recursed_depth, NULL, f, depth+1, mutate_ok);
f925fa
 
f925fa
             scan = next;
f925fa
         } else
f925fa
@@ -4305,7 +4311,8 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
 		    /* we suppose the run is continuous, last=next...*/
f925fa
 		    minnext = study_chunk(pRExC_state, &scan, minlenp,
f925fa
                                       &deltanext, next, &data_fake, stopparen,
f925fa
-                                      recursed_depth, NULL, f,depth+1);
f925fa
+                                      recursed_depth, NULL, f, depth+1,
f925fa
+                                      mutate_ok);
f925fa
 
f925fa
 		    if (min1 > minnext)
f925fa
 			min1 = minnext;
f925fa
@@ -4372,9 +4379,10 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
 		    }
f925fa
 		}
f925fa
 
f925fa
-                if (PERL_ENABLE_TRIE_OPTIMISATION &&
f925fa
-                        OP( startbranch ) == BRANCH )
f925fa
-                {
f925fa
+                if (PERL_ENABLE_TRIE_OPTIMISATION
f925fa
+                    && OP(startbranch) == BRANCH
f925fa
+                    && mutate_ok
f925fa
+                ) {
f925fa
 		/* demq.
f925fa
 
f925fa
                    Assuming this was/is a branch we are dealing with: 'scan'
f925fa
@@ -4825,6 +4833,9 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
                 newframe->stopparen = stopparen;
f925fa
                 newframe->prev_recursed_depth = recursed_depth;
f925fa
                 newframe->this_prev_frame= frame;
f925fa
+                newframe->in_gosub = (
f925fa
+                    (frame && frame->in_gosub) || OP(scan) == GOSUB
f925fa
+                );
f925fa
 
f925fa
                 DEBUG_STUDYDATA("frame-new:",data,depth);
f925fa
                 DEBUG_PEEP("fnew", scan, depth);
f925fa
@@ -5043,7 +5054,7 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
                                   (mincount == 0
f925fa
                                    ? (f & ~SCF_DO_SUBSTR)
f925fa
                                    : f)
f925fa
-                                  ,depth+1);
f925fa
+                                  , depth+1, mutate_ok);
f925fa
 
f925fa
 		if (flags & SCF_DO_STCLASS)
f925fa
 		    data->start_class = oclass;
f925fa
@@ -5105,7 +5116,9 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
 		if (  OP(oscan) == CURLYX && data
f925fa
 		      && data->flags & SF_IN_PAR
f925fa
 		      && !(data->flags & SF_HAS_EVAL)
f925fa
-		      && !deltanext && minnext == 1 ) {
f925fa
+		      && !deltanext && minnext == 1
f925fa
+                      && mutate_ok
f925fa
+                ) {
f925fa
 		    /* Try to optimize to CURLYN.  */
f925fa
 		    regnode *nxt = NEXTOPER(oscan) + EXTRA_STEP_2ARGS;
f925fa
 		    regnode * const nxt1 = nxt;
f925fa
@@ -5151,10 +5164,10 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
 		      && !(data->flags & SF_HAS_EVAL)
f925fa
 		      && !deltanext	/* atom is fixed width */
f925fa
 		      && minnext != 0	/* CURLYM can't handle zero width */
f925fa
-
f925fa
                          /* Nor characters whose fold at run-time may be
f925fa
                           * multi-character */
f925fa
                       && ! (RExC_seen & REG_UNFOLDED_MULTI_SEEN)
f925fa
+                      && mutate_ok
f925fa
 		) {
f925fa
 		    /* XXXX How to optimize if data == 0? */
f925fa
 		    /* Optimize to a simpler form.  */
f925fa
@@ -5201,7 +5214,8 @@ S_study_chunk(pTHX_ RExC_state_t *pRExC_state, regnode **scanp,
f925fa
 #endif
f925fa
 			/* Optimize again: */
f925fa
 			study_chunk(pRExC_state, &nxt1, minlenp, &deltanext, nxt,
f925fa
-                                    NULL, stopparen, recursed_depth, NULL, 0,depth+1);
f925fa
+                                    NULL, stopparen, recursed_depth, NULL, 0,
f925fa
+                                    depth+1, mutate_ok);
f925fa
 		    }
f925fa
 		    else
f925fa
 			oscan->flags = 0;
f925fa
@@ -5592,7 +5606,8 @@ Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
f925fa
                 nscan = NEXTOPER(NEXTOPER(scan));
f925fa
                 minnext = study_chunk(pRExC_state, &nscan, minlenp, &deltanext,
f925fa
                                       last, &data_fake, stopparen,
f925fa
-                                      recursed_depth, NULL, f, depth+1);
f925fa
+                                      recursed_depth, NULL, f, depth+1,
f925fa
+                                      mutate_ok);
f925fa
                 if (scan->flags) {
f925fa
                     if (deltanext) {
f925fa
 			FAIL("Variable length lookbehind not implemented");
f925fa
@@ -5681,7 +5696,7 @@ Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
f925fa
                 *minnextp = study_chunk(pRExC_state, &nscan, minnextp,
f925fa
                                         &deltanext, last, &data_fake,
f925fa
                                         stopparen, recursed_depth, NULL,
f925fa
-                                        f,depth+1);
f925fa
+                                        f, depth+1, mutate_ok);
f925fa
                 if (scan->flags) {
f925fa
                     if (deltanext) {
f925fa
 			FAIL("Variable length lookbehind not implemented");
f925fa
@@ -5841,7 +5856,8 @@ Perl_re_printf( aTHX_  "LHS=%" UVuf " RHS=%" UVuf "\n",
f925fa
                            branches even though they arent otherwise used. */
f925fa
                         minnext = study_chunk(pRExC_state, &scan, minlenp,
f925fa
                             &deltanext, (regnode *)nextbranch, &data_fake,
f925fa
-                            stopparen, recursed_depth, NULL, f,depth+1);
f925fa
+                            stopparen, recursed_depth, NULL, f, depth+1,
f925fa
+                            mutate_ok);
f925fa
                     }
f925fa
                     if (nextbranch && PL_regkind[OP(nextbranch)]==BRANCH)
f925fa
                         nextbranch= regnext((regnode*)nextbranch);
f925fa
@@ -7524,7 +7540,7 @@ Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
f925fa
             &data, -1, 0, NULL,
f925fa
             SCF_DO_SUBSTR | SCF_WHILEM_VISITED_POS | stclass_flag
f925fa
                           | (restudied ? SCF_TRIE_DOING_RESTUDY : 0),
f925fa
-            0);
f925fa
+            0, TRUE);
f925fa
 
f925fa
 
f925fa
         CHECK_RESTUDY_GOTO_butfirst(LEAVE_with_name("study_chunk"));
f925fa
@@ -7670,7 +7686,7 @@ Perl_re_op_compile(pTHX_ SV ** const patternp, int pat_count,
f925fa
             SCF_DO_STCLASS_AND|SCF_WHILEM_VISITED_POS|(restudied
f925fa
                                                       ? SCF_TRIE_DOING_RESTUDY
f925fa
                                                       : 0),
f925fa
-            0);
f925fa
+            0, TRUE);
f925fa
 
f925fa
         CHECK_RESTUDY_GOTO_butfirst(NOOP);
f925fa
 
f925fa
diff --git a/t/re/pat.t b/t/re/pat.t
f925fa
index 1d98fe77d7..1488259b02 100644
f925fa
--- a/t/re/pat.t
f925fa
+++ b/t/re/pat.t
f925fa
@@ -23,7 +23,7 @@ BEGIN {
f925fa
     skip_all('no re module') unless defined &DynaLoader::boot_DynaLoader;
f925fa
     skip_all_without_unicode_tables();
f925fa
 
f925fa
-plan tests => 840;  # Update this when adding/deleting tests.
f925fa
+plan tests => 844;  # Update this when adding/deleting tests.
f925fa
 
f925fa
 run_tests() unless caller;
f925fa
 
f925fa
@@ -1929,6 +1929,30 @@ EOP
f925fa
         fresh_perl_is('"AA" =~ m/AA{1,0}/','',{},"handle OPFAIL insert properly");
f925fa
     }
f925fa
 
f925fa
+    # gh16947: test regexp corruption (GOSUB)
f925fa
+    {
f925fa
+        fresh_perl_is(q{
f925fa
+            'xy' =~ /x(?0)|x(?|y|y)/ && print 'ok'
f925fa
+        }, 'ok', {}, 'gh16947: test regexp corruption (GOSUB)');
f925fa
+    }
f925fa
+    # gh16947: test fix doesn't break SUSPEND
f925fa
+    {
f925fa
+        fresh_perl_is(q{ 'sx' =~ m{ss++}i; print 'ok' },
f925fa
+                'ok', {}, "gh16947: test fix doesn't break SUSPEND");
f925fa
+    }
f925fa
+
f925fa
+    # gh17743: more regexp corruption via GOSUB
f925fa
+    {
f925fa
+        fresh_perl_is(q{
f925fa
+            "0" =~ /((0(?0)|000(?|0000|0000)(?0))|)/; print "ok"
f925fa
+        }, 'ok', {}, 'gh17743: test regexp corruption (1)');
f925fa
+
f925fa
+        fresh_perl_is(q{
f925fa
+            "000000000000" =~ /(0(())(0((?0)())|000(?|\x{ef}\x{bf}\x{bd}|\x{ef}\x{bf}\x{bd}))|)/;
f925fa
+            print "ok"
f925fa
+        }, 'ok', {}, 'gh17743: test regexp corruption (2)');
f925fa
+    }
f925fa
+
f925fa
 } # End of sub run_tests
f925fa
 
f925fa
 1;
f925fa
-- 
f925fa
2.20.1
f925fa