From 0313f3a0f2fcf649943d2683c782040cc2c7810b Mon Sep 17 00:00:00 2001 From: Vadim Zhestikov Date: Wed, 29 Nov 2023 20:46:32 -0800 Subject: [PATCH] Fixed memory over-read in njs_utf8_prev() and njs_utf8_next(). Previously, njs_utf8_next() might over-read up to 1 byte beyond the string memory. Whereas njs_utf8_prev() might over-read unlimited number of bytes before the string. --- src/njs_iterator.c | 2 +- src/njs_string.c | 4 ++-- src/njs_utf8.h | 11 ++++++++++- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/src/njs_iterator.c b/src/njs_iterator.c index 2f8b757a..6159ed02 100644 --- a/src/njs_iterator.c +++ b/src/njs_iterator.c @@ -542,7 +542,7 @@ njs_object_iterate_reverse(njs_vm_t *vm, njs_iterator_args_t *args, } while (i-- > to) { - pos = njs_utf8_prev(p); + pos = njs_utf8_prev(p, string_prop.start); /* This cannot fail. */ (void) njs_string_new(vm, &character, pos, p - pos , 1); diff --git a/src/njs_string.c b/src/njs_string.c index ed07509f..f783f455 100644 --- a/src/njs_string.c +++ b/src/njs_string.c @@ -1884,7 +1884,7 @@ njs_string_prototype_last_index_of(njs_vm_t *vm, njs_value_t *args, p = njs_string_utf8_offset(string.start, end, index); - for (; p >= string.start; p = njs_utf8_prev(p)) { + for (; p >= string.start; p = njs_utf8_prev(p, string.start)) { if ((p + s.size) <= end && memcmp(p, s.start, s.size) == 0) { goto done; } @@ -2408,7 +2408,7 @@ njs_string_trim(const njs_value_t *value, njs_string_prop_t *string, break; } - prev = njs_utf8_prev(prev); + prev = njs_utf8_prev(prev, start); p = prev; cp = njs_utf8_decode(&ctx, &p, end); diff --git a/src/njs_utf8.h b/src/njs_utf8.h index 26c23dbb..ce4d8665 100644 --- a/src/njs_utf8.h +++ b/src/njs_utf8.h @@ -53,6 +53,10 @@ njs_utf8_next(const u_char *p, const u_char *end) if ((c & 0x80) != 0) { + if (njs_slow_path(p >= end)) { + return p; + } + do { c = *p; @@ -70,12 +74,17 @@ njs_utf8_next(const u_char *p, const u_char *end) njs_inline const u_char * -njs_utf8_prev(const u_char *p) +njs_utf8_prev(const u_char *p, const u_char *start) { u_char c; do { p--; + + if (njs_slow_path(p < start)) { + break; + } + c = *p; } while ((c & 0xC0) == 0x80); -- 2.47.3