From 82da1827730cf94100d6dd3ca9372431bfd649fb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Kha=C3=AFs=20COLIN?= Date: Wed, 9 Apr 2025 17:25:48 +0200 Subject: [PATCH] fix: potential buffer overflow caused by missing terminating null byte in t_buffer This only occurs in specific circumstances where the number of bytes to be added to a t_buffer via the ft_buffer_push_buf function is exactly equal to the number of free bytes in the current underlying buffer. This does not occur if the number of bytes to add to the buffer is smaller than that, since we allocate new space using ft_calloc. In these circumstances, since no terminating null byte is added, other code may read past the end of the buffer, causing a buffer overflow. --- src/buffer/buffer.c | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/src/buffer/buffer.c b/src/buffer/buffer.c index ce91f2a..391476f 100644 --- a/src/buffer/buffer.c +++ b/src/buffer/buffer.c @@ -6,7 +6,7 @@ /* By: kcolin +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2024/12/12 12:39:58 by kcolin #+# #+# */ -/* Updated: 2025/03/10 18:45:34 by khais ### ########.fr */ +/* Updated: 2025/04/09 17:26:24 by khais ### ########.fr */ /* */ /* ************************************************************************** */ @@ -84,6 +84,8 @@ t_buffer *ft_buffer_pushchar(t_buffer *buffer, char c) /* ** push buf to the end of buffer, growing buffer if needed. ** +** also adds an additional null byte to terminate the buffer. +** ** the number of bytes to copy to buffer is n. ** returns buffer. ** in case of error, all memory is freed and null is returned. @@ -92,7 +94,7 @@ t_buffer *ft_buffer_push_buf(t_buffer *buffer, char *buf, size_t n) { if (buffer == NULL) return (NULL); - while (buffer->length + n > buffer->capacity) + while (buffer->length + n + 1 > buffer->capacity) { buffer = ft_buffer_grow(buffer); if (buffer == NULL) @@ -100,5 +102,6 @@ t_buffer *ft_buffer_push_buf(t_buffer *buffer, char *buf, size_t n) } ft_memcpy(buffer->buffer + buffer->length, buf, n); buffer->length += n; + buffer->buffer[buffer->length] = '\0'; return (buffer); }