From fe580d272f14482e761c45e6178624b3cd4ce418 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Markus=20M=C3=A4kel=C3=A4?= Date: Thu, 17 Aug 2017 15:54:44 +0300 Subject: [PATCH] Fix possible out-of-bounds reads in modutil_count_statements The pointer manipulation in modutil_count_statements assumed that if a semicolon is found, it is not the last character in the buffer. It also assumed that the buffer contained at least one readable character. --- server/core/modutil.c | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/server/core/modutil.c b/server/core/modutil.c index b96a504cd..6c44660de 100644 --- a/server/core/modutil.c +++ b/server/core/modutil.c @@ -1018,28 +1018,33 @@ GWBUF* modutil_create_query(const char* query) */ int modutil_count_statements(GWBUF* buffer) { - char* ptr = ((char*)(buffer)->start + 5); + char* start = ((char*)(buffer)->start + 5); + char* ptr = start; char* end = ((char*)(buffer)->end); int num = 1; while (ptr < end && (ptr = strnchr_esc(ptr, ';', end - ptr))) { num++; - while (*ptr == ';') + while (ptr < end && *ptr == ';') { ptr++; } } ptr = end - 1; - while (isspace(*ptr)) - { - ptr--; - } - if (*ptr == ';') + if (ptr >= start && ptr < end) { - num--; + while (ptr > start && isspace(*ptr)) + { + ptr--; + } + + if (*ptr == ';') + { + num--; + } } return num;