[njs] Fixed njs_string_slice().

Alexander Borisov alexander.borisov at nginx.com
Fri Jul 19 15:52:55 UTC 2019


details:   https://hg.nginx.org/njs/rev/2fdad3cbbd74
branches:  
changeset: 1059:2fdad3cbbd74
user:      Dmitry Volyntsev <xeioex at nginx.com>
date:      Thu Jul 18 21:12:25 2019 +0300
description:
Fixed njs_string_slice().

Previously, njs_string_slice() when slice->start == slice->string_length
may call njs_string_offset() with invalid index.

This might result in invalid memory access in njs_string_offset()
for native functions which use njs_string_slice():

    String.prototype.substring()

diffstat:

 njs/njs_string.c         |  31 +++++++++++++++++++------------
 njs/test/njs_unit_test.c |   3 +++
 2 files changed, 22 insertions(+), 12 deletions(-)

diffs (55 lines):

diff -r 57cf608a29b5 -r 2fdad3cbbd74 njs/njs_string.c
--- a/njs/njs_string.c	Thu Jul 18 16:18:19 2019 +0300
+++ b/njs/njs_string.c	Thu Jul 18 21:12:25 2019 +0300
@@ -1351,19 +1351,26 @@ njs_string_slice_string_prop(njs_string_
     } else {
         /* UTF-8 string. */
         end = start + string->size;
-        start = njs_string_offset(start, end, slice->start);
-
-        /* Evaluate size of the slice in bytes and ajdust length. */
-        p = start;
-        n = length;
-
-        while (n != 0 && p < end) {
-            p = nxt_utf8_next(p, end);
-            n--;
+
+        if (slice->start < slice->string_length) {
+            start = njs_string_offset(start, end, slice->start);
+
+            /* Evaluate size of the slice in bytes and adjust length. */
+            p = start;
+            n = length;
+
+            while (n != 0 && p < end) {
+                p = nxt_utf8_next(p, end);
+                n--;
+            }
+
+            size = p - start;
+            length -= n;
+
+        } else {
+            length = 0;
+            size = 0;
         }
-
-        size = p - start;
-        length -= n;
     }
 
     dst->start = (u_char *) start;
diff -r 57cf608a29b5 -r 2fdad3cbbd74 njs/test/njs_unit_test.c
--- a/njs/test/njs_unit_test.c	Thu Jul 18 16:18:19 2019 +0300
+++ b/njs/test/njs_unit_test.c	Thu Jul 18 21:12:25 2019 +0300
@@ -4825,6 +4825,9 @@ static njs_unit_test_t  njs_test[] =
     { nxt_string("'α'.repeat(32).substring(32)"),
       nxt_string("") },
 
+    { nxt_string("'α'.repeat(32).substring(32,32)"),
+      nxt_string("") },
+
     { nxt_string("'abcdefghijklmno'.slice(NaN, 5)"),
       nxt_string("abcde") },
 


More information about the nginx-devel mailing list