CVE-2022-41884: Always-Incorrect Control Flow Implementation (CWE-670)
value: TensorFlow is an open source platform for machine learning. If a numpy array is created with a shape such that one element is zero and the others sum to a large number, an error will be raised. We have patched the issue in GitHub commit 2b56169c16e375c521a3bc8ea658811cc0793784. The fix will be included in TensorFlow 2.11. We will also cherrypick this commit on TensorFlow 2.10.1, 2.9.3, and TensorFlow 2.8.4, as these are also affected and still in supported range.
CWE description: The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.
CVSS v3 base score: 7.5
Published: 2022-11-18T22:15Z
Repository: https://github.com/tensorflow/tensorflow
Language: Other
Files changed: tensorflow/python/eager/tensor_test.py, tensorflow/python/lib/core/BUILD, tensorflow/python/lib/core/ndarray_tensor_bridge.cc
Commit date: 2022-09-29 10:02:06 -0700
Commit message: Fix segfault when using unusally shaped tensors.

If a numpy array is created with a shape such that one element is zero and the others sum to a large number, an error will be raised. E.g. the following raises an error:

np.ones((0, 2**31, 2**31))

TF previously would not check the return value of PyArray_SimpleNewFromData, which returns null on such shapes. Now the return value is checked.

PiperOrigin-RevId: 477751929

Diff: diff --git a/tensorflow/python/eager/tensor_test.py b/tensorflow/python/eager/tensor_test.py
index a12b18abaecef..8058a97446cb8 100644
--- a/tensorflow/python/eager/tensor_test.py
+++ b/tensorflow/python/eager/tensor_test.py
@@ -513,10 +513,20 @@ class TFETensorTest(test_util.TensorFlowTestCase):
         errors.InvalidArgumentError,
         "Cannot convert tensor with 33 dimensions to NumPy array. NumPy arrays "
         "can have at most 32 dimensions"):
       t.numpy()
 
+  def testNumpyDimsTooBig(self):
+    # Creating a Numpy array fails in some cases if the product of non-zero
+    # dimensions is very big, even if the shape also has a zero in it.
+    t = array_ops.ones((0, 2**31, 2**31))
+    with self.assertRaisesRegex(
+        errors.InvalidArgumentError,
+        r"Failed to create numpy array from tensor of shape "
+        r"\[0, 2147483648, 2147483648\]. Numpy error.*array is too big"):
+      t.numpy()
+
 
 class TFETensorUtilTest(test_util.TensorFlowTestCase):
 
   def setUp(self):
     super(TFETensorUtilTest, self).setUp()
diff --git a/tensorflow/python/lib/core/BUILD b/tensorflow/python/lib/core/BUILD
index ed063c191d4c7..8b3b785c5e639 100644
--- a/tensorflow/python/lib/core/BUILD
+++ b/tensorflow/python/lib/core/BUILD
@@ -86,10 +86,11 @@ cc_library(
         ],
     ),
     deps = [
         ":bfloat16_lib",
         ":numpy_lib",
+        ":py_util",
         "//tensorflow/c:c_api_no_xla",
         "//tensorflow/core:lib",
         "//tensorflow/core:protos_all_cc",
     ],
 )
diff --git a/tensorflow/python/lib/core/ndarray_tensor_bridge.cc b/tensorflow/python/lib/core/ndarray_tensor_bridge.cc
index 00aeed4978dac..b3b1fe2fdc7c4 100644
--- a/tensorflow/python/lib/core/ndarray_tensor_bridge.cc
+++ b/tensorflow/python/lib/core/ndarray_tensor_bridge.cc
@@ -11,20 +11,24 @@ 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.
 ==============================================================================*/
 
+// clang-format off
 // Must be included first.
 #include "tensorflow/python/lib/core/numpy.h"
+// clang-format on
+
+#include "tensorflow/python/lib/core/ndarray_tensor_bridge.h"
 
 #include <vector>
 
 #include "tensorflow/c/c_api.h"
 #include "tensorflow/core/lib/core/errors.h"
 #include "tensorflow/core/platform/mutex.h"
 #include "tensorflow/python/lib/core/bfloat16.h"
-#include "tensorflow/python/lib/core/ndarray_tensor_bridge.h"
+#include "tensorflow/python/lib/core/py_util.h"
 
 namespace tensorflow {
 
 // Mutex used to serialize accesses to cached vector of pointers to python
 // arrays to be dereferenced.
@@ -212,10 +216,24 @@ Status ArrayFromMemory(int dim_size, npy_intp* dims, void* data, DataType dtype,
         " dimensions to NumPy array. NumPy arrays can have at most ",
         NPY_MAXDIMS, " dimensions");
   }
   auto* np_array = reinterpret_cast<PyArrayObject*>(
       PyArray_SimpleNewFromData(dim_size, dims, type_num, data));
+  if (np_array == nullptr) {
+    string shape_str = absl::StrJoin(
+        absl::Span<npy_intp>{dims, static_cast<size_t>(dim_size)}, ", ");
+    if (PyErr_Occurred()) {
+      string exception_str = PyExceptionFetch();
+      PyErr_Clear();
+      return errors::InvalidArgument(
+          "Failed to create numpy array from tensor of shape [", shape_str,
+          "]. Numpy error: ", exception_str);
+    }
+    return errors::Internal(
+        "Failed to create numpy array from tensor of shape [", shape_str, "]");
+  }
+
   PyArray_CLEARFLAGS(np_array, NPY_ARRAY_OWNDATA);
   if (PyType_Ready(&TensorReleaserType) == -1) {
     return errors::Unknown("Python type initialization failed.");
   }
   auto* releaser = reinterpret_cast<TensorReleaser*>(

Vulnerable code: #include "tensorflow/python/lib/core/ndarray_tensor_bridge.h"
Fixed code:   def testNumpyDimsTooBig(self):
    # Creating a Numpy array fails in some cases if the product of non-zero
    # dimensions is very big, even if the shape also has a zero in it.
    t = array_ops.ones((0, 2**31, 2**31))
    with self.assertRaisesRegex(
        errors.InvalidArgumentError,
        r"Failed to create numpy array from tensor of shape "
        r"\[0, 2147483648, 2147483648\]. Numpy error.*array is too big"):
      t.numpy()

        ":py_util",
// clang-format off
// clang-format on

#include "tensorflow/python/lib/core/ndarray_tensor_bridge.h"
#include "tensorflow/python/lib/core/py_util.h"
  if (np_array == nullptr) {
    string shape_str = absl::StrJoin(
        absl::Span<npy_intp>{dims, static_cast<size_t>(dim_size)}, ", ");
    if (PyErr_Occurred()) {
      string exception_str = PyExceptionFetch();
      PyErr_Clear();
      return errors::InvalidArgument(
          "Failed to create numpy array from tensor of shape [", shape_str,
          "]. Numpy error: ", exception_str);
    }
    return errors::Internal(
        "Failed to create numpy array from tensor of shape [", shape_str, "]");
  }