diff --git a/src/libwolfboot.c b/src/libwolfboot.c index 9f652202..072f6033 100644 --- a/src/libwolfboot.c +++ b/src/libwolfboot.c @@ -342,8 +342,15 @@ uint16_t wolfBoot_find_header(uint8_t *haystack, uint16_t type, uint8_t **ptr) { uint8_t *p = haystack; uint16_t len; - while (((p[0] != 0) || (p[1] != 0)) && ((p - haystack) < IMAGE_HEADER_SIZE)) { + const uint8_t *max_p = (haystack - IMAGE_HEADER_OFFSET) + IMAGE_HEADER_SIZE; + + while ((p + 4) < max_p) { + if ((p[0] == 0) && (p[1] == 0)) { + /* Explicit end of options reached */ + break; + } if (*p == HDR_PADDING) { + /* Padding byte (skip one position) */ p++; continue; } @@ -353,6 +360,10 @@ uint16_t wolfBoot_find_header(uint8_t *haystack, uint16_t type, uint8_t **ptr) continue; } len = p[2] | (p[3] << 8); + if (p + 4 + len > max_p) { + /* This field is too large and would overflow the image header */ + break; + } if ((p[0] | (p[1] << 8)) == type) { *ptr = (p + 4); return len;