hitoshura25/cvefixes huggingface dataset:
CVE-2022-29205 (C++, published 2022-05-20T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, there is a potential for segfault / denial of service in TensorFlow by calling `tf.compat.v1.*` ops which don't yet have support for quantized types, which was added after migration to TensorFlow 2.x. In these scenarios, since the kernel is missing, a `nullptr` value is passed to `ParseDimensionValue` for the `py_value` argument. Then, this is dereferenced, resulting in segfault. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.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/kernels/strided_slice_op.cc
tensorflow/core/kernels/strided_slice_op_impl.h
tensorflow/python/eager/pywrap_tfe_src.cc
Commit message: Fix tf.compat.v1.placeholder_with_default vulnerability with quantized types.

When iterating through the tensor to extract shape values, an underlying missing kernel
(`StridedSlice` for quantized types) causes an error, which then results in a `nullptr`
being passed to `ParseDimensionValue()`, causing a segfault.

The `nullptr` check allows the missing kernel error to propagate.
Adding the missing kernel registrations allows the shape values
to be extracted successfully.

PiperOrigin-RevId: 445045957


Vulnerable code:

        } else if (!ParseDimensionValue(key, inner_py_value.get(), status,

Fixed code:
TF_CALL_QUANTIZED_TYPES(REGISTER_STRIDED_SLICE);
TF_CALL_QUANTIZED_TYPES(DECLARE_FOR_N_CPU);
        // If an error is generated when iterating through object, we can
        // sometimes get a nullptr.
        } else if (inner_py_value.get() == nullptr ||
                   !ParseDimensionValue(key, inner_py_value.get(), status,
CVE-2022-29205 (C++, published 2022-05-20T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, there is a potential for segfault / denial of service in TensorFlow by calling `tf.compat.v1.*` ops which don't yet have support for quantized types, which was added after migration to TensorFlow 2.x. In these scenarios, since the kernel is missing, a `nullptr` value is passed to `ParseDimensionValue` for the `py_value` argument. Then, this is dereferenced, resulting in segfault. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-908 \u2014 Use of Uninitialized Resource
The product uses or accesses a resource that has not been initialized.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/strided_slice_op.cc
tensorflow/core/kernels/strided_slice_op_impl.h
tensorflow/python/eager/pywrap_tfe_src.cc
Commit message: Fix tf.compat.v1.placeholder_with_default vulnerability with quantized types.

When iterating through the tensor to extract shape values, an underlying missing kernel
(`StridedSlice` for quantized types) causes an error, which then results in a `nullptr`
being passed to `ParseDimensionValue()`, causing a segfault.

The `nullptr` check allows the missing kernel error to propagate.
Adding the missing kernel registrations allows the shape values
to be extracted successfully.

PiperOrigin-RevId: 445045957


Vulnerable code:

        } else if (!ParseDimensionValue(key, inner_py_value.get(), status,

Fixed code:
TF_CALL_QUANTIZED_TYPES(REGISTER_STRIDED_SLICE);
TF_CALL_QUANTIZED_TYPES(DECLARE_FOR_N_CPU);
        // If an error is generated when iterating through object, we can
        // sometimes get a nullptr.
        } else if (inner_py_value.get() == nullptr ||
                   !ParseDimensionValue(key, inner_py_value.get(), status,
CVE-2022-29207 (C++, published 2022-05-20T22:16Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, multiple TensorFlow operations misbehave in eager mode when the resource handle provided to them is invalid. In graph mode, it would have been impossible to perform these API calls, but migration to TF 2.x eager mode opened up this vulnerability. If the resource handle is empty, then a reference is bound to a null pointer inside TensorFlow codebase (various codepaths). This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-20 \u2014 Improper Input Validation
The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/common_runtime/eager/execute.cc
Commit message: Fix empty resource handle vulnerability.

Some ops that attempt to extract a resource handle from user input
can lead to nullptr dereferences.  This returns an error in such
a case.

PiperOrigin-RevId: 445571938


Vulnerable code:

Fixed code:
    if (tensor->NumElements() == 0) {
      return errors::InvalidArgument("Empty resource handle");
    }
CVE-2022-29207 (C++, published 2022-05-20T22:16Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, multiple TensorFlow operations misbehave in eager mode when the resource handle provided to them is invalid. In graph mode, it would have been impossible to perform these API calls, but migration to TF 2.x eager mode opened up this vulnerability. If the resource handle is empty, then a reference is bound to a null pointer inside TensorFlow codebase (various codepaths). This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-475 \u2014 Undefined Behavior for Input to API
The behavior of this function is undefined unless its control parameter is set to a specific value.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/common_runtime/eager/execute.cc
Commit message: Fix empty resource handle vulnerability.

Some ops that attempt to extract a resource handle from user input
can lead to nullptr dereferences.  This returns an error in such
a case.

PiperOrigin-RevId: 445571938


Vulnerable code:

Fixed code:
    if (tensor->NumElements() == 0) {
      return errors::InvalidArgument("Empty resource handle");
    }
CVE-2022-29207 (Python, published 2022-05-20T22:16Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, multiple TensorFlow operations misbehave in eager mode when the resource handle provided to them is invalid. In graph mode, it would have been impossible to perform these API calls, but migration to TF 2.x eager mode opened up this vulnerability. If the resource handle is empty, then a reference is bound to a null pointer inside TensorFlow codebase (various codepaths). This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-20 \u2014 Improper Input Validation
The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/python/kernel_tests/summary_ops/summary_ops_test.py
tensorflow/python/ops/summary_ops_v2.py
Commit message: Fix segfault from passing invalid input to tf.summary.flush()

This removes an obsolete legacy codepath from tf.summary.flush(). Because that codepath was still used by tpu_estimator.py, for now, we preserve a copy of the legacy codepath and update tpu_estimator.py to use it.

PiperOrigin-RevId: 441606843


Vulnerable code:
        summary_ops.write('tag', 1, step=0)
        self.assertEqual(4, get_total())
        summary_ops.flush(writer=writer._resource)  # pylint:disable=protected-access
        self.assertEqual(5, get_total())

Fixed code:

  # Regression test for b/228097117.
  def testFlushFunction_disallowsInvalidWriterInput(self):
    with context.eager_mode():
      with self.assertRaisesRegex(ValueError, 'Invalid argument to flush'):
        summary_ops.flush(writer=())
  del name  # unused
  raise ValueError("Invalid argument to flush(): %r" % (writer,))


def legacy_raw_flush(writer=None, name=None):
  """Legacy version of flush() that accepts a raw resource tensor for `writer`.

  Do not use this function in any new code. Not supported and not part of the
  public TF APIs.

  Args:
    writer: The `tf.summary.SummaryWriter` to flush. If None, the current
      default writer will be used instead; if there is no current writer, this
      returns `tf.no_op`. For this legacy version only, also accepts a raw
      resource tensor pointing to the underlying C++ writer resource.
    name: Ignored legacy argument for a name for the operation.

  Returns:
    The created `tf.Operation`.
  """
  if writer is None or isinstance(writer, SummaryWriter):
    # Forward to the TF2 implementation of flush() when possible.
    return flush(writer, name)
CVE-2022-29207 (Python, published 2022-05-20T22:16Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, multiple TensorFlow operations misbehave in eager mode when the resource handle provided to them is invalid. In graph mode, it would have been impossible to perform these API calls, but migration to TF 2.x eager mode opened up this vulnerability. If the resource handle is empty, then a reference is bound to a null pointer inside TensorFlow codebase (various codepaths). This is undefined behavior. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-475 \u2014 Undefined Behavior for Input to API
The behavior of this function is undefined unless its control parameter is set to a specific value.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/python/kernel_tests/summary_ops/summary_ops_test.py
tensorflow/python/ops/summary_ops_v2.py
Commit message: Fix segfault from passing invalid input to tf.summary.flush()

This removes an obsolete legacy codepath from tf.summary.flush(). Because that codepath was still used by tpu_estimator.py, for now, we preserve a copy of the legacy codepath and update tpu_estimator.py to use it.

PiperOrigin-RevId: 441606843


Vulnerable code:
        summary_ops.write('tag', 1, step=0)
        self.assertEqual(4, get_total())
        summary_ops.flush(writer=writer._resource)  # pylint:disable=protected-access
        self.assertEqual(5, get_total())

Fixed code:

  # Regression test for b/228097117.
  def testFlushFunction_disallowsInvalidWriterInput(self):
    with context.eager_mode():
      with self.assertRaisesRegex(ValueError, 'Invalid argument to flush'):
        summary_ops.flush(writer=())
  del name  # unused
  raise ValueError("Invalid argument to flush(): %r" % (writer,))


def legacy_raw_flush(writer=None, name=None):
  """Legacy version of flush() that accepts a raw resource tensor for `writer`.

  Do not use this function in any new code. Not supported and not part of the
  public TF APIs.

  Args:
    writer: The `tf.summary.SummaryWriter` to flush. If None, the current
      default writer will be used instead; if there is no current writer, this
      returns `tf.no_op`. For this legacy version only, also accepts a raw
      resource tensor pointing to the underlying C++ writer resource.
    name: Ignored legacy argument for a name for the operation.

  Returns:
    The created `tf.Operation`.
  """
  if writer is None or isinstance(writer, SummaryWriter):
    # Forward to the TF2 implementation of flush() when possible.
    return flush(writer, name)
CVE-2022-29209 (Unknown, published 2022-05-21T00:15Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the macros that TensorFlow uses for writing assertions (e.g., `CHECK_LT`, `CHECK_GT`, etc.) have an incorrect logic when comparing `size_t` and `int` values. Due to type conversion rules, several of the macros would trigger incorrectly. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-843 \u2014 Access of Resource Using Incompatible Type ('Type Confusion')
The product allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
Commit message: Merge pull request #55730 from graphcore:awf/issue-55530

PiperOrigin-RevId: 445252025


Vulnerable code:

Fixed code:
CVE-2022-29210 (Other, published 2022-05-21T00:15Z)
Description: value: TensorFlow is an open source platform for machine learning. In version 2.8.0, the `TensorKey` hash function used total estimated `AllocatedBytes()`, which (a) is an estimate per tensor, and (b) is a very poor hash function for constants (e.g. `int32_t`). It also tried to access individual tensor bytes through `tensor.data()` of size `AllocatedBytes()`. This led to ASAN failures because the `AllocatedBytes()` is an estimate of total bytes allocated by a tensor, including any pointed-to constructs (e.g. strings), and does not refer to contiguous bytes in the `.data()` buffer. The discoverers could not use this byte vector anyway because types such as `tstring` include pointers, whereas they needed to hash the string values themselves. This issue is patched in Tensorflow versions 2.9.0 and 2.8.1.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-787 \u2014 Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/framework/tensor_key.h
tensorflow/python/kernel_tests/data_structures/BUILD
Commit message: Fix TensorKey hash function.

The original hash function only used total estimated `AllocatedBytes()`, which (a) is an estimate per tensor, and (b) is a very poor hash function for constants (e.g. `int32_t`).
It also tried to access individual tensor bytes through `tensor.data()` of size `AllocatedBytes()`.  This led to ASAN failures because the `AllocatedBytes()` is an estimate of total bytes allocated by a tensor, including any pointed-to constructs (e.g. strings), and does not refer to contiguous bytes in the `.data()` buffer.  We couldn't use this byte vector anyways, since types like `tstring` include pointers, whereas we need to hash the string values themselves.

Modified the hash function to more closely mirror the `==` operator.  This correctly handles `tstring` and any numeric types that do have contiguous storage.  Other types are currently left as unimplemented.

PiperOrigin-RevId: 446265413


Vulnerable code:
    }
    if (t1.dtype() == DT_STRING) {
    const uint8* d = static_cast<uint8*>(k.data());
    size_t s = k.AllocatedBytes();
    std::vector<uint8> vec;
    vec.reserve(s);
    for (int i = 0; i < s; i++) {
      vec.push_back(d[i]);
    return H::combine(std::move(h), s);
        "noasan",  # TODO(b/164696004)
        "notsan",  # TODO(b/164696004)

Fixed code:
#include "tensorflow/core/framework/types.h"
    } else if (t1.dtype() == DT_STRING) {
    } else {
      DCHECK(false) << "Unimplemented dtype " << DataTypeString(t1.dtype())
                    << std::endl;
    if (DataTypeCanUseMemcpy(k.dtype())) {
      return H::combine(std::move(h), k.tensor_data());
    } else if (k.dtype() == DT_STRING) {
      const auto strs = k.unaligned_flat<tstring>();
      for (int64_t i = 0, n = k.NumElements(); i < n; ++i) {
        h = H::combine(std::move(h), strs(i));
      }
      return h;
    } else {
      DCHECK(false) << "Unimplemented dtype " << DataTypeString(k.dtype())
                    << std::endl;
    return h;
CVE-2022-29211 (C++, published 2022-05-21T00:15Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the implementation of `tf.histogram_fixed_width` is vulnerable to a crash when the values array contain `Not a Number` (`NaN`) elements. The implementation assumes that all floating point operations are defined and then converts a floating point result to an integer index. If `values` contains `NaN` then the result of the division is still `NaN` and the cast to `int32` would result in a crash. This only occurs on the CPU implementation. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-20 \u2014 Improper Input Validation
The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/histogram_op.cc
Commit message: Prevent crash when histogram is called with NaN values.

Fixes #45770

PiperOrigin-RevId: 443149951


Vulnerable code:
        ctx, (value_range(0) < value_range(1)),
        ctx, (nbins > 0),

Fixed code:
    // We cannot handle NANs in the algorithm below (due to the case to int32)
    const Eigen::Tensor<int32, 1, 1> nans_tensor =
        values.isnan().template cast<int32>();
    const Eigen::Tensor<int32, 0, 1> reduced_tensor = nans_tensor.sum();
    const int num_nans = reduced_tensor(0);
    if (num_nans > 0) {
      return errors::InvalidArgument("Histogram values must not contain NaN");
    }

        ctx, value_range(0) < value_range(1),
        ctx, nbins > 0,
CVE-2022-29212 (C++, published 2022-05-21T00:15Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, certain TFLite models that were created using TFLite model converter would crash when loaded in the TFLite interpreter. The culprit is that during quantization the scale of values could be greater than 1 but code was always assuming sub-unit scaling. Thus, since code was calling `QuantizeMultiplierSmallerThanOneExp`, the `TFLITE_CHECK_LT` assertion would trigger and abort the process. Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.5)
Weakness: CWE-20 \u2014 Improper Input Validation
The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/lite/kernels/comparisons.cc
tensorflow/lite/kernels/comparisons_test.cc
Commit message: Improve to cover scale value greater than one

PiperOrigin-RevId: 433050921


Vulnerable code:
    int input1_shift;
    QuantizeMultiplierSmallerThanOneExp(input1->params.scale,
                                        &input1_multiplier, &input1_shift);
    QuantizeMultiplierSmallerThanOneExp(input2->params.scale,
                                        &input2_multiplier, &input2_shift);

Fixed code:
void QuantizeMultiplier(double double_multiplier, int32_t* quantized_multiplier,
                        int* left_shift) {
  if (double_multiplier < 1.0) {
    QuantizeMultiplierSmallerThanOneExp(double_multiplier, quantized_multiplier,
                                        left_shift);
  } else {
    QuantizeMultiplierGreaterThanOne(double_multiplier, quantized_multiplier,
                                     left_shift);
  }
}

    int input1_shift;
    QuantizeMultiplier(input1->params.scale, &input1_multiplier, &input1_shift);
    QuantizeMultiplier(input2->params.scale, &input2_multiplier, &input2_shift);
TEST(ComparisonsTest,
     QuantizedInt8GreaterWithBroadcastMultiplierGreaterThanOne) {
  const float kMin = -127.f;
  const float kMax = 127.f;
  std::vector<std::vector<int>> test_shapes = {
      {6}, {2, 3}, {2, 1, 3}, {1, 3, 1, 2}};
  for (int i = 0; i < test_shapes.size(); ++i) {
    ComparisonOpModel model({TensorType_INT8, test_shapes[i], kMin, kMax},
                            {TensorType_INT8, {}, kMin, kMax}, TensorType_INT8,
                            BuiltinOperator_GREATER);
    model.QuantizeAndPopulate<int8_t>(model.input1(),
                                      {572, -2, -71, 8, 11, 20});
    model.QuantizeAndPopulate<int8_t>(model.input2(), {8});
    model.Invoke();
    EXPECT_THAT(model.GetOutput(),
                ElementsAre(true, false, false, false, true, true))
        << "With shape number " << i;
  }
}
CVE-2022-29213 (Python, published 2022-05-21T00:15Z)
Description: value: TensorFlow is an open source platform for machine learning. Prior to versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4, the `tf.compat.v1.signal.rfft2d` and `tf.compat.v1.signal.rfft3d` lack input validation and under certain condition can result in crashes (due to `CHECK`-failures). Versions 2.9.0, 2.8.1, 2.7.2, and 2.6.4 contain a patch for this issue.
Severity: LOW (CVSS v3 base score: 5.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/fft_ops.cc
tensorflow/python/kernel_tests/signal/fft_ops_test.py
Commit message: Merge pull request #55274 from yongtang:55263-tf.signal.rfft2d

PiperOrigin-RevId: 436736690


Vulnerable code:

Fixed code:
+        OP_REQUIRES(ctx, fft_length_as_vec(i) >= 0,
+                    errors::InvalidArgument(
+                        "fft_length[", i,
+                        "] must >= 0, but got: ", fft_length_as_vec(i)));
   def test_invalid_args(self):
     # Test case for GitHub issue 55263
     a = np.empty([6, 0])
     b = np.array([1, -1])
+    with self.assertRaisesRegex(errors.InvalidArgumentError, "must >= 0"):
       with self.session():
+        v = fft_ops.rfft2d(input_tensor=a, fft_length=b)
         self.evaluate(v)