diff -Nrup a/telnet/telnetd/utility.c b/telnet/telnetd/utility.c --- a/telnet/telnetd/utility.c 2009-11-05 21:15:06.000000000 +0100 +++ b/telnet/telnetd/utility.c 2020-04-08 10:48:11.197782686 +0200 @@ -213,32 +213,38 @@ ptyflush() * character. */ static char * -nextitem(current) - char *current; +nextitem(char *current, const char *endp) { + if (current >= endp) { + return NULL; + } if ((*current&0xff) != IAC) { return current+1; } + if (current+1 >= endp) { + return NULL; + } switch (*(current+1)&0xff) { case DO: case DONT: case WILL: case WONT: - return current+3; + return current+3 <= endp ? current+3 : NULL; case SB: /* loop forever looking for the SE */ { register char *look = current+2; - for (;;) { + while (look < endp) { if ((*look++&0xff) == IAC) { - if ((*look++&0xff) == SE) { + if (look < endp && (*look++&0xff) == SE) { return look; } } } + return NULL; } default: - return current+2; + return current+2 <= endp ? current+2 : NULL; } } /* end of nextitem */ @@ -265,7 +271,7 @@ netclear() register char *thisitem, *next; char *good; #define wewant(p) ((nfrontp > p) && ((*p&0xff) == IAC) && \ - ((*(p+1)&0xff) != EC) && ((*(p+1)&0xff) != EL)) + (nfrontp > p+1 && (((*(p+1)&0xff) != EC) && ((*(p+1)&0xff) != EL)))) #ifdef ENCRYPTION thisitem = nclearto > netobuf ? nclearto : netobuf; @@ -273,7 +279,7 @@ netclear() thisitem = netobuf; #endif /* ENCRYPTION */ - while ((next = nextitem(thisitem)) <= nbackp) { + while ((next = nextitem(thisitem, nbackp)) != NULL && next <= nbackp) { thisitem = next; } @@ -285,20 +291,23 @@ netclear() good = netobuf; /* where the good bytes go */ #endif /* ENCRYPTION */ - while (nfrontp > thisitem) { + while (thisitem != NULL && nfrontp > thisitem) { if (wewant(thisitem)) { unsigned int length; next = thisitem; do { - next = nextitem(next); - } while (wewant(next) && (nfrontp > next)); + next = nextitem(next, nfrontp); + } while (next != NULL && wewant(next) && (nfrontp > next)); + if (next == NULL) { + next = nfrontp; + } length = next-thisitem; memcpy(good, thisitem, length); good += length; thisitem = next; } else { - thisitem = nextitem(thisitem); + thisitem = nextitem(thisitem, nfrontp); } }