Right now, if read() returns less than 127 bytes (the most likely case),
the end of the "string" buf will contain garbage from the stack, because
buf is always null-terminated at a fixed offset 127. This is especially
bad because the next operation is a strrchr().
Also, make sure that the whole /proc/PID/stat file is read, otherwise
its parsing may be unsafe (the strrchr() may point into user-controlled
data, comm). This should never happen with the current file format (comm
is very short), but be safe, just in case.
int tty;
int fd;
int i;
+ ssize_t len;
if (pid == my_pid || pid == 0)
return;
/* pid (cmd) state ppid pgrp session tty */
if (i == -1)
goto closure;
}
- if (read(fd, buf, 128) <= 0)
- goto closure;
- buf[127] = '\0';
+ len = read(fd, buf, sizeof(buf));
+ if (len <= 0 || (size_t)len >= sizeof(buf))
+ goto closure;
+ buf[len] = '\0';
tmp = strrchr(buf, ')');
*tmp++ = '\0';
i = 5;