CVE-2022-35952: Reachable Assertion (CWE-617)
value: TensorFlow is an open source platform for machine learning. The `UnbatchGradOp` function takes an argument `id` that is assumed to be a scalar. A nonscalar `id` can trigger a `CHECK` failure and crash the program. It also requires its argument `batch_index` to contain three times the number of elements as indicated in its `batch_index.dim_size(0)`. An incorrect `batch_index` can trigger a `CHECK` failure and crash the program. We have patched the issue in GitHub commit 5f945fc6409a3c1e90d6970c9292f805f6e6ddf2. 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 contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
CVSS v3 base score: 7.5
Published: 2022-09-16T20:15Z
Repository: https://github.com/tensorflow/tensorflow
Language: Python
Files changed: tensorflow/core/kernels/batch_kernels.cc, tensorflow/python/ops/batch_ops_test.py
Commit date: 2022-07-14 10:25:43 -0700
Commit message: Fix security vulnerability with UnbatchGradKernel

PiperOrigin-RevId: 460992964

Diff: diff --git a/tensorflow/core/kernels/batch_kernels.cc b/tensorflow/core/kernels/batch_kernels.cc
index b2e099313f85a..7aba9db55ddc7 100644
--- a/tensorflow/core/kernels/batch_kernels.cc
+++ b/tensorflow/core/kernels/batch_kernels.cc
@@ -883,12 +883,17 @@ class UnbatchGradResource : public ResourceBase {
   Status Compute(OpKernelContext* context,
                  const AsyncOpKernel::DoneCallback& done) {
     const Tensor& data_t = context->input(0);
     const Tensor& batch_index_t = context->input(1);
     const Tensor& grad_t = context->input(2);
+    const Tensor& batch_key_t = context->input(3);
 
     mutex_lock ml(mu_);
+    if (batch_key_t.NumElements() != 1) {
+      return errors::InvalidArgument("Expected `id` to be scalar. Received ",
+                                     batch_key_t.DebugString());
+    }
 
     const int64_t batch_key = context->input(3).scalar<int64_t>()();
     // Mark our tensor as available.
     if (!available_tensors_.emplace(batch_key, grad_t).second) {
       return errors::InvalidArgument("Two runs with the same batch key.");
@@ -900,10 +905,15 @@ class UnbatchGradResource : public ResourceBase {
       if (batch_index_t.NumElements() == 0) {
         return errors::InvalidArgument(
             "batch_index is empty while the tensor isn't.");
       }
       std::unordered_set<int64_t> missing_tensors;
+      if (batch_index_t.NumElements() != batch_index_t.dim_size(0) * 3) {
+        return errors::InvalidArgument(
+            "batch_index should contain ", batch_index_t.dim_size(0) * 3,
+            " elements. Received ", batch_index_t.NumElements());
+      }
       const auto batch_index =
           batch_index_t.shaped<int64_t, 2>({batch_index_t.dim_size(0), 3});
       for (int i = 0; i < batch_index_t.dim_size(0); ++i) {
         const int64_t batch_key = batch_index(i, 0);
         if (available_tensors_.find(batch_key) == available_tensors_.end()) {
diff --git a/tensorflow/python/ops/batch_ops_test.py b/tensorflow/python/ops/batch_ops_test.py
index 7ef5e06fb6757..8fae09a791199 100644
--- a/tensorflow/python/ops/batch_ops_test.py
+++ b/tensorflow/python/ops/batch_ops_test.py
@@ -18,20 +18,23 @@ import threading
 import time
 import numpy as np
 
 from tensorflow.core.protobuf import config_pb2
 from tensorflow.python.eager import context
+from tensorflow.python.framework import constant_op
 from tensorflow.python.framework import dtypes
+from tensorflow.python.framework import errors
 from tensorflow.python.framework import function
 from tensorflow.python.framework import ops
 from tensorflow.python.framework import test_util
 from tensorflow.python.framework.errors import InvalidArgumentError
 from tensorflow.python.ops import array_ops
 from tensorflow.python.ops import batch_ops
 from tensorflow.python.ops import gen_batch_ops
 from tensorflow.python.ops import gen_functional_ops
 from tensorflow.python.ops import math_ops
+from tensorflow.python.ops import random_ops
 from tensorflow.python.ops import resource_variable_ops
 from tensorflow.python.ops import script_ops
 from tensorflow.python.ops import variables
 from tensorflow.python.platform import test
 
@@ -555,8 +558,58 @@ class BatchOpsTest(test.TestCase):
       _ = sess.run([result_delayed], feed_dict={inp: [2]})
       worker_thread.join()
       # The thread's call should hit the timeout, and thus get 0 results.
       self.assertEqual(len(thread_results), 0)
 
+  def testUnbatchGradInvalidId(self):
+    with self.assertRaises(errors.InvalidArgumentError):
+      self.evaluate(
+          gen_batch_ops.unbatch_grad(
+              original_input=constant_op.constant([1]),
+              batch_index=constant_op.constant([
+                  [0, 0, 0],
+              ], dtype=dtypes.int64),
+              grad=constant_op.constant([
+                  1,
+              ]),
+              id=constant_op.constant([
+                  1,
+                  1,
+              ], dtype=dtypes.int64)))
+
+  def testUnbatchGradInvalidBatchId(self):
+    with self.assertRaises(errors.InvalidArgumentError):
+      self.evaluate(
+          gen_batch_ops.unbatch_grad(
+              original_input=constant_op.constant([1]),
+              batch_index=constant_op.constant([
+                  [0, 0],
+              ], dtype=dtypes.int64),
+              grad=constant_op.constant([
+                  1,
+              ]),
+              id=constant_op.constant([
+                  1,
+              ], dtype=dtypes.int64)))
+
+  def testUnbatchGradInvalidArgs(self):
+    original_input = random_ops.random_uniform(
+        shape=(3, 1), dtype=dtypes.float64, maxval=None)
+    batch_index = random_ops.random_uniform(
+        shape=(3, 1), dtype=dtypes.int64, maxval=65536)
+    grad = random_ops.random_uniform(
+        shape=(3, 1), dtype=dtypes.float64, maxval=None)
+    batch_id = random_ops.random_uniform(
+        shape=(3, 1), dtype=dtypes.int64, maxval=65536)
+    with self.assertRaises(errors.InvalidArgumentError):
+      self.evaluate(
+          gen_batch_ops.unbatch_grad(
+              original_input=original_input,
+              batch_index=batch_index,
+              grad=grad,
+              id=batch_id,
+              container="",
+              shared_name="",
+              name=""))
 
 if __name__ == "__main__":
   test.main()

Fixed code:     const Tensor& batch_key_t = context->input(3);
    if (batch_key_t.NumElements() != 1) {
      return errors::InvalidArgument("Expected `id` to be scalar. Received ",
                                     batch_key_t.DebugString());
    }
      if (batch_index_t.NumElements() != batch_index_t.dim_size(0) * 3) {
        return errors::InvalidArgument(
            "batch_index should contain ", batch_index_t.dim_size(0) * 3,
            " elements. Received ", batch_index_t.NumElements());
      }
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors
from tensorflow.python.ops import random_ops
  def testUnbatchGradInvalidId(self):
    with self.assertRaises(errors.InvalidArgumentError):
      self.evaluate(
          gen_batch_ops.unbatch_grad(
              original_input=constant_op.constant([1]),
              batch_index=constant_op.constant([
                  [0, 0, 0],
              ], dtype=dtypes.int64),
              grad=constant_op.constant([
                  1,
              ]),
              id=constant_op.constant([
                  1,
                  1,
              ], dtype=dtypes.int64)))

  def testUnbatchGradInvalidBatchId(self):
    with self.assertRaises(errors.InvalidArgumentError):
      self.evaluate(
          gen_batch_ops.unbatch_grad(
              original_input=constant_op.constant([1]),
              batch_index=constant_op.constant([
                  [0, 0],
              ], dtype=dtypes.int64),
              grad=constant_op.constant([
                  1,
              ]),
              id=constant_op.constant([
                  1,
              ], dtype=dtypes.int64)))

  def testUnbatchGradInvalidArgs(self):
    original_input = random_ops.random_uniform(
        shape=(3, 1), dtype=dtypes.float64, maxval=None)
    batch_index = random_ops.random_uniform(
        shape=(3, 1), dtype=dtypes.int64, maxval=65536)
    grad = random_ops.random_uniform(
        shape=(3, 1), dtype=dtypes.float64, maxval=None)
    batch_id = random_ops.random_uniform(
        shape=(3, 1), dtype=dtypes.int64, maxval=65536)
    with self.assertRaises(errors.InvalidArgumentError):
      self.evaluate(
          gen_batch_ops.unbatch_grad(
              original_input=original_input,
              batch_index=batch_index,
              grad=grad,
              id=batch_id,
              container="",
              shared_name="",
              name=""))