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