hitoshura25/cvefixes huggingface dataset:
CVE-2022-21731 (Python, published 2022-02-03T12:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of shape inference for `ConcatV2` can be used to trigger a denial of service attack via a segfault caused by a type confusion. The `axis` argument is translated into `concat_dim` in the `ConcatShapeHelper` helper function. Then, a value for `min_rank` is computed based on `concat_dim`. This is then used to validate that the `values` tensor has at least the required rank. However, `WithRankAtLeast` receives the lower bound as a 64-bits value and then compares it against the maximum 32-bits integer value that could be represented. Due to the fact that `min_rank` is a 32-bits value and the value of `axis`, the `rank` argument is a negative value, so the error check is bypassed. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.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:
tensorflow/core/framework/common_shape_fns.cc
tensorflow/python/kernel_tests/array_ops/concat_op_test.py
Commit message: Fix Segfault in Concat V2 shape function.

PiperOrigin-RevId: 412120654
Change-Id: I3ff915faea694f9ad8b00024e9af2de9909011be


Vulnerable code:
  const int min_rank = concat_dim < 0 ? -concat_dim : concat_dim + 1;

Fixed code:
  const int64 min_rank = concat_dim < 0 ? -concat_dim : concat_dim + 1;
from tensorflow.python.eager import def_function
  def testConcatInvalidAxisInTfFunction(self):

    @def_function.function
    def concat_wrapper():
      y = gen_array_ops.concat_v2(
          values=[[1, 2, 3], [4, 5, 6]], axis=0xb500005b)
      return y

    with self.assertRaises(ValueError):
      concat_wrapper()
CVE-2022-21732 (C++, published 2022-02-03T12:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `ThreadPoolHandle` can be used to trigger a denial of service attack by allocating too much memory. This is because the `num_threads` argument is only checked to not be negative, but there is no upper bound on its value. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.5)
Weakness: CWE-770 \u2014 Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/data/experimental/threadpool_dataset_op.cc
Commit message: [tf.data] Set limit on number of threads used in threadpool_dataset.

PiperOrigin-RevId: 410922677
Change-Id: Ib25814a99043ab10805b5d2d7088ae0e0b7b04fd


Vulnerable code:
    OP_REQUIRES(
        ctx, num_threads_ > 0,
        errors::InvalidArgument("`num_threads` must be greater than zero."));
  OP_REQUIRES(ctx, num_threads >= 0,
              errors::InvalidArgument("`num_threads` must be >= 0"));
  OP_REQUIRES(ctx, num_threads >= 0,
              errors::InvalidArgument("`num_threads` must be >= 0"));

Fixed code:
namespace {
// To prevent integer overflow issues when allocating threadpool memory for an
// unreasonable number of threads.
constexpr int kThreadLimit = 65536;

Status ValidateNumThreads(int32_t num_threads) {
  if (num_threads < 0) {
    return errors::InvalidArgument("`num_threads` must be >= 0");
  }
  if (num_threads >= kThreadLimit) {
    return errors::InvalidArgument("`num_threads` must be < ", kThreadLimit);
  }
  return Status::OK();
}
}  // namespace

    OP_REQUIRES_OK(ctx, ValidateNumThreads(num_threads_));
  OP_REQUIRES_OK(ctx, ValidateNumThreads(num_threads));
  OP_REQUIRES_OK(ctx, ValidateNumThreads(num_threads));
CVE-2022-21733 (Python, published 2022-02-03T12:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `StringNGrams` can be used to trigger a denial of service attack by causing an out of memory condition after an integer overflow. We are missing a validation on `pad_witdh` and that result in computing a negative value for `ngram_width` which is later used to allocate parts of the output. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.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/kernels/string_ngrams_op.cc
tensorflow/python/ops/raw_ops_test.py
Commit message: Add a check for pad width to be a positive value.

PiperOrigin-RevId: 413275853
Change-Id: I261a8db9dabf5ce48a806a9e58129080c9fac619


Vulnerable code:
@test_util.disable_tfrt
    with self.assertRaisesRegex(errors.InvalidArgumentError,
                                "Invalid split value"):

Fixed code:

        // If reached here, pad_width should be > 0, pad_width_ = -1,
        // which indicates max(ngram_widths) - 1 cannot be used here since
        // ngram_width is not known.
        OP_REQUIRES(
            context, pad_width_ >= 0,
            errors::InvalidArgument("Pad width should be >= 0 when "
                                    "preserve_short_sequences is True and "
                                    "ngram_widths are not provided, got ",
                                    pad_width_));
    with self.assertRaisesRegex(
        errors.InvalidArgumentError,
        r"Invalid split value|First split value must be 0"):
  def testStringSplit(self):
    data = ["123456"]
    data_splits = [0, 1]
    separator = "a" * 15
    ngram_widths = []
    pad_width = -5
    left_pad = right_pad = ""
    with self.assertRaisesRegex(errors.InvalidArgumentError,
                                "Pad width should be >= 0"):
      self.evaluate(gen_string_ops.string_n_grams(
          data=data,
          data_splits=data_splits,
          separator=separator,
          ngram_widths=ngram_widths,
          left_pad=left_pad,
          right_pad=right_pad,
          pad_width=pad_width,
          preserve_short_sequences=True))
CVE-2022-21735 (Python, published 2022-02-03T13:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `FractionalMaxPool` can be made to crash a TensorFlow process via a division by 0. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.5)
Weakness: CWE-369 \u2014 Divide By Zero
The product divides a value by zero.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/core/kernels/fractional_max_pool_op.cc
tensorflow/python/kernel_tests/nn_ops/fractional_max_pool_op_test.py
Commit message: Fix potential divide by zero error when executing FractionalMaxPool, when pooling ratio is higher than input size for a particular dimension.

PiperOrigin-RevId: 412151722
Change-Id: I06e57cbb8eca43816eff79eac264fa7aae8f7163


Vulnerable code:

Fixed code:

      OP_REQUIRES(
          context, input_size[i] >= pooling_ratio_[i],
          errors::InvalidArgument("Pooling ratio is higher than input "
                                  "dimension size for dimension ",
                                  i, ". Input dim size: ", input_size[i],
                                  " pooling ratio: ", pooling_ratio_[i]));
from tensorflow.python.framework import errors
  def testPoolingRatio(self):
    with self.cached_session() as _:
      with self.assertRaisesRegex(
          errors.InvalidArgumentError,
          r"Pooling ratio is higher than input dimension size for dimension 1.*"
      ):
        result = nn_ops.gen_nn_ops.fractional_max_pool(
            value=constant_op.constant(
                value=[[[[1, 4, 2, 3]]]], dtype=dtypes.int64),
            pooling_ratio=[1.0, 1.44, 1.73, 1.0],
            pseudo_random=False,
            overlapping=False,
            deterministic=False,
            seed=0,
            seed2=0,
            name=None)
        self.evaluate(result)
CVE-2022-21738 (C++, published 2022-02-03T14:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseCountSparseOutput` can be made to crash a TensorFlow process by an integer overflow whose result is then used in a memory allocation. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.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/kernels/count_ops.cc
Commit message: Prevent crash due to integer overflow followed by allocating negative sized array.

PiperOrigin-RevId: 414891322
Change-Id: I5df390e0dc1d9f115209293708950cdf9306931c


Vulnerable code:

Fixed code:
#include <limits>

// Don't allocate too large `BatchedMap<T>` objects
static int kMaxBatches = std::numeric_limits<int>::max();

    OP_REQUIRES(
        context, 0 < num_batches && num_batches < kMaxBatches,
        errors::InvalidArgument("Cannot allocate ", num_batches,
                                " batches, is the dense shape too wide?"));
CVE-2022-21739 (C++, published 2022-02-03T14:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `QuantizedMaxPool` has an undefined behavior where user controlled inputs can trigger a reference binding to null pointer. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.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/quantized_pooling_ops.cc
Commit message: Fix nullptr exception in QuantizedMaxPool op when empty list is sent to min_input or max_input parameters.

PiperOrigin-RevId: 413960973
Change-Id: I9e3ded593f3c4eabf0d6d5dc356e6a19a3ad2682


Vulnerable code:

Fixed code:
#include "tensorflow/core/framework/op_requires.h"
#include "tensorflow/core/platform/errors.h"
    auto min_input_tensor = context->input(1);
    auto max_input_tensor = context->input(2);
    OP_REQUIRES(
        context, min_input_tensor.NumElements() == 1,
        errors::InvalidArgument(
            "min_input must be a scalar float value, got tensor with shape ",
            min_input_tensor.shape()));
    OP_REQUIRES(
        context, max_input_tensor.NumElements() == 1,
        errors::InvalidArgument(
            "max_input must be a scalar float value, got tensor with shape ",
            max_input_tensor.shape()));
CVE-2022-21740 (C++, published 2022-02-03T15:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `SparseCountSparseOutput` is vulnerable to a heap overflow. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 8.8)
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/kernels/count_ops.cc
Commit message: Further validate sparse tensor for `SparseCount`: indices must be valid within dense shape.

PiperOrigin-RevId: 414888122
Change-Id: I4552bd74c135ecd4bcb5448acc0a3ce9402d8286


Vulnerable code:
    auto shape_vector = shape.flat<int64_t>();
    int num_values = values.NumElements();
    const auto indices_values = indices.matrix<int64_t>();

Fixed code:
    // Validate indices: each index must be valid for the corresponding
    // dimension. This could be possibly done better.
    const auto indices_values = indices.matrix<int64_t>();
    const auto shape_vector = shape.vec<int64_t>();
    int num_values = values.NumElements();  // same as first dim of indices
    int rank = indices.shape().dim_size(1);
    for (int i = 0; i < num_values; ++i) {
      for (int j = 0; j < rank; ++j) {
        OP_REQUIRES(
            context,
            indices_values(i, j) >= 0 && indices_values(i, j) < shape_vector(j),
            errors::InvalidArgument(
                "Invalid index value at ", i, ": dimension ", j, " has value ",
                indices_values(i, j), " which is not in [0, ", shape_vector(j),
                ") (as given by dense shape ", shape.DebugString()));
      }
    }
CVE-2022-21741 (C++, published 2022-02-03T15:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. ### Impact An attacker can craft a TFLite model that would trigger a division by zero in the implementation of depthwise convolutions. The parameters of the convolution can be user controlled and are also used within a division operation to determine the size of the padding that needs to be added before applying the convolution. There is no check before this division that the divisor is strictly positive. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.5)
Weakness: CWE-369 \u2014 Divide By Zero
The product divides a value by zero.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/lite/kernels/depthwise_conv.cc
Commit message: [lite] Add validation check for dilation height/width to be positive integers.

PiperOrigin-RevId: 416429178
Change-Id: If7cdcddca54486434d9b2f06e7e2b401d7c3ee25


Vulnerable code:

Fixed code:
  TF_LITE_ENSURE(context, params->dilation_height_factor > 0);
  TF_LITE_ENSURE(context, params->dilation_width_factor > 0);
CVE-2022-23557 (C, published 2022-02-04T23:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would trigger a division by zero in `BiasAndClamp` implementation. There is no check that the `bias_size` is non zero. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 6.5)
Weakness: CWE-369 \u2014 Divide By Zero
The product divides a value by zero.
Repository: https://github.com/tensorflow/tensorflow
Files changed:
tensorflow/lite/kernels/internal/common.h
Commit message: [lite] Add check for bias_size is zero to avoid division by zero. This shouldn't happen for properly converted models. Just safety check

PiperOrigin-RevId: 416383645
Change-Id: If8e508bf696ae8ecfb927e69c139a8ccf7fe60cb


Vulnerable code:

Fixed code:
  if (bias_size == 0) return;
CVE-2022-23558 (C, published 2022-02-04T23:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in `TfLiteIntArrayCreate`. The `TfLiteIntArrayGetSizeInBytes` returns an `int` instead of a `size_t. An attacker can control model inputs such that `computed_size` overflows the size of `int` datatype. The fix will be included in TensorFlow 2.8.0. We will also cherrypick this commit on TensorFlow 2.7.1, TensorFlow 2.6.3, and TensorFlow 2.5.3, as these are also affected and still in supported range.
Severity: MEDIUM (CVSS v3 base score: 8.8)
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/lite/c/common.c
tensorflow/lite/c/common.h
Commit message: [lite] Update TfLiteIntArrayCreate to return size_t

PiperOrigin-RevId: 416439896
Change-Id: I847f69b68d1ddaff4b1e925a09b8b69c1756653b


Vulnerable code:
int TfLiteIntArrayGetSizeInBytes(int size) {
  int computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size;
  int alloc_size = TfLiteIntArrayGetSizeInBytes(size);
int TfLiteIntArrayGetSizeInBytes(int size);

Fixed code:
size_t TfLiteIntArrayGetSizeInBytes(int size) {
  size_t computed_size = sizeof(dummy) + sizeof(dummy.data[0]) * size;
  size_t alloc_size = TfLiteIntArrayGetSizeInBytes(size);
size_t TfLiteIntArrayGetSizeInBytes(int size);
CVE-2022-23559 (C++, published 2022-02-04T23:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in embedding lookup operations. Both `embedding_size` and `lookup_size` are products of values provided by the user. Hence, a malicious user could trigger overflows in the multiplication. In certain scenarios, this can then result in heap OOB read/write. Users are advised to upgrade to a patched version.
Severity: MEDIUM (CVSS v3 base score: 8.8)
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/lite/kernels/embedding_lookup_sparse.cc
Commit message: Prevent segfault in `embedding_lookup_sparse.cc`

Previous fixes missed one additional case.

PiperOrigin-RevId: 417676944
Change-Id: I8ab412155cf9b1e897448a6611d209eaa7ca9e66


Vulnerable code:

Fixed code:
  const size_t values_size = NumElements(value);
      // only index if indices are valid
      if (current_output_offset + k < 0) continue;
      if (current_output_offset + k >= output_size) continue;
      if (example_embedding_offset + k < 0) continue;
      if (example_embedding_offset + k >= values_size) continue;
CVE-2022-23559 (C++, published 2022-02-04T23:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. An attacker can craft a TFLite model that would cause an integer overflow in embedding lookup operations. Both `embedding_size` and `lookup_size` are products of values provided by the user. Hence, a malicious user could trigger overflows in the multiplication. In certain scenarios, this can then result in heap OOB read/write. Users are advised to upgrade to a patched version.
Severity: MEDIUM (CVSS v3 base score: 8.8)
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/lite/kernels/embedding_lookup_sparse.cc
Commit message: [lite] Check for overflow when creating required bytes.

PiperOrigin-RevId: 417629001
Change-Id: Ia7feb3ea8e988f4fd4b3c98c1a1fed4557d99fd7


Vulnerable code:
  int embedding_size = 1;
  int lookup_size = 1;
    const int dim = dense_shape->data.i32[i];
    lookup_size *= dim;
    const int dim = SizeOfDimension(value, i);
    embedding_size *= dim;
  const int output_size = lookup_size * embedding_size;

Fixed code:
#include "tensorflow/lite/util.h"
  size_t embedding_size = 1;
  size_t lookup_size = 1;
    const size_t dim = dense_shape->data.i32[i];
    TF_LITE_ENSURE_MSG(
        context,
        MultiplyAndCheckOverflow(lookup_size, dim, &lookup_size) == kTfLiteOk,
        "Lookup size overflowed.");
    const size_t dim = SizeOfDimension(value, i);
    TF_LITE_ENSURE_MSG(context,
                       MultiplyAndCheckOverflow(embedding_size, dim,
                                                &embedding_size) == kTfLiteOk,
                       "Embedding size overflowed.");
  const size_t output_size = lookup_size * embedding_size;
  // Makes sure reallocation was successful.
  TF_LITE_ENSURE(context, output_ptr != nullptr);