[njs] Fixed memory over-read in njs_utf8_prev() and njs_utf8_next().

Vadim Zhestikov v.zhestikov at f5.com
Thu Nov 30 04:48:02 UTC 2023


details:   https://hg.nginx.org/njs/rev/a3364db5fdef
branches:  
changeset: 2243:a3364db5fdef
user:      Vadim Zhestikov <v.zhestikov at f5.com>
date:      Wed Nov 29 20:46:32 2023 -0800
description:
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.

diffstat:

 src/njs_iterator.c |   2 +-
 src/njs_string.c   |   4 ++--
 src/njs_utf8.h     |  11 ++++++++++-
 3 files changed, 13 insertions(+), 4 deletions(-)

diffs (66 lines):

diff -r f64d1f9f19e5 -r a3364db5fdef src/njs_iterator.c
--- a/src/njs_iterator.c	Wed Nov 29 18:43:45 2023 -0800
+++ b/src/njs_iterator.c	Wed Nov 29 20:46:32 2023 -0800
@@ -542,7 +542,7 @@ njs_object_iterate_reverse(njs_vm_t *vm,
             }
 
             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 -r f64d1f9f19e5 -r a3364db5fdef src/njs_string.c
--- a/src/njs_string.c	Wed Nov 29 18:43:45 2023 -0800
+++ b/src/njs_string.c	Wed Nov 29 20:46:32 2023 -0800
@@ -1884,7 +1884,7 @@ njs_string_prototype_last_index_of(njs_v
 
         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
                     break;
                 }
 
-                prev = njs_utf8_prev(prev);
+                prev = njs_utf8_prev(prev, start);
                 p = prev;
                 cp = njs_utf8_decode(&ctx, &p, end);
 
diff -r f64d1f9f19e5 -r a3364db5fdef src/njs_utf8.h
--- a/src/njs_utf8.h	Wed Nov 29 18:43:45 2023 -0800
+++ b/src/njs_utf8.h	Wed Nov 29 20:46:32 2023 -0800
@@ -53,6 +53,10 @@ njs_utf8_next(const u_char *p, const u_c
 
     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_c
 
 
 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);


More information about the nginx-devel mailing list