CVE-2022-35940: Integer Overflow or Wraparound (CWE-190)
value: TensorFlow is an open source platform for machine learning. The `RaggedRangOp` function takes an argument `limits` that is eventually used to construct a `TensorShape` as an `int64`. If `limits` is a very large float, it can overflow when converted to an `int64`. This triggers an `InvalidArgument` but also throws an abort signal that crashes the program. We have patched the issue in GitHub commit 37cefa91bee4eace55715eeef43720b958a01192. The fix will be included in TensorFlow 2.10.0. We will also cherrypick this commit on TensorFlow 2.9.1, TensorFlow 2.8.1, and TensorFlow 2.7.2, as these are also affected and still in supported range. There are no known workarounds for this issue.
CWE description: The product performs a calculation that can
         produce an integer overflow or wraparound when the logic
         assumes that the resulting value will always be larger than
         the original value. This occurs when an integer value is
         incremented to a value that is too large to store in the
         associated representation. When this occurs, the value may
         become a very small or negative number.
CVSS v3 base score: 7.5
Published: 2022-09-16T20:15Z
Repository: https://github.com/tensorflow/tensorflow
Language: C++
Files changed: tensorflow/core/kernels/ragged_range_op.cc, tensorflow/core/kernels/ragged_range_op_test.cc, tensorflow/python/ops/ragged/ragged_range_op_test.py
Commit date: 2022-07-18 17:08:01 -0700
Commit message: [security] Fix int overflow in RaggedRangeOp.

PiperOrigin-RevId: 461749624

Diff: diff --git a/tensorflow/core/kernels/ragged_range_op.cc b/tensorflow/core/kernels/ragged_range_op.cc
index 066e5d638bbc4..469ef06b4b3bb 100644
--- a/tensorflow/core/kernels/ragged_range_op.cc
+++ b/tensorflow/core/kernels/ragged_range_op.cc
@@ -10,10 +10,11 @@ Unless required by applicable law or agreed to in writing, software
 distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 ==============================================================================*/
+#include <cstdint>
 #include <limits>
 #include <memory>
 #include <string>
 #include <vector>
 
@@ -76,12 +77,29 @@ class RaggedRangeOp : public OpKernel {
     for (int row = 0; row < nrows; ++row) {
       T start = broadcast_starts ? starts(0) : starts(row);
       T limit = broadcast_limits ? limits(0) : limits(row);
       T delta = broadcast_deltas ? deltas(0) : deltas(row);
       OP_REQUIRES(context, delta != 0, InvalidArgument("Requires delta != 0"));
-      rt_nested_splits(row + 1) =
-          rt_nested_splits(row) + RangeSize(start, limit, delta);
+      int64_t size;  // The number of elements in the specified range.
+      if (((delta > 0) && (limit < start)) ||
+          ((delta < 0) && (limit > start))) {
+        size = 0;
+      } else if (std::is_integral<T>::value) {
+        // The following is copied from tensorflow::RangeOp::Compute().
+        size = Eigen::divup(Eigen::numext::abs(limit - start),
+                            Eigen::numext::abs(delta));
+      } else {
+        // The following is copied from tensorflow::RangeOp::Compute().
+        auto size_auto =
+            Eigen::numext::ceil(Eigen::numext::abs((limit - start) / delta));
+        OP_REQUIRES(
+            context, size_auto <= std::numeric_limits<int64_t>::max(),
+            errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
+                                    std::numeric_limits<int64_t>::max()));
+        size = static_cast<int64_t>(size_auto);
+      }
+      rt_nested_splits(row + 1) = rt_nested_splits(row) + size;
     }
     SPLITS_TYPE nvals = rt_nested_splits(nrows);
 
     // Construct the rt_dense_values tensor.
     Tensor* rt_dense_values_out = nullptr;
@@ -97,23 +115,10 @@ class RaggedRangeOp : public OpKernel {
         rt_dense_values(value_index++) = T(value);
         value += delta;
       }
     }
   }
-
- private:
-  // Returns the number of elements in the specified range.
-  SPLITS_TYPE RangeSize(T start, T limit, T delta) {
-    if (((delta > 0) && (limit < start)) || ((delta < 0) && (limit > start))) {
-      return 0;
-    }
-    // The following is copied from tensorflow::RangeOp::Compute().
-    return (std::is_integral<T>::value
-                ? ((std::abs(limit - start) + std::abs(delta) - 1) /
-                   std::abs(delta))
-                : std::ceil(std::abs((limit - start) / delta)));
-  }
 };
 
 #define REGISTER_CPU_KERNEL(TYPE)                                  \
   REGISTER_KERNEL_BUILDER(Name("RaggedRange")                      \
                               .Device(DEVICE_CPU)                  \
diff --git a/tensorflow/core/kernels/ragged_range_op_test.cc b/tensorflow/core/kernels/ragged_range_op_test.cc
index 94aaedde3420e..fc3b302eeb7e3 100644
--- a/tensorflow/core/kernels/ragged_range_op_test.cc
+++ b/tensorflow/core/kernels/ragged_range_op_test.cc
@@ -11,10 +11,11 @@ distributed under the License is distributed on an "AS IS" BASIS,
 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 See the License for the specific language governing permissions and
 limitations under the License.
 ==============================================================================*/
 
+#include <gtest/gtest.h>
 #include "tensorflow/core/framework/fake_input.h"
 #include "tensorflow/core/framework/node_def_builder.h"
 #include "tensorflow/core/framework/shape_inference.h"
 #include "tensorflow/core/framework/shape_inference_testutil.h"
 #include "tensorflow/core/framework/tensor.h"
@@ -75,10 +76,21 @@ TEST_F(RaggedRangeOpTest, FloatValues) {
   test::ExpectTensorNear<float>(
       *GetOutput(kValuesOutput),
       test::AsTensor<float>({0, 2, 4, 6, 5, 6, 5, 4, 3, 2}), 0.1);
 }
 
+TEST_F(RaggedRangeOpTest, RangeSizeOverflow) {
+  BuildRaggedRangeGraph<float>();
+  AddInputFromArray<float>(TensorShape({2}), {1.1, 0.1});    // starts
+  AddInputFromArray<float>(TensorShape({2}), {10.0, 1e10});  // limits
+  AddInputFromArray<float>(TensorShape({2}), {1, 1e-10});    // deltas
+
+  EXPECT_EQ(absl::StrCat("Requires ((limit - start) / delta) <= ",
+                         std::numeric_limits<int64_t>::max()),
+            RunOpKernel().error_message());
+}
+
 TEST_F(RaggedRangeOpTest, BroadcastDeltas) {
   BuildRaggedRangeGraph<int>();
   AddInputFromArray<int>(TensorShape({3}), {0, 5, 8});  // starts
   AddInputFromArray<int>(TensorShape({3}), {8, 7, 8});  // limits
   AddInputFromArray<int>(TensorShape({}), {1});         // deltas
diff --git a/tensorflow/python/ops/ragged/ragged_range_op_test.py b/tensorflow/python/ops/ragged/ragged_range_op_test.py
index 8465fb25997b8..aaf48bf978378 100644
--- a/tensorflow/python/ops/ragged/ragged_range_op_test.py
+++ b/tensorflow/python/ops/ragged/ragged_range_op_test.py
@@ -82,12 +82,11 @@ class RaggedRangeOpTest(test_util.TensorFlowTestCase):
         [list(range(0, 4, 3)),
          list(range(3, 4, 3)),
          list(range(5, 15, 3))])
 
     # Broadcast all arguments.
-    self.assertAllEqual(
-        ragged_math_ops.range(0, 5, 1), [list(range(0, 5, 1))])
+    self.assertAllEqual(ragged_math_ops.range(0, 5, 1), [list(range(0, 5, 1))])
 
   def testEmptyRanges(self):
     rt1 = ragged_math_ops.range([0, 5, 3], [0, 3, 5])
     rt2 = ragged_math_ops.range([0, 5, 5], [0, 3, 5], -1)
     self.assertAllEqual(rt1, [[], [], [3, 4]])
@@ -106,10 +105,14 @@ class RaggedRangeOpTest(test_util.TensorFlowTestCase):
   def testKernelErrors(self):
     with self.assertRaisesRegex(errors.InvalidArgumentError,
                                 r'Requires delta != 0'):
       self.evaluate(ragged_math_ops.range(0, 0, 0))
 
+    with self.assertRaisesRegex(errors.InvalidArgumentError,
+                                r'Requires \(\(limit - start\) / delta\) <='):
+      self.evaluate(ragged_math_ops.range(0.1, 1e10, 1e-10))
+
   def testShape(self):
     self.assertAllEqual(
         ragged_math_ops.range(0, 0, 1).shape.as_list(), [1, None])
     self.assertAllEqual(
         ragged_math_ops.range([1, 2, 3]).shape.as_list(), [3, None])

Vulnerable code:       rt_nested_splits(row + 1) =
          rt_nested_splits(row) + RangeSize(start, limit, delta);

 private:
  // Returns the number of elements in the specified range.
  SPLITS_TYPE RangeSize(T start, T limit, T delta) {
    if (((delta > 0) && (limit < start)) || ((delta < 0) && (limit > start))) {
      return 0;
    }
    // The following is copied from tensorflow::RangeOp::Compute().
    return (std::is_integral<T>::value
                ? ((std::abs(limit - start) + std::abs(delta) - 1) /
                   std::abs(delta))
                : std::ceil(std::abs((limit - start) / delta)));
  }
    self.assertAllEqual(
        ragged_math_ops.range(0, 5, 1), [list(range(0, 5, 1))])
Fixed code: #include <cstdint>
      int64_t size;  // The number of elements in the specified range.
      if (((delta > 0) && (limit < start)) ||
          ((delta < 0) && (limit > start))) {
        size = 0;
      } else if (std::is_integral<T>::value) {
        // The following is copied from tensorflow::RangeOp::Compute().
        size = Eigen::divup(Eigen::numext::abs(limit - start),
                            Eigen::numext::abs(delta));
      } else {
        // The following is copied from tensorflow::RangeOp::Compute().
        auto size_auto =
            Eigen::numext::ceil(Eigen::numext::abs((limit - start) / delta));
        OP_REQUIRES(
            context, size_auto <= std::numeric_limits<int64_t>::max(),
            errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
                                    std::numeric_limits<int64_t>::max()));
        size = static_cast<int64_t>(size_auto);
      }
      rt_nested_splits(row + 1) = rt_nested_splits(row) + size;
#include <gtest/gtest.h>
TEST_F(RaggedRangeOpTest, RangeSizeOverflow) {
  BuildRaggedRangeGraph<float>();
  AddInputFromArray<float>(TensorShape({2}), {1.1, 0.1});    // starts
  AddInputFromArray<float>(TensorShape({2}), {10.0, 1e10});  // limits
  AddInputFromArray<float>(TensorShape({2}), {1, 1e-10});    // deltas

  EXPECT_EQ(absl::StrCat("Requires ((limit - start) / delta) <= ",
                         std::numeric_limits<int64_t>::max()),
            RunOpKernel().error_message());
}

    self.assertAllEqual(ragged_math_ops.range(0, 5, 1), [list(range(0, 5, 1))])
    with self.assertRaisesRegex(errors.InvalidArgumentError,
                                r'Requires \(\(limit - start\) / delta\) <='):
      self.evaluate(ragged_math_ops.range(0.1, 1e10, 1e-10))