From e9fc519737f0901c96658241a31161e1401c4c96 Mon Sep 17 00:00:00 2001 From: Martijn Dekker Date: Fri, 19 Aug 2022 18:32:50 +0100 Subject: [PATCH] Fix buffer overflow in sh_lex() This macro expansion in lex.c may assign -1 to n if EOF is reached: 1178: fcgetc(n); As a result, n may be -1 when this code is reached: 1190: if(sh_isoption(SH_BRACEEXPAND) && c==LBRACE && !assignment && state[n]!=S_BREAK 'state[n]' is a buffer overflow if n==-1. src/cmd/ksh93/sh/lex.c: sh_lex(): case S_BRACE: - Apart from the buffer overflow, if n<=0, none of the code following fcget(n) does anything until 'break' on line 1199 is reached. So, if fcget(n) yields <=0, just break. This allows some code simplification. Progresses: https://github.com/ksh93/ksh/issues/518 --- src/cmd/ksh93/sh/lex.c | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/src/cmd/ksh93/sh/lex.c b/src/cmd/ksh93/sh/lex.c index db0cefcff..4d0ad60be 100644 --- a/src/cmd/ksh93/sh/lex.c +++ b/src/cmd/ksh93/sh/lex.c @@ -1175,14 +1175,12 @@ int sh_lex(Lex_t* lp) goto do_reg; } isfirst = (lp->lexd.first&&fcseek(0)==lp->lexd.first+1); - fcgetc(n); + if(fcgetc(n)<=0) + break; /* check for {} */ if(c==LBRACE && n==RBRACE) break; - if(n>0) - fcseek(-LEN); - else if(lp->lex.reservok) - break; + fcseek(-LEN); /* check for reserved word { or } */ if(lp->lex.reservok && state[n]==S_BREAK && isfirst) break;