Skip to content

Commit

Permalink
io_prompt(): fix use-after-free in PS2 handling (re: 2322f93)
Browse files Browse the repository at this point in the history
If a PS2.get discipline function is set (like in our shipped
'bin/package use' environment), then the value of PS2 is pushed on
the stack (see nvdisc.c:429). So, restoring the stack state after
getting the PS2 value may free the space that contains the value
and a use-after-free may occur when calling sfputr to output it.

src/cmd/ksh93/sh/io.c: io_prompt():
- Output the obtained value of PS2 before restoring the stack.
- Get rid of the ugly gotos.
  • Loading branch information
McDutchie committed Dec 31, 2024
1 parent 13b9897 commit d2b0f82
Showing 1 changed file with 7 additions and 11 deletions.
18 changes: 7 additions & 11 deletions src/cmd/ksh93/sh/io.c
Original file line number Diff line number Diff line change
Expand Up @@ -2167,35 +2167,31 @@ static int io_prompt(Sfio_t *iop,int flag)
c = *++cp;
/* print out line number if not !! */
if(c!= HIST_CHAR)
{
sfprintf(sfstderr,"%d", sh.hist_ptr?(int)sh.hist_ptr->histind:++cmdno);
}
if(c==0)
goto done;
break;
}
sfputc(sfstderr,c);
}
goto done;
break;
}
case 2:
{
/* PS2 prompt. Save stack state to avoid corrupting command substitutions
* in case we're executing a PS2.get discipline function at parse time. */
int savestacktop = stktell(sh.stk);
void *savestackptr = stkfreeze(sh.stk,0);
cp = nv_getval(sh_scoped(PS2NOD));
if (cp = nv_getval(sh_scoped(PS2NOD)))
sfputr(sfstderr,cp,-1);
/* Restore the stack. (If nv_getval ran a PS2.get discipline, this may free the space cp points to.) */
stkset(sh.stk, savestackptr, savestacktop);
break;
}
case 3:
cp = nv_getval(sh_scoped(PS3NOD));
if (cp = nv_getval(sh_scoped(PS3NOD)))
sfputr(sfstderr,cp,-1);
break;
default:
goto done;
}
if(cp)
sfputr(sfstderr,cp,-1);
done:
if(*sh.prompt && (endprompt=(char*)sfreserve(sfstderr,0,0)))
*endprompt = 0;
sfset(sfstderr,sfflags&SFIO_READ|SFIO_SHARE|SFIO_PUBLIC,1);
Expand Down

0 comments on commit d2b0f82

Please sign in to comment.