[njs] Fixed integer-overflow in Date() constructor.

Dmitry Volyntsev xeioex at nginx.com
Mon Mar 2 11:51:47 UTC 2020


details:   https://hg.nginx.org/njs/rev/36208bd2362f
branches:  
changeset: 1343:36208bd2362f
user:      Dmitry Volyntsev <xeioex at nginx.com>
date:      Fri Feb 28 19:39:13 2020 +0300
description:
Fixed integer-overflow in Date() constructor.

Found by UndefinedBehaviorSanitizer.

diffstat:

 src/njs_date.c           |  17 +++++++++++------
 src/test/njs_unit_test.c |  18 ++++++++++++++++++
 2 files changed, 29 insertions(+), 6 deletions(-)

diffs (73 lines):

diff -r 3f094214cd64 -r 36208bd2362f src/njs_date.c
--- a/src/njs_date.c	Fri Feb 28 18:56:24 2020 +0300
+++ b/src/njs_date.c	Fri Feb 28 19:39:13 2020 +0300
@@ -118,14 +118,19 @@ njs_days_from_year(int64_t y)
 }
 
 
-njs_inline int64_t
+njs_inline double
 njs_make_day(int64_t yr, int64_t month, int64_t date)
 {
-    int64_t  i, ym, mn, md, days;
+    double   days;
+    int64_t  i, ym, mn, md;
 
     static const int month_days[] = { 31, 28, 31, 30, 31, 30,
                                       31, 31, 30, 31, 30, 31 };
 
+    if (yr < -271822 || yr > 275761) {
+        return NAN;
+    }
+
     mn = njs_mod(month, 12);
     ym = yr + (month - mn) / 12;
 
@@ -228,15 +233,15 @@ njs_year_from_days(int64_t *days)
 njs_inline double
 njs_make_date(int64_t tm[], njs_bool_t local)
 {
-    int64_t  days, time;
+    double  time, days;
 
     days = njs_make_day(tm[NJS_DATE_YR], tm[NJS_DATE_MON],
                         tm[NJS_DATE_DAY]);
 
-    time = ((tm[NJS_DATE_HR] * 60 + tm[NJS_DATE_MIN]) * 60
-            + tm[NJS_DATE_SEC]) * 1000 + tm[NJS_DATE_MSEC];
+    time = ((tm[NJS_DATE_HR] * 60.0 + tm[NJS_DATE_MIN]) * 60.0
+            + tm[NJS_DATE_SEC]) * 1000.0 + tm[NJS_DATE_MSEC];
 
-    time += days * 86400000;
+    time += days * 86400000.0;
 
     if (local) {
         time += njs_tz_offset(time) * 60000;
diff -r 3f094214cd64 -r 36208bd2362f src/test/njs_unit_test.c
--- a/src/test/njs_unit_test.c	Fri Feb 28 18:56:24 2020 +0300
+++ b/src/test/njs_unit_test.c	Fri Feb 28 19:39:13 2020 +0300
@@ -13270,6 +13270,24 @@ static njs_unit_test_t  njs_test[] =
     { njs_str("new Date(8.65e15)"),
       njs_str("Invalid Date") },
 
+    { njs_str("var d = new Date(1308895200000); new Date(d.getTime(), d.getTime())"),
+      njs_str("Invalid Date") },
+
+    { njs_str("new Date(275760, 1, 2**61)"),
+      njs_str("Invalid Date") },
+
+    { njs_str("new Date(275760, 1, 1, 2**61)"),
+      njs_str("Invalid Date") },
+
+    { njs_str("new Date(275760, 1, 1, 1, 2**61)"),
+      njs_str("Invalid Date") },
+
+    { njs_str("new Date(275760, 1, 1, 1, 1, 2**61)"),
+      njs_str("Invalid Date") },
+
+    { njs_str("new Date(275760, 1, 1, 1, 1, 1, 2**61)"),
+      njs_str("Invalid Date") },
+
     { njs_str("njs.dump([new Date(8.65e15)])"),
       njs_str("[Invalid Date]") },
 


More information about the nginx-devel mailing list