From cf9c3eb36e5cb8a2da6954a22ac214a6d355fb03 Mon Sep 17 00:00:00 2001 From: Behdad Esfahbod Date: Sat, 16 May 2026 13:06:40 +0100 Subject: [PATCH] [vector] Fix heap buffer overflow in append_base64 / append_len When the sum old_len + out_len (or old_len + l) exceeded INT_MAX, the (int) cast turned it negative. resize_full() treated negative size as zero, alloc(0) succeeded, and the subsequent write loop overflowed the buffer. Fix both layers: - resize_full(): reject negative size_ (return false) instead of silently treating it as zero. This is defense-in-depth for every caller that casts unsigned to int. - append_len() and append_base64(): use hb_unsigned_add_overflows() to detect unsigned wraparound before the cast. This catches the case where old_len + new_bytes > UINT_MAX wraps to a small positive value that would pass the negative check. Assisted-by: Claude --- src/hb-vector-buf.hh | 8 ++++++-- src/hb-vector.hh | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/hb-vector-buf.hh b/src/hb-vector-buf.hh index d09f907de..543cbddd7 100644 --- a/src/hb-vector-buf.hh +++ b/src/hb-vector-buf.hh @@ -46,7 +46,9 @@ struct hb_vector_buf_t : hb_vector_t bool append_len (const char *s, unsigned l) { unsigned old_len = length; - if (unlikely (!resize_dirty ((int) (old_len + l)))) + unsigned new_len; + if (unlikely (hb_unsigned_add_overflows (old_len, l, &new_len) || + !resize_dirty ((int) new_len))) return false; hb_memcpy (arrayZ + old_len, s, l); return true; @@ -155,7 +157,9 @@ struct hb_vector_buf_t : hb_vector_t { unsigned out_len = ((len + 2) / 3) * 4; unsigned old_len = length; - if (unlikely (!resize_dirty ((int) (old_len + out_len)))) + unsigned new_len; + if (unlikely (hb_unsigned_add_overflows (old_len, out_len, &new_len) || + !resize_dirty ((int) new_len))) return false; char *dst = arrayZ + old_len; diff --git a/src/hb-vector.hh b/src/hb-vector.hh index e831c72b4..7f0b454d2 100644 --- a/src/hb-vector.hh +++ b/src/hb-vector.hh @@ -635,7 +635,9 @@ struct hb_vector_t HB_ALWAYS_INLINE_VECTOR_ALLOCS bool resize_full (int size_, bool initialize, bool exact) { - unsigned int size = size_ < 0 ? 0u : (unsigned int) size_; + if (unlikely (size_ < 0)) + return false; + unsigned int size = (unsigned int) size_; if (!alloc (size, exact)) return false;