diff --git a/lib/util/event_select.c b/lib/util/event_select.c index c839f312cd..4906a933b7 100644 --- a/lib/util/event_select.c +++ b/lib/util/event_select.c @@ -81,33 +81,38 @@ sudo_ev_add_impl(struct sudo_event_base *base, struct sudo_event *ev) const size_t new_bytes = (size_t)(n - o) * sizeof(fd_mask); fd_set *rfds_in, *wfds_in, *rfds_out, *wfds_out; + /* + * Store each new pointer in the base as it is allocated. + * reallocarray() frees the old pointer on success, so leaving + * it in the base would mean a use-after-free or double free + * if a later allocation fails. + */ rfds_in = reallocarray(base->readfds_in, (size_t)n, sizeof(fd_mask)); + if (rfds_in != NULL) + base->readfds_in = rfds_in; wfds_in = reallocarray(base->writefds_in, (size_t)n, sizeof(fd_mask)); + if (wfds_in != NULL) + base->writefds_in = wfds_in; rfds_out = reallocarray(base->readfds_out, (size_t)n, sizeof(fd_mask)); + if (rfds_out != NULL) + base->readfds_out = rfds_out; wfds_out = reallocarray(base->writefds_out, (size_t)n, sizeof(fd_mask)); + if (wfds_out != NULL) + base->writefds_out = wfds_out; if (rfds_in == NULL || wfds_in == NULL || rfds_out == NULL || wfds_out == NULL) { sudo_debug_printf(SUDO_DEBUG_ERROR|SUDO_DEBUG_LINENO, "%s: unable to reallocarray(%d, %zu)", __func__, n, sizeof(fd_mask)); - free(rfds_in); - free(wfds_in); - free(rfds_out); - free(wfds_out); debug_return_int(-1); } /* Clear newly allocated space. */ - memset((char *)rfds_in + used_bytes, 0, new_bytes); - memset((char *)wfds_in + used_bytes, 0, new_bytes); - memset((char *)rfds_out + used_bytes, 0, new_bytes); - memset((char *)wfds_out + used_bytes, 0, new_bytes); - - /* Update base. */ - base->readfds_in = rfds_in; - base->writefds_in = wfds_in; - base->readfds_out = rfds_out; - base->writefds_out = wfds_out; + memset((char *)base->readfds_in + used_bytes, 0, new_bytes); + memset((char *)base->writefds_in + used_bytes, 0, new_bytes); + memset((char *)base->readfds_out + used_bytes, 0, new_bytes); + memset((char *)base->writefds_out + used_bytes, 0, new_bytes); + base->maxfd = (n * NFDBITS) - 1; }