CVE-2022-21740: Out-of-bounds Write (CWE-787)
value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseCountSparseOutput` is vulnerable to a heap overflow. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
CWE description: The product writes data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 8.8
Published: 2022-02-03T15:15Z
Repository: https://github.com/tensorflow/tensorflow
Language: C++
Files changed: tensorflow/core/kernels/count_ops.cc
Commit date: 2021-12-07 19:40:32 -0800
Commit message: Cleanup and remove duplicate validation in `SparseCount`.

We have valdiation that is duplicated, checking different conditions, in different formats and failing to capture all cases. This should fix all the previous bugs.

PiperOrigin-RevId: 414886981
Change-Id: Ibf0bba0beb057b76d505324bb9487565daf95f01

Diff: diff --git a/tensorflow/core/kernels/count_ops.cc b/tensorflow/core/kernels/count_ops.cc
index 5330c36361e5e..1f99e0783e26f 100644
--- a/tensorflow/core/kernels/count_ops.cc
+++ b/tensorflow/core/kernels/count_ops.cc
@@ -183,60 +183,54 @@ class SparseCount : public OpKernel {
 
     OP_REQUIRES(context, TensorShapeUtils::IsMatrix(indices.shape()),
                 errors::InvalidArgument(
                     "Input indices must be a 2-dimensional tensor. Got: ",
                     indices.shape().DebugString()));
+    OP_REQUIRES(context, TensorShapeUtils::IsVector(values.shape()),
+                errors::InvalidArgument("Input values must be a vector. Got: ",
+                                        values.shape().DebugString()));
+    OP_REQUIRES(context, TensorShapeUtils::IsVector(shape.shape()),
+                errors::InvalidArgument("Input shape must be a vector. Got: ",
+                                        shape.shape().DebugString()));
+    OP_REQUIRES(context,
+                values.shape().dim_size(0) == indices.shape().dim_size(0),
+                errors::InvalidArgument(
+                    "Number of values must match first dimension of indices.",
+                    "Got ", values.shape().dim_size(0),
+                    " values, indices shape: ", indices.shape().DebugString()));
+    OP_REQUIRES(
+        context, shape.shape().dim_size(0) == indices.shape().dim_size(1),
+        errors::InvalidArgument(
+            "Number of dimensions must match second dimension of indices.",
+            "Got ", shape.shape().dim_size(0),
+            " dimensions, indices shape: ", indices.shape().DebugString()));
+    OP_REQUIRES(context, shape.NumElements() > 0,
+                errors::InvalidArgument(
+                    "The shape argument requires at least one element."));
 
     if (use_weights) {
       OP_REQUIRES(
           context, weights.shape() == values.shape(),
           errors::InvalidArgument(
               "Weights and values must have the same shape. Weight shape: ",
               weights.shape().DebugString(),
               "; values shape: ", values.shape().DebugString()));
     }
 
-    OP_REQUIRES(context, shape.NumElements() != 0,
-                errors::InvalidArgument(
-                    "The shape argument requires at least one element."));
-
     bool is_1d = shape.NumElements() == 1;
     auto shape_vector = shape.flat<int64_t>();
     int num_batches = is_1d ? 1 : shape_vector(0);
     int num_values = values.NumElements();
 
-    for (int b = 0; b < shape_vector.size(); b++) {
-      OP_REQUIRES(context, shape_vector(b) >= 0,
-                  errors::InvalidArgument(
-                      "Elements in dense_shape must be >= 0. Instead got:",
-                      shape.DebugString()));
-    }
-
-    OP_REQUIRES(context, num_values == indices.shape().dim_size(0),
-                errors::InvalidArgument(
-                    "Number of values must match first dimension of indices.",
-                    "Got ", num_values,
-                    " values, indices shape: ", indices.shape().DebugString()));
-
     const auto indices_values = indices.matrix<int64_t>();
     const auto values_values = values.flat<T>();
     const auto weight_values = weights.flat<W>();
 
     auto per_batch_counts = BatchedMap<W>(num_batches);
 
     T max_value = 0;
 
-    OP_REQUIRES(context, num_values <= indices.shape().dim_size(0),
-                errors::InvalidArgument(
-                    "The first dimension of indices must be equal to or "
-                    "greather than number of values. ( ",
-                    indices.shape().dim_size(0), " vs. ", num_values, " )"));
-    OP_REQUIRES(context, indices.shape().dim_size(1) > 0,
-                errors::InvalidArgument("The second dimension of indices must "
-                                        "be greater than 0. Received: ",
-                                        indices.shape().dim_size(1)));
-
     for (int idx = 0; idx < num_values; ++idx) {
       int batch = is_1d ? 0 : indices_values(idx, 0);
       if (batch >= num_batches) {
         OP_REQUIRES(context, batch < num_batches,
                     errors::InvalidArgument(

Vulnerable code:     OP_REQUIRES(context, shape.NumElements() != 0,
                errors::InvalidArgument(
                    "The shape argument requires at least one element."));

    for (int b = 0; b < shape_vector.size(); b++) {
      OP_REQUIRES(context, shape_vector(b) >= 0,
                  errors::InvalidArgument(
                      "Elements in dense_shape must be >= 0. Instead got:",
                      shape.DebugString()));
    }

    OP_REQUIRES(context, num_values == indices.shape().dim_size(0),
                errors::InvalidArgument(
                    "Number of values must match first dimension of indices.",
                    "Got ", num_values,
                    " values, indices shape: ", indices.shape().DebugString()));

    OP_REQUIRES(context, num_values <= indices.shape().dim_size(0),
                errors::InvalidArgument(
                    "The first dimension of indices must be equal to or "
                    "greather than number of values. ( ",
                    indices.shape().dim_size(0), " vs. ", num_values, " )"));
    OP_REQUIRES(context, indices.shape().dim_size(1) > 0,
                errors::InvalidArgument("The second dimension of indices must "
                                        "be greater than 0. Received: ",
                                        indices.shape().dim_size(1)));

Fixed code:     OP_REQUIRES(context, TensorShapeUtils::IsVector(values.shape()),
                errors::InvalidArgument("Input values must be a vector. Got: ",
                                        values.shape().DebugString()));
    OP_REQUIRES(context, TensorShapeUtils::IsVector(shape.shape()),
                errors::InvalidArgument("Input shape must be a vector. Got: ",
                                        shape.shape().DebugString()));
    OP_REQUIRES(context,
                values.shape().dim_size(0) == indices.shape().dim_size(0),
                errors::InvalidArgument(
                    "Number of values must match first dimension of indices.",
                    "Got ", values.shape().dim_size(0),
                    " values, indices shape: ", indices.shape().DebugString()));
    OP_REQUIRES(
        context, shape.shape().dim_size(0) == indices.shape().dim_size(1),
        errors::InvalidArgument(
            "Number of dimensions must match second dimension of indices.",
            "Got ", shape.shape().dim_size(0),
            " dimensions, indices shape: ", indices.shape().DebugString()));
    OP_REQUIRES(context, shape.NumElements() > 0,
                errors::InvalidArgument(
                    "The shape argument requires at least one element."));