od: Fix buffer overflow if -N flag is larger than BUFSIZ

Previously, if max was specified, od will call read with that size,
potentially overflowing buf with data read from the file.
This commit is contained in:
Michael Forney 2016-12-06 02:16:54 -08:00 committed by Laslo Hunhold
parent 9e594a986e
commit 5e4e6aeb3e

18
od.c
View File

@ -129,23 +129,25 @@ od(FILE *fp, char *fname, int last)
{ {
static unsigned char *line; static unsigned char *line;
static size_t lineoff; static size_t lineoff;
size_t i;
unsigned char buf[BUFSIZ];
static off_t addr; static off_t addr;
size_t buflen; unsigned char buf[BUFSIZ];
size_t i, n, size = sizeof(buf);
while (skip - addr > 0) { while (skip - addr > 0) {
buflen = fread(buf, 1, MIN(skip - addr, BUFSIZ), fp); n = fread(buf, 1, MIN(skip - addr, sizeof(buf)), fp);
addr += buflen; addr += n;
if (feof(fp) || ferror(fp)) if (feof(fp) || ferror(fp))
return; return;
} }
if (!line) if (!line)
line = emalloc(linelen); line = emalloc(linelen);
while ((buflen = fread(buf, 1, max >= 0 ? for (;;) {
max - (addr - skip) : BUFSIZ, fp))) { if (max >= 0)
for (i = 0; i < buflen; i++, addr++) { size = MIN(max - (addr - skip), size);
if (!(n = fread(buf, 1, size, fp)))
break;
for (i = 0; i < n; i++, addr++) {
line[lineoff++] = buf[i]; line[lineoff++] = buf[i];
if (lineoff == linelen) { if (lineoff == linelen) {
printline(line, lineoff, addr - lineoff + 1); printline(line, lineoff, addr - lineoff + 1);