Vulnerability: Type confusion during tensor casts lead to dereferencing null pointers ### Impact
Calling TF operations with tensors of non-numeric types when the operations expect numeric tensors result in null pointer dereferences.

There are multiple ways to reproduce this, listing a few examples here:

```python
import tensorflow as tf
import numpy as np
data = tf.random.truncated_normal(shape=1,mean=np.float32(20.8739),stddev=779.973,dtype=20,seed=64)
```

```python
import tensorflow as tf
import numpy as np
data =
tf.random.stateless_truncated_normal(shape=1,seed=[63,70],mean=np.float32(20.8739),stddev=779.973,dtype=20)
```

```python
import tensorflow as tf
import numpy as np
data = tf.one_hot(indices=[62,50],depth=136,on_value=np.int32(237),off_value=158,axis=856,dtype=20)
```

```python
import tensorflow as tf
import numpy as np
data = tf.range(start=np.int32(214),limit=660,delta=129,dtype=20)
```

```python
import tensorflow as tf
import numpy as np
data = tf.raw_ops.ResourceCountUpTo(resource=np.int32(30), limit=872, T=3)
```

```python
import tensorflow as tf
import numpy as np

writer_array = np.array([1,2],dtype=np.int32)
writer_tensor = tf.convert_to_tensor(writer_array,dtype=tf.resource)
```

All these examples and similar ones have the same behavior: the [conversion from Python array to C++ array](https://github.com/tensorflow/tensorflow/blob/ff70c47a396ef1e3cb73c90513da4f5cb71bebba/tensorflow/python/lib/core/ndarray_tensor.cc#L113-L169) is vulnerable to a type confusion:

```cc
  int pyarray_type = PyArray_TYPE(array);
  PyArray_Descr* descr = PyArray_DESCR(array);
  switch (pyarray_type) {
    ...
    case NPY_VOID:
      // Quantized types are currently represented as custom struct types.
      // PyArray_TYPE returns NPY_VOID for structs, and we should look into
      // descr to derive the actual type.
      // Direct feeds of certain types of ResourceHandles are represented as a
      // custom struct type.
      return PyArrayDescr_to_TF_DataType(descr, out_tf_datatype);
    ...
  }
```

For the tensor types involved in the above example, the `pyarray_type` is `NPY_VOID` but the `descr` field is such that `descr->field = NULL`. Then [`PyArrayDescr_to_TF_DataType`](https://github.com/tensorflow/tensorflow/blob/ff70c47a396ef1e3cb73c90513da4f5cb71bebba/tensorflow/python/lib/core/ndarray_tensor.cc#L72-L77) will trigger a null dereference:

```cc
Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,
                                   TF_DataType* out_tf_datatype) {
  PyObject* key;
  PyObject* value;
  Py_ssize_t pos = 0;
  if (PyDict_Next(descr->fields, &pos, &key, &value)) {
    ...
  }
}
```

This is because the Python's `PyDict_Next` implementation would dereference the first argument.

### Patches
We have patched the issue in GitHub commit [030af767d357d1b4088c4a25c72cb3906abac489](https://github.com/tensorflow/tensorflow/commit/030af767d357d1b4088c4a25c72cb3906abac489).

The fix will be included in TensorFlow 2.5.0. We will also cherrypick this commit on TensorFlow 2.4.2, TensorFlow 2.3.3, TensorFlow 2.2.3 and TensorFlow 2.1.4, as these are also affected and still in supported range.

### For more information
Please consult [our security guide](https://github.com/tensorflow/tensorflow/blob/master/SECURITY.md) for more information regarding the security model and how to contact us with issues and questions.

### Attribution
This vulnerability has been reported by members of the Aivul Team from Qihoo 360 as well as Ye Zhang and Yakun Zhang of Baidu X-Team.
Vulnerability ID: GHSA-452g-f7fp-9jf7
CWE: CWE-476
Severity score: 2.5
Project: https://github.com/tensorflow/tensorflow
Published: 2021-05-21
File: tensorflow/python/lib/core/ndarray_tensor.cc
Commit message: Fix `tf.raw_ops.ResourceCountUpTo` null pointer dereference.

PiperOrigin-RevId: 368294347
Change-Id: I2c16fbfc9b4966c402c3d8e311f0d665a9c852d8
Commit author: Amit Patankar

Vulnerable version (before fix):
 limitations under the License. #include "tensorflow/python/lib/core/ndarray_tensor.h"  #include <cstring>  #include "tensorflow/c/eager/tfe_context_internal.h" #include "tensorflow/c/tf_tensor_internal.h" Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,   PyObject* key;   PyObject* value;   Py_ssize_t pos = 0;   if (PyDict_Next(descr->fields, &pos, &key, &value)) {     // In Python 3, the keys of numpy custom struct types are unicode, unlike     // Python 2, where the keys are bytes.

Fixed version (after fix):
 limitations under the License. #include "tensorflow/python/lib/core/ndarray_tensor.h"  #include <cstring> #include <optional>  #include "tensorflow/c/eager/tfe_context_internal.h" #include "tensorflow/c/tf_tensor_internal.h" Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,   PyObject* key;   PyObject* value;   Py_ssize_t pos = 0;    // Return an error if the fields attribute is null.   // Occurs with an improper conversion attempt to resource.   if (descr->fields == nullptr) {     return errors::Internal("Unexpected numpy data type");   }    if (PyDict_Next(descr->fields, &pos, &key, &value)) {     // In Python 3, the keys of numpy custom struct types are unicode, unlike     // Python 2, where the keys are bytes.

Patch:
patch: @@ -16,6 +16,7 @@ limitations under the License.
 #include "tensorflow/python/lib/core/ndarray_tensor.h"
 
 #include <cstring>
+#include <optional>
 
 #include "tensorflow/c/eager/tfe_context_internal.h"
 #include "tensorflow/c/tf_tensor_internal.h"
@@ -74,6 +75,13 @@ Status PyArrayDescr_to_TF_DataType(PyArray_Descr* descr,
   PyObject* key;
   PyObject* value;
   Py_ssize_t pos = 0;
+
+  // Return an error if the fields attribute is null.
+  // Occurs with an improper conversion attempt to resource.
+  if (descr->fields == nullptr) {
+    return errors::Internal("Unexpected numpy data type");
+  }
+
   if (PyDict_Next(descr->fields, &pos, &key, &value)) {
     // In Python 3, the keys of numpy custom struct types are unicode, unlike
     // Python 2, where the keys are bytes.
path: tensorflow/python/lib/core/ndarray_tensor.cc