[PATCH 4/6 v7] libsepol/cil: Add overflow checks and cil_reallocarray
James Carter <[email protected]>
| Newsgroups | org.kernel.vger.selinux |
|---|---|
| Message-ID | <[email protected]> |
The CIL stack implementation uses "stack->size *= 2" to grow the size of the stack without checking for overflow and calls cil_realloc() using a multiplcation that could overflow. Use __builtin_smul_overflow() to grow the stack size and exit with an error if there is an overflow. Add the function cil_reallocarray() that checks for overflow of the multiplication of the array member size with the number of members and exits with an error if there is an overflow. Acked-by: Stephen Smalley <[email protected]> Signed-off-by: James Carter <[email protected]> --- v7: No changes libsepol/cil/src/cil_mem.c | 12 ++++++++++++ libsepol/cil/src/cil_mem.h | 1 + libsepol/cil/src/cil_stack.c | 9 ++++++--- 3 files changed, 19 insertions(+), 3 deletions(-) diff --git a/libsepol/cil/src/cil_mem.c b/libsepol/cil/src/cil_mem.c index aeffdae2..4f75122a 100644 --- a/libsepol/cil/src/cil_mem.c +++ b/libsepol/cil/src/cil_mem.c @@ -74,6 +74,18 @@ void *cil_realloc(void *ptr, size_t size) return mem; } +void *cil_reallocarray(void *ptr, size_t nmemb, size_t size) +{ + size_t array_size; + + if (__builtin_mul_overflow(nmemb, size, &array_size)) { + cil_log(CIL_ERR, "Overflow\n"); + exit(1); + } + + return cil_realloc(ptr, array_size); +} + char *cil_strdup(const char *str) { char *mem = NULL; diff --git a/libsepol/cil/src/cil_mem.h b/libsepol/cil/src/cil_mem.h index 7ec316af..f3f40c46 100644 --- a/libsepol/cil/src/cil_mem.h +++ b/libsepol/cil/src/cil_mem.h @@ -34,6 +34,7 @@ void *cil_malloc(size_t size); void *cil_calloc(size_t num_elements, size_t element_size); void *cil_realloc(void *ptr, size_t size); +void *cil_reallocarray(void *ptr, size_t nmemb, size_t size); char *cil_strdup(const char *str); int cil_asprintf(char **strp, const char *fmt, ...); diff --git a/libsepol/cil/src/cil_stack.c b/libsepol/cil/src/cil_stack.c index d9c7b0c0..da2efa5f 100644 --- a/libsepol/cil/src/cil_stack.c +++ b/libsepol/cil/src/cil_stack.c @@ -77,9 +77,12 @@ void cil_stack_push(struct cil_stack *stack, enum cil_flavor flavor, void *data) stack->pos++; if (stack->pos == stack->size) { - stack->size *= 2; - stack->stack = cil_realloc(stack->stack, - sizeof(*stack->stack) * stack->size); + if (__builtin_smul_overflow(stack->size, 2, &stack->size)) { + cil_log(CIL_ERR, "Overflow\n"); + exit(1); + } + stack->stack = cil_reallocarray(stack->stack, stack->size, + sizeof(*stack->stack)); } stack->stack[stack->pos].flavor = flavor; -- 2.55.0