expand_buf: fix conditional for when we need to preserve existing data

It is possible for the buffer offset to be zero when the length is
non-zero.  The proper value to use is the same as is used for the
memcpy/memmove size.  Fixes buffer corruption caused by a very long
command line that usually results in a dropped connection.
This commit is contained in:
Todd C. Miller
2021-09-28 13:24:21 -06:00
parent 476f00b82f
commit dea7e6aefd

View File

@@ -58,18 +58,20 @@ expand_buf(struct connection_buffer *buf, unsigned int needed)
if (buf->size < needed) { if (buf->size < needed) {
/* Expand buffer. */ /* Expand buffer. */
needed = sudo_pow2_roundup(needed); needed = sudo_pow2_roundup(needed);
sudo_debug_printf(SUDO_DEBUG_INFO|SUDO_DEBUG_LINENO,
"expanding buffer from %u to %u", buf->size, needed);
if ((newdata = malloc(needed)) == NULL) { if ((newdata = malloc(needed)) == NULL) {
sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory")); sudo_warnx(U_("%s: %s"), __func__, U_("unable to allocate memory"));
debug_return_bool(false); debug_return_bool(false);
} }
if (buf->off > 0) if (buf->len - buf->off > 0)
memcpy(newdata, buf->data + buf->off, buf->len - buf->off); memcpy(newdata, buf->data + buf->off, buf->len - buf->off);
free(buf->data); free(buf->data);
buf->data = newdata; buf->data = newdata;
buf->size = needed; buf->size = needed;
} else { } else {
/* Just reset existing buffer. */ /* Just reset existing buffer. */
if (buf->off > 0) { if (buf->len - buf->off > 0) {
memmove(buf->data, buf->data + buf->off, memmove(buf->data, buf->data + buf->off,
buf->len - buf->off); buf->len - buf->off);
} }