Vulnerability: Invalid validation in `SparseMatrixSparseCholesky` ### Impact
An attacker can trigger a null pointer dereference by providing an invalid `permutation` to `tf.raw_ops.SparseMatrixSparseCholesky`:

```python
import tensorflow as tf
import numpy as np
from tensorflow.python.ops.linalg.sparse import sparse_csr_matrix_ops

indices_array = np.array([[0, 0]])
value_array = np.array([-10.0], dtype=np.float32)
dense_shape = [1, 1]
st = tf.SparseTensor(indices_array, value_array, dense_shape)

input = sparse_csr_matrix_ops.sparse_tensor_to_csr_sparse_matrix(
       st.indices, st.values, st.dense_shape)

permutation = tf.constant([], shape=[1, 0], dtype=tf.int32)
 
tf.raw_ops.SparseMatrixSparseCholesky(input=input, permutation=permutation, type=tf.float32)
```

This is because the [implementation](https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/kernels/sparse/sparse_cholesky_op.cc#L85-L86) fails to properly validate the input arguments: 
                          
```cc 
void Compute(OpKernelContext* ctx) final {
  ...
  const Tensor& input_permutation_indices = ctx->input(1);
  ...
  ValidateInputs(ctx, *input_matrix, input_permutation_indices, &batch_size, &num_rows);
  ...
}

void ValidateInputs(OpKernelContext* ctx,
    const CSRSparseMatrix& sparse_matrix,
    const Tensor& permutation_indices, int* batch_size,
    int64* num_rows) {
  OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum<T>::value, ...)
  ...
}
```
Although `ValidateInputs` is called and there are checks in the body of this function, the code proceeds to the next line in `ValidateInputs` since [`OP_REQUIRES`](https://github.com/tensorflow/tensorflow/blob/080f1d9e257589f78b3ffb75debf584168aa6062/tensorflow/core/framework/op_requires.h#L41-L48) is a macro that only exits the current function.

```cc
#define OP_REQUIRES(CTX, EXP, STATUS)                     \
  do {                                                    \
    if (!TF_PREDICT_TRUE(EXP)) {                          \
      CheckNotInComputeAsync((CTX), "OP_REQUIRES_ASYNC"); \
      (CTX)->CtxFailure(__FILE__, __LINE__, (STATUS));    \
      return;                                             \
    }                                                     \
  } while (0)
```

Thus, the first validation condition that fails in `ValidateInputs` will cause an early return from that function. However, the caller will continue execution from the next line. The fix is to either explicitly check `context->status()` or to convert `ValidateInputs` to return a `Status`.

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

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 Ying Wang and Yakun Zhang of Baidu X-Team.
Vulnerability ID: GHSA-xcwj-wfcm-m23c
CWE: CWE-476
Severity score: 2.5
Project: https://github.com/tensorflow/tensorflow
Published: 2021-05-21
File: tensorflow/core/kernels/sparse/sparse_cholesky_op.cc
Commit message: Remove `OP_REQUIRES` call from helper function.

Since `OP_REQUIRES` macro expands to a `return;` (among other), calling it in a helper function only ends the helper function's execution earlier, but the kernel will still run from start to end. Thus, all the expected validations are actually broken/useless as the code ploughs through the next crash anyway.

PiperOrigin-RevId: 369524386
Change-Id: I54f6cf9328445675ccc392e661b04336b229c9da
Commit author: Mihai Maruseac

Vulnerable version (before fix):
 limitations under the License. #include <numeric> #include <vector>  #define EIGEN_USE_THREADS  #include "third_party/eigen3/Eigen/Core" class CSRSparseCholeskyCPUOp : public OpKernel {      int64 num_rows;     int batch_size;     ValidateInputs(ctx, *input_matrix, input_permutation_indices, &batch_size,                    &num_rows);      // Allocate batch pointers.     Tensor batch_ptr(cpu_allocator(), DT_INT32, TensorShape({batch_size + 1})); class CSRSparseCholeskyCPUOp : public OpKernel {   }   private:   void ValidateInputs(OpKernelContext* ctx,                       const CSRSparseMatrix& sparse_matrix,                       const Tensor& permutation_indices, int* batch_size,                       int64* num_rows) {     OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum<T>::value,                 errors::InvalidArgument(                     "Asked for a CSRSparseMatrix of type ",                     DataTypeString(DataTypeToEnum<T>::value),                     " but saw dtype: ", DataTypeString(sparse_matrix.dtype())));      const Tensor& dense_shape = sparse_matrix.dense_shape();     const int rank = dense_shape.dim_size(0);     OP_REQUIRES(ctx, rank == 2 || rank == 3,                 errors::InvalidArgument("sparse matrix must have rank 2 or 3; ",                                         "but dense_shape has size ", rank));     const int row_dim = (rank == 2) ? 0 : 1;     auto dense_shape_vec = dense_shape.vec<int64>();     *num_rows = dense_shape_vec(row_dim);     const int64 num_cols = dense_shape_vec(row_dim + 1);     OP_REQUIRES(ctx, *num_rows == num_cols,                 errors::InvalidArgument("sparse matrix must be square; got: ",                                         *num_rows, " != ", num_cols));     const TensorShape& perm_shape = permutation_indices.shape();     OP_REQUIRES(         ctx, perm_shape.dims() + 1 == rank,         errors::InvalidArgument(             "sparse matrix must have the same rank as permutation; got: ", rank,             " != ", perm_shape.dims(), " + 1."));     OP_REQUIRES(         ctx, perm_shape.dim_size(rank - 2) == *num_rows,         errors::InvalidArgument(             "permutation must have the same number of elements in each batch "             "as the number of rows in sparse matrix; got: ",             perm_shape.dim_size(rank - 2), " != ", *num_rows));      *batch_size = sparse_matrix.batch_size();     if (*batch_size > 1) {       OP_REQUIRES(           ctx, perm_shape.dim_size(0) == *batch_size,           errors::InvalidArgument("permutation must have the same batch size "                                   "as sparse matrix; got: ",                                   perm_shape.dim_size(0), " != ", *batch_size));     }   } }; 

Fixed version (after fix):
 limitations under the License. #include <numeric> #include <vector>  #include "tensorflow/core/framework/op_requires.h"  #define EIGEN_USE_THREADS  #include "third_party/eigen3/Eigen/Core" class CSRSparseCholeskyCPUOp : public OpKernel {      int64 num_rows;     int batch_size;     OP_REQUIRES_OK(ctx, ValidateInputs(*input_matrix, input_permutation_indices,                                        &batch_size, &num_rows));      // Allocate batch pointers.     Tensor batch_ptr(cpu_allocator(), DT_INT32, TensorShape({batch_size + 1})); class CSRSparseCholeskyCPUOp : public OpKernel {   }   private:   Status ValidateInputs(const CSRSparseMatrix& sparse_matrix,                         const Tensor& permutation_indices, int* batch_size,                         int64* num_rows) {     if (sparse_matrix.dtype() != DataTypeToEnum<T>::value)       return errors::InvalidArgument(           "Asked for a CSRSparseMatrix of type ",           DataTypeString(DataTypeToEnum<T>::value),           " but saw dtype: ", DataTypeString(sparse_matrix.dtype()));      const Tensor& dense_shape = sparse_matrix.dense_shape();     const int rank = dense_shape.dim_size(0);     if (rank < 2 || rank > 3)       return errors::InvalidArgument("sparse matrix must have rank 2 or 3; ",                                      "but dense_shape has size ", rank);     const int row_dim = (rank == 2) ? 0 : 1;     auto dense_shape_vec = dense_shape.vec<int64>();     *num_rows = dense_shape_vec(row_dim);     const int64 num_cols = dense_shape_vec(row_dim + 1);     if (*num_rows != num_cols)       return errors::InvalidArgument(           "sparse matrix must be square; got: ", *num_rows, " != ", num_cols);     const TensorShape& perm_shape = permutation_indices.shape();     if (perm_shape.dims() + 1 != rank)       return errors::InvalidArgument(           "sparse matrix must have the same rank as permutation; got: ", rank,           " != ", perm_shape.dims(), " + 1.");     if (perm_shape.dim_size(rank - 2) != *num_rows)       return errors::InvalidArgument(           "permutation must have the same number of elements in each batch "           "as the number of rows in sparse matrix; got: ",           perm_shape.dim_size(rank - 2), " != ", *num_rows);      *batch_size = sparse_matrix.batch_size();     if (*batch_size > 1) {       if (perm_shape.dim_size(0) != *batch_size)         return errors::InvalidArgument(             "permutation must have the same batch size "             "as sparse matrix; got: ",             perm_shape.dim_size(0), " != ", *batch_size);     }      return Status::OK();   } }; 

Patch:
patch: @@ -17,6 +17,8 @@ limitations under the License.
 #include <numeric>
 #include <vector>
 
+#include "tensorflow/core/framework/op_requires.h"
+
 #define EIGEN_USE_THREADS
 
 #include "third_party/eigen3/Eigen/Core"
@@ -82,8 +84,8 @@ class CSRSparseCholeskyCPUOp : public OpKernel {
 
     int64 num_rows;
     int batch_size;
-    ValidateInputs(ctx, *input_matrix, input_permutation_indices, &batch_size,
-                   &num_rows);
+    OP_REQUIRES_OK(ctx, ValidateInputs(*input_matrix, input_permutation_indices,
+                                       &batch_size, &num_rows));
 
     // Allocate batch pointers.
     Tensor batch_ptr(cpu_allocator(), DT_INT32, TensorShape({batch_size + 1}));
@@ -226,49 +228,48 @@ class CSRSparseCholeskyCPUOp : public OpKernel {
   }
 
  private:
-  void ValidateInputs(OpKernelContext* ctx,
-                      const CSRSparseMatrix& sparse_matrix,
-                      const Tensor& permutation_indices, int* batch_size,
-                      int64* num_rows) {
-    OP_REQUIRES(ctx, sparse_matrix.dtype() == DataTypeToEnum<T>::value,
-                errors::InvalidArgument(
-                    "Asked for a CSRSparseMatrix of type ",
-                    DataTypeString(DataTypeToEnum<T>::value),
-                    " but saw dtype: ", DataTypeString(sparse_matrix.dtype())));
+  Status ValidateInputs(const CSRSparseMatrix& sparse_matrix,
+                        const Tensor& permutation_indices, int* batch_size,
+                        int64* num_rows) {
+    if (sparse_matrix.dtype() != DataTypeToEnum<T>::value)
+      return errors::InvalidArgument(
+          "Asked for a CSRSparseMatrix of type ",
+          DataTypeString(DataTypeToEnum<T>::value),
+          " but saw dtype: ", DataTypeString(sparse_matrix.dtype()));
 
     const Tensor& dense_shape = sparse_matrix.dense_shape();
     const int rank = dense_shape.dim_size(0);
-    OP_REQUIRES(ctx, rank == 2 || rank == 3,
-                errors::InvalidArgument("sparse matrix must have rank 2 or 3; ",
-                                        "but dense_shape has size ", rank));
+    if (rank < 2 || rank > 3)
+      return errors::InvalidArgument("sparse matrix must have rank 2 or 3; ",
+                                     "but dense_shape has size ", rank);
     const int row_dim = (rank == 2) ? 0 : 1;
     auto dense_shape_vec = dense_shape.vec<int64>();
     *num_rows = dense_shape_vec(row_dim);
     const int64 num_cols = dense_shape_vec(row_dim + 1);
-    OP_REQUIRES(ctx, *num_rows == num_cols,
-                errors::InvalidArgument("sparse matrix must be square; got: ",
-                                        *num_rows, " != ", num_cols));
+    if (*num_rows != num_cols)
+      return errors::InvalidArgument(
+          "sparse matrix must be square; got: ", *num_rows, " != ", num_cols);
     const TensorShape& perm_shape = permutation_indices.shape();
-    OP_REQUIRES(
-        ctx, perm_shape.dims() + 1 == rank,
-        errors::InvalidArgument(
-            "sparse matrix must have the same rank as permutation; got: ", rank,
-            " != ", perm_shape.dims(), " + 1."));
-    OP_REQUIRES(
-        ctx, perm_shape.dim_size(rank - 2) == *num_rows,
-        errors::InvalidArgument(
-            "permutation must have the same number of elements in each batch "
-            "as the number of rows in sparse matrix; got: ",
-            perm_shape.dim_size(rank - 2), " != ", *num_rows));
+    if (perm_shape.dims() + 1 != rank)
+      return errors::InvalidArgument(
+          "sparse matrix must have the same rank as permutation; got: ", rank,
+          " != ", perm_shape.dims(), " + 1.");
+    if (perm_shape.dim_size(rank - 2) != *num_rows)
+      return errors::InvalidArgument(
+          "permutation must have the same number of elements in each batch "
+          "as the number of rows in sparse matrix; got: ",
+          perm_shape.dim_size(rank - 2), " != ", *num_rows);
 
     *batch_size = sparse_matrix.batch_size();
     if (*batch_size > 1) {
-      OP_REQUIRES(
-          ctx, perm_shape.dim_size(0) == *batch_size,
-          errors::InvalidArgument("permutation must have the same batch size "
-                                  "as sparse matrix; got: ",
-                                  perm_shape.dim_size(0), " != ", *batch_size));
+      if (perm_shape.dim_size(0) != *batch_size)
+        return errors::InvalidArgument(
+            "permutation must have the same batch size "
+            "as sparse matrix; got: ",
+            perm_shape.dim_size(0), " != ", *batch_size);
     }
+
+    return Status::OK();
   }
 };
path: tensorflow/core/kernels/sparse/sparse_cholesky_op.cc