hitoshura25/cvefixes huggingface dataset:
CVE-2022-36004 (Python, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `tf.random.gamma` receives large input shape and rates, it gives a `CHECK` fail that can trigger a denial of service attack. We have patched the issue in GitHub commit 552bfced6ce4809db5f3ca305f60ff80dd40c5a3. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-617 \u2014 Reachable Assertion
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.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/random_op.cc
tensorflow/core/kernels/random_poisson_op.cc
tensorflow/python/kernel_tests/random/random_gamma_test.py
tensorflow/python/kernel_tests/random/random_poisson_test.py
Commit message: Fix size check for large input shape and rates.

To address a check failure for exceedingly large output shapes, we need to
`AppendShapeWithStatus`.

PiperOrigin-RevId: 462885894


Vulnerable code:
    samples_shape.AppendShape(alpha_t.shape());
    samples_shape.AppendShape(rate_t.shape());

Fixed code:
    OP_REQUIRES_OK(ctx, samples_shape.AppendShapeWithStatus(alpha_t.shape()));
    OP_REQUIRES_OK(ctx, samples_shape.AppendShapeWithStatus(rate_t.shape()));
from tensorflow.python.eager import context
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import errors
  def testSizeTooLarge(self):
    # Grappler asserts on size overflow, so this error is only caught when
    # running eagerly.
    if context.executing_eagerly():
      with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                  "overflow"):
        rate = constant_op.constant(1.0, shape=(4, 4, 4, 4, 4))
        self.evaluate(
            random_ops.random_gamma(
                shape=[46902, 51188, 34063, 59195], alpha=rate))
from tensorflow.python.framework import errors
  def testSizeTooLarge(self):
    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                "overflow"):
      rate = constant_op.constant(1.0, shape=(4, 4, 4, 4, 4))
      self.evaluate(
          random_ops.random_poisson(
              shape=[46902, 51188, 34063, 59195], lam=rate))
CVE-2022-36011 (Other, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `mlir::tfg::ConvertGenericFunctionToFunctionDef` is given empty function attributes, it gives a null dereference. We have patched the issue in GitHub commit 1cf45b831eeb0cab8655c9c7c5d06ec6f45fc41b. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-476 \u2014 NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/ir/importexport/functiondef_import.cc
tensorflow/core/ir/importexport/tests/graphdef_to_mlir/invalid_generic_function_attr_name.pbtxt
Commit message: [tfg][functiondef_import] Emit error on empty function attributes

Disallow empty function attributes. Emit an error when one is encountered.

PiperOrigin-RevId: 448629968


Vulnerable code:

Fixed code:
    if (namedAttr.first.empty())
      return InvalidArgument("Invalid function attribute name");
# RUN: not tfg-translate -graphdef-to-mlir %s 2>&1 | FileCheck %s

# CHECK: Invalid function attribute name

library {
  function {
    signature {
      name: "foo"
      input_arg {
        name: "a"
      }
      output_arg {
        name: "d"
      }
    }
    node_def {
      op: "Const"
      attr {
        key: "_b"
        value {
          placeholder: "T"
        }
      }
      attr {
        key: "dtype"
        value {
          type: DT_INT32
        }
      }
      attr {
        key: "value"
        value {
          tensor {
            dtype: DT_INT32
            tensor_shape {
            }
          }
        }
      }
    }
    ret {
      key: "d"
      value: "a"
    }
    attr {
      key: ""
      value {
        s: "a"
      }
    }
  }
}
CVE-2022-36013 (Other, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `mlir::tfg::GraphDefImporter::ConvertNodeDef` tries to convert NodeDefs without an op name, it crashes. We have patched the issue in GitHub commit a0f0b9a21c9270930457095092f558fbad4c03e5. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-476 \u2014 NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/ir/importexport/graphdef_import.cc
tensorflow/core/ir/importexport/tests/graphdef_to_mlir/invalid_op_name.pbtxt
Commit message: [TF] NodeDefs without an op name are invalid, return error on import

PiperOrigin-RevId: 453711926


Vulnerable code:

Fixed code:
  if (node.op().empty())
    return InvalidArgument("Node ", node.name(), " has an empty op name");

# RUN: not tfg-translate -graphdef-to-mlir %s 2>&1 | FileCheck %s

# CHECK: Node  has an empty op name

library {
  function {
    signature {
      name: "\\344\\264\\264"
      description: "value"
      is_distributed_communication: true
    }
    node_def {
      input: "|"
    }
    control_ret {
      key: ""
      value: ""
    }
  }
}
CVE-2022-36014 (Other, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `mlir::tfg::TFOp::nameAttr` receives null type list attributes, it crashes. We have patched the issue in GitHub commits 3a754740d5414e362512ee981eefba41561a63a6 and a0f0b9a21c9270930457095092f558fbad4c03e5. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-476 \u2014 NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/ir/importexport/graphdef_import.cc
tensorflow/core/ir/importexport/tests/graphdef_to_mlir/invalid_op_name.pbtxt
Commit message: [TF] NodeDefs without an op name are invalid, return error on import

PiperOrigin-RevId: 453711926


Vulnerable code:

Fixed code:
  if (node.op().empty())
    return InvalidArgument("Node ", node.name(), " has an empty op name");

# RUN: not tfg-translate -graphdef-to-mlir %s 2>&1 | FileCheck %s

# CHECK: Node  has an empty op name

library {
  function {
    signature {
      name: "\\344\\264\\264"
      description: "value"
      is_distributed_communication: true
    }
    node_def {
      input: "|"
    }
    control_ret {
      key: ""
      value: ""
    }
  }
}
CVE-2022-36014 (Other, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `mlir::tfg::TFOp::nameAttr` receives null type list attributes, it crashes. We have patched the issue in GitHub commits 3a754740d5414e362512ee981eefba41561a63a6 and a0f0b9a21c9270930457095092f558fbad4c03e5. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-476 \u2014 NULL Pointer Dereference
The product dereferences a pointer that it expects to be valid but is NULL.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/ir/importexport/graphdef_import.cc
tensorflow/core/ir/importexport/tests/graphdef_to_mlir/invalid_backedge_input_size.pbtxt
Commit message: [tfg] Fix null type attribute

Type attributes can be null and the input should be `dyn_cast_or_null`.

PiperOrigin-RevId: 449889247


Vulnerable code:
    if (auto v = attrs.get(arg_def.type_list_attr()).dyn_cast<ArrayAttr>()) {
    if (auto v = attrs.get(arg_def.number_attr()).dyn_cast<IntegerAttr>()) {
    if (auto v = attrs.get(arg_def.type_attr()).dyn_cast<TypeAttr>()) {

Fixed code:
    if (auto v =
            attrs.get(arg_def.type_list_attr()).dyn_cast_or_null<ArrayAttr>()) {
    if (auto v =
            attrs.get(arg_def.number_attr()).dyn_cast_or_null<IntegerAttr>()) {
    if (auto v = attrs.get(arg_def.type_attr()).dyn_cast_or_null<TypeAttr>()) {
# RUN: not tfg-translate -graphdef-to-mlir %s 2>&1 | FileCheck %s

# CHECK: Type attr not found

library {
  function {
    signature {
      name: "\344\264\264"
      description: "value"
      is_distributed_communication: true
    }
    node_def {
      op: "Const"
      input: "|"
    }
    control_ret {
      key: ""
      value: ""
    }
  }
}
CVE-2022-36015 (C++, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `RangeSize` receives values that do not fit into an `int64_t`, it crashes. We have patched the issue in GitHub commit 37e64539cd29fcfb814c4451152a60f5d107b0f0. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-190 \u2014 Integer Overflow or Wraparound
The product performs a calculation that can
         produce an integer overflow or wraparound when the logic
         assumes that the resulting value will always be larger than
         the original value. This occurs when an integer value is
         incremented to a value that is too large to store in the
         associated representation. When this occurs, the value may
         become a very small or negative number.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/ops/math_ops.cc
Commit message: Fix overflow issue

We're also decreasing the test numbers by 1 as the overflow threshold is 1 less.

PiperOrigin-RevId: 449856148


Vulnerable code:
  auto size = (std::is_integral<T>::value
                   ? ((Eigen::numext::abs(limit - start) +
                       Eigen::numext::abs(delta) - T(1)) /
                      Eigen::numext::abs(delta))
                   : (Eigen::numext::ceil(
                         Eigen::numext::abs((limit - start) / delta))));

  // Undefined behaviour if size will not fit into int64_t
  if (size > std::numeric_limits<int64_t>::max()) {
    return errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
                                   std::numeric_limits<int64_t>::max());

Fixed code:
  int64_t size;
  if (std::is_integral<T>::value) {
    size = Eigen::divup(static_cast<int64_t>(Eigen::numext::abs(limit - start)),
                        static_cast<int64_t>(Eigen::numext::abs(delta)));
  } else {
    auto size_auto =
        Eigen::numext::ceil(Eigen::numext::abs((limit - start) / delta));
    if (size_auto > std::numeric_limits<int64_t>::max()) {
      return errors::InvalidArgument("Requires ((limit - start) / delta) <= ",
                                     std::numeric_limits<int64_t>::max());
    }
    size = static_cast<int64_t>(size_auto);
CVE-2022-36016 (C++, published 2022-09-16T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When `tensorflow::full_type::SubstituteFromAttrs` receives a `FullTypeDef& t` that is not exactly three args, it triggers a `CHECK`-fail instead of returning a status. We have patched the issue in GitHub commit 6104f0d4091c260ce9352f9155f7e9b725eab012. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-617 \u2014 Reachable Assertion
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.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/framework/full_type_util.cc
tensorflow/core/framework/full_type_util_test.cc
Commit message: Strengthen input verification for SpecializeType by replacing DCHECK with explicit test/status return.

PiperOrigin-RevId: 453436708


Vulnerable code:
  DCHECK_EQ(t.args_size(), 3);

Fixed code:
  if (t.args_size() != 3) {
    return Status(error::INVALID_ARGUMENT,
                  absl::StrCat("illegal FOR_EACH type, expected 3 args, got ",
                               t.args_size()));
  }
TEST(SpecializeType, ForEachRejectsMalformedInput) {
  OpDef op;
  FullTypeDef* t = op.add_output_arg()->mutable_experimental_full_type();
  t->set_type_id(TFT_FOR_EACH);
  t->add_args()->set_type_id(TFT_PRODUCT);

  NodeDef ndef;
  AttrSlice attrs(ndef);

  FullTypeDef ft;
  EXPECT_FALSE(SpecializeType(attrs, op, ft).ok());
}
CVE-2022-36018 (Python, published 2022-09-16T22:15Z)
Description: value: TensorFlow is an open source platform for machine learning. If `RaggedTensorToVariant` is given a `rt_nested_splits` list that contains tensors of ranks other than one, it results in a `CHECK` fail that can be used to trigger a denial of service attack. We have patched the issue in GitHub commit 88f93dfe691563baa4ae1e80ccde2d5c7a143821. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-617 \u2014 Reachable Assertion
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.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/ragged_tensor_to_variant_op.cc
tensorflow/python/ops/ragged/ragged_tensor_test.py
Commit message: [security] Fix failed shape check in RaggedTensorToVariant.

`row_splits` must have rank 1.

PiperOrigin-RevId: 461915027


Vulnerable code:

Fixed code:
      OP_REQUIRES(context, ragged_nested_splits_in[i].dims() == 1,
                  errors::InvalidArgument("Requires nested_row_splits[", i, "]",
                                          " to be rank 1 but is rank ",
                                          ragged_nested_splits_in[i].dims()));
  def testToVariantInvalidParams(self):
    self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                           r'be rank 1 but is rank 0',
                           gen_ragged_conversion_ops.ragged_tensor_to_variant,
                           rt_nested_splits=[0, 1, 2],
                           rt_dense_values=[0, 1, 2],
                           batched_input=True)

    self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                           r'be rank 1 but is rank 2',
                           gen_ragged_conversion_ops.ragged_tensor_to_variant,
                           rt_nested_splits=[[[0]], [[1]], [[2]]],
                           rt_dense_values=[0, 1, 2],
                           batched_input=True)
CVE-2022-41880 (Python, published 2022-11-18T22:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When the `BaseCandidateSamplerOp` function receives a value in `true_classes` larger than `range_max`, a heap oob read occurs. We have patched the issue in GitHub commit b389f5c944cadfdfe599b3f1e4026e036f30d2d4. 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.
Severity: nan (CVSS v3 base score: 9.1)
Weakness: CWE-125 \u2014 Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/candidate_sampler_ops.cc
tensorflow/python/kernel_tests/random/candidate_sampler_ops_test.py
Commit message: Add true_classes input validation for candidate sampler ops.

The values must be within the valid range of the sampler.  Added a
check for this.

PiperOrigin-RevId: 479441496


Vulnerable code:

Fixed code:

    for (const auto& candidate : true_candidate) {
      OP_REQUIRES(context, candidate >= 0 && candidate < sampler_->range(),
                  errors::InvalidArgument("`true_candidate` out of range [", 0,
                                          ", ", sampler_->range(),
                                          "), received ", candidate));
    }

from tensorflow.python.framework import errors
  def testCandidateOutOfRange(self):
    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                "out of range"):
      self.evaluate(
          candidate_sampling_ops.log_uniform_candidate_sampler(
              true_classes=[[0, 10]],
              num_true=2,
              num_sampled=1000,
              unique=False,
              range_max=2))

    with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
                                "out of range"):
      self.evaluate(
          candidate_sampling_ops.log_uniform_candidate_sampler(
              true_classes=[[0, -10]],
              num_true=2,
              num_sampled=1000,
              unique=False,
              range_max=2))
CVE-2022-41883 (Python, published 2022-11-18T21:15Z)
Description: value: TensorFlow is an open source platform for machine learning. When ops that have specified input sizes receive a differing number of inputs, the executor will crash. We have patched the issue in GitHub commit f5381e0e10b5a61344109c1b7c174c68110f7629. 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-125 \u2014 Out-of-bounds Read
The product reads data past the end, or before the beginning, of the intended buffer.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/common_runtime/eager/execute.cc
tensorflow/python/kernel_tests/data_structures/dynamic_stitch_op_test.py
Commit message: Fix OOB error when op input sizes do not match.

In cases where op input sizes are specified as in
```
REGISTER_OP("DynamicStitch")
    .Input("indices: N * int32")
    .Input("data: N * T")
    .Output("merged: T")
    .Attr("N : int >= 1")
    .Attr("T : type")
    .SetShapeFn(DynamicStitchShapeFunction);
```
if differing number of inputs are provided (e.g. 3 for `indices` and 4 for `data`)
we can get a crash in the executor when parsing the inputs, even before the kernel
called.  Here we avoid this by checking the return code for the argument id and
exit early.

PiperOrigin-RevId: 478068540


Vulnerable code:

Fixed code:
  // Fail if argument ID not found.
  if (arg_id < 0) {
    return false;
  }
from tensorflow.python.framework import errors
  @test_util.run_in_graph_and_eager_modes
  def testMismatchedDataAndIndexListSizes(self):
    indices = [
        constant_op.constant([2]),
        constant_op.constant([1]),
        constant_op.constant([0]),
        constant_op.constant([3]),
    ]
    data = [
        constant_op.constant([1.0]),
        constant_op.constant([2.0]),
        constant_op.constant([3.0]),
        constant_op.constant([4.0])
    ]
    with self.assertRaisesRegex(
        (ValueError, errors.InvalidArgumentError),
        "expected inputs .* do not match|List argument .* must match"):
      self.evaluate(data_flow_ops.dynamic_stitch(indices[0:2], data))

    with self.assertRaisesRegex(
        (ValueError, errors.InvalidArgumentError),
        "expected inputs .* do not match|List argument .* must match"):
      self.evaluate(data_flow_ops.dynamic_stitch(indices, data[0:2]))
CVE-2022-41884 (Other, published 2022-11-18T22:15Z)
Description: 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.
Severity: nan (CVSS v3 base score: 7.5)
Weakness: CWE-670 \u2014 Always-Incorrect Control Flow Implementation
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.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/python/eager/tensor_test.py
tensorflow/python/lib/core/BUILD
tensorflow/python/lib/core/ndarray_tensor_bridge.cc
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


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, "]");
  }