hitoshura25/cvefixes huggingface dataset:
CVE-2021-41224 (C++, published 2021-11-05T21:15Z)
Description: value: TensorFlow is an open source platform for machine learning. In affected versions the implementation of `SparseFillEmptyRows` can be made to trigger a heap OOB access. This occurs whenever the size of `indices` does not match the size of `values`. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.
Severity: LOW (CVSS v3 base score: 7.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/sparse_fill_empty_rows_op.cc
Commit message: Make SparseFillEmptyRows validate that the length of `values` must be equal to the number of index tuples.

PiperOrigin-RevId: 399969549
Change-Id: I3c2f2ca1c1d2cc88bb5951c6958b38c16e9436c8


Vulnerable code:

Fixed code:
#include "tensorflow/core/framework/op_requires.h"
#include "tensorflow/core/platform/errors.h"
  OP_REQUIRES_ASYNC(
      context, indices_t.dim_size(0) == values_t.dim_size(0),
      errors::InvalidArgument("The length of `values` (", values_t.dim_size(0),
                              ") must match the first dimension of `indices` (",
                              indices_t.dim_size(0), ")."),
      done);
CVE-2021-41225 (C++, published 2021-11-05T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. In affected versions TensorFlow's Grappler optimizer has a use of unitialized variable. If the `train_nodes` vector (obtained from the saved model that gets optimized) does not contain a `Dequeue` node, then `dequeue_node` is left unitialized. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.
Severity: LOW (CVSS v3 base score: 7.8)
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/grappler/optimizers/auto_parallel.cc
tensorflow/core/grappler/optimizers/auto_parallel_test.cc
Commit message: Prevent unitialized variable use in grappler.

PiperOrigin-RevId: 399702928
Change-Id: Id7e75451fbff297692dfb687f60ea04b25c96b24


Vulnerable code:
  const NodeDef* dequeue_node;

Fixed code:
  const NodeDef* dequeue_node = nullptr;
TEST_F(AutoParallelTest, SimpleParallelNoDequeue) {
  tensorflow::Scope s = tensorflow::Scope::DisabledShapeInferenceScope();
  Output constant_a = ops::Const(s.WithOpName("constant_a"), 1.0f, {1});
  Output constant_c = ops::Const(s.WithOpName("constant_c"), 1.0f, {1});
  Output constant_b = ops::Const(s.WithOpName("constant_b"), 1, {1});
  Output var = ops::Variable(s.WithOpName("var"), {1}, DT_FLOAT);
  Output assign = ops::Assign(s.WithOpName("assign"), {var}, {constant_a});
  Output add = ops::AddN(s.WithOpName("add"), {constant_a, constant_c});
  Output learning_rate = ops::Const(s.WithOpName("learning_rate"), 0.01f, {1});
  Output apply_gradient = ops::ApplyGradientDescent(
      s.WithOpName("apply_gradient"), {var}, {learning_rate}, {add});

  GrapplerItem item;
  item.init_ops.push_back("assign");
  item.fetch.push_back("apply_gradient");
  item.init_ops.push_back("assign");
  TF_CHECK_OK(s.ToGraphDef(&item.graph));

  AutoParallel parallel(2);
  GraphDef output;
  Status status = parallel.Optimize(nullptr, item, &output);
  TF_EXPECT_OK(status);
}
CVE-2021-41226 (C++, published 2021-11-05T21:15Z)
Description: value: TensorFlow is an open source platform for machine learning. In affected versions the implementation of `SparseBinCount` is vulnerable to a heap OOB access. This is because of missing validation between the elements of the `values` argument and the shape of the sparse output. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.
Severity: LOW (CVSS v3 base score: 7.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/bincount_op.cc
Commit message: Prevent out-of-bound accesses in SparseBincount.

PiperOrigin-RevId: 399918616
Change-Id: I11d154f4444d3fde1f09c5c40628b8671791a30d


Vulnerable code:

Fixed code:
        OP_REQUIRES(
            ctx, batch < out.dimension(0),
            errors::InvalidArgument("Index out of bound. `batch` (", batch,
                                    ") must be less than the dimension size (",
                                    out.dimension(0), ")."));
        OP_REQUIRES(
            ctx, bin < out.dimension(1),
            errors::InvalidArgument("Index out ouf bound. `bin` (", bin,
                                    ") must be less then the dimension size (",
                                    out.dimension(1), ")."));
CVE-2021-41227 (C, published 2021-11-05T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. In affected versions the `ImmutableConst` operation in TensorFlow can be tricked into reading arbitrary memory contents. This is because the `tstring` TensorFlow string class has a special case for memory mapped strings but the operation itself does not offer any support for this datatype. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.
Severity: LOW (CVSS v3 base score: 5.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/platform/ctstring_internal.h
tensorflow/core/platform/ctstring_test.cc
Commit message: Fix macros for converting little endian to host for TF_TSRT_OFFSET GetSize

Make the macro that converts little endian data do nothing on little endian hosts,
and byte swap otherwise.
This only affects getting the size of TStrings of type "Offset".

Added a test for TStrings of type "Offset" that checks if type and size are consistent.

PiperOrigin-RevId: 400789721
Change-Id: I1398bffd842ab1631614b212b7c3a2af88d99538


Vulnerable code:
#define TF_le32toh(x) TF_swap32(x)
#else  // TF_TSTRING_LITTLE_ENDIAN

Fixed code:
#else  // TF_TSTRING_LITTLE_ENDIAN
#define TF_le32toh(x) TF_swap32(x)
#include "tensorflow/core/platform/ctstring_internal.h"

TEST(TF_CTStringTest, OffsetType) {
  {
    TF_TString s71;

    TF_TString_Init(&s71);
    size_t header_length = 24;
    size_t size = 8;
    TF_TString_ResizeUninitialized(&s71, header_length + size);
    uint32_t save_size = s71.u.offset.size;
    uint32_t save_offset = s71.u.offset.offset;
    uint32_t save_count = s71.u.offset.count;

    s71.u.offset.size = TF_TString_ToInternalSizeT(size, TF_TSTR_OFFSET);
    s71.u.offset.offset = header_length;
    s71.u.offset.count = 0;
    EXPECT_EQ(size, TF_TString_GetSize(&s71));
    EXPECT_EQ(TF_TSTR_OFFSET, TF_TString_GetType(&s71));

    // restore state so string can be deallocated
    s71.u.offset.size = save_size;
    s71.u.offset.offset = save_offset;
    s71.u.offset.count = save_count;
    TF_TString_Dealloc(&s71);
  }
}
CVE-2021-41227 (C++, published 2021-11-05T23:15Z)
Description: value: TensorFlow is an open source platform for machine learning. In affected versions the `ImmutableConst` operation in TensorFlow can be tricked into reading arbitrary memory contents. This is because the `tstring` TensorFlow string class has a special case for memory mapped strings but the operation itself does not offer any support for this datatype. The fix will be included in TensorFlow 2.7.0. We will also cherrypick this commit on TensorFlow 2.6.1, TensorFlow 2.5.2, and TensorFlow 2.4.4, as these are also affected and still in supported range.
Severity: LOW (CVSS v3 base score: 5.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/kernels/immutable_constant_op.cc
tensorflow/core/kernels/immutable_constant_op_test.cc
Commit message: Add error checking to ImmutableConst OP that strings are not yet supported.

PiperOrigin-RevId: 401065359
Change-Id: I9dd2bd2a2c36f22f4a05153daf6ebdc4613469d2


Vulnerable code:
Status CreateTempFile(Env* env, float value, uint64 size, string* filename) {
  TF_ASSERT_OK(CreateTempFile(env, 2.0f, 1000, &two_file));
  TF_ASSERT_OK(CreateTempFile(env, 3.0f, 1000, &three_file));

Fixed code:
  OP_REQUIRES(ctx, dtype_ != DT_STRING,
              errors::Unimplemented("Sorry, DT_STRING is not currently "
                                    "supported for ImmutableConstOp."));
Status CreateTempFileFloat(Env* env, float value, uint64 size,
                           string* filename) {
  TF_ASSERT_OK(CreateTempFileFloat(env, 2.0f, 1000, &two_file));
  TF_ASSERT_OK(CreateTempFileFloat(env, 3.0f, 1000, &three_file));
Status CreateTempFileBadString(Env* env, char value, uint64 size,
                               const string suffix, string* filename) {
  const string dir = testing::TmpDir();
  *filename = io::JoinPath(dir, strings::StrCat("file_", suffix));
  std::unique_ptr<WritableFile> file;
  TF_RETURN_IF_ERROR(env->NewWritableFile(*filename, &file));
  TF_RETURN_IF_ERROR(file->Append(std::string(size, value)));
  TF_RETURN_IF_ERROR(file->Close());
  return Status::OK();
}

TEST(ImmutableConstantOpTest, FromFileStringUnimplmented) {
  const TensorShape kFileTensorShape({1});
  Env* env = Env::Default();
  auto root = Scope::NewRootScope().ExitOnError();

  string bad_file;
  TF_ASSERT_OK(CreateTempFileBadString(env, '\xe2', 128, "bad_e2", &bad_file));
  auto result =
      ops::ImmutableConst(root, DT_STRING, kFileTensorShape, bad_file);
  GraphDef graph_def;
  TF_ASSERT_OK(root.ToGraphDef(&graph_def));
  SessionOptions session_options;
  session_options.env = Env::Default();
  std::unique_ptr<Session> session(NewSession(session_options));
  ASSERT_TRUE(session != nullptr) << "Failed to create session";
  TF_ASSERT_OK(session->Create(graph_def)) << "Can't create test graph";
  std::vector<Tensor> outputs;
  // Check that the run returned error.
  EXPECT_EQ(
      session->Run({}, {result.node()->name() + ":0"}, {}, &outputs).code(),
      error::UNIMPLEMENTED);
}
CVE-2022-21726 (C++, published 2022-02-03T11:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `Dequantize` does not fully validate the value of `axis` and can result in heap OOB accesses. The `axis` argument can be `-1` (the default value for the optional argument) or any other positive value at most the number of dimensions of the input. Unfortunately, the upper bound is not checked and this results in reading past the end of the array containing the dimensions of the input tensor. 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-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/dequantize_op.cc
Commit message: Fix out of bound access in DequantizeOp by adding check for axis < input dimension

PiperOrigin-RevId: 411214268
Change-Id: I3249d2a69ddc82f182c589a3a5bbfb71543f4b29


Vulnerable code:

Fixed code:
    OP_REQUIRES(
        ctx, axis_ < input.dims(),
        errors::InvalidArgument("Axis must be less than input dimension(",
                                input.dims(), "), got ", axis_));
CVE-2022-21727 (Python, published 2022-02-03T11:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of shape inference for `Dequantize` is vulnerable to an integer overflow weakness. The `axis` argument can be `-1` (the default value for the optional argument) or any other positive value at most the number of dimensions of the input. Unfortunately, the upper bound is not checked, and, since the code computes `axis + 1`, an attacker can trigger an integer 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-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/array_ops.cc
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
Commit message: Fix Integer overflow error in Dequantize op shape function, by adding a bound check on axis.

PiperOrigin-RevId: 412121389
Change-Id: I3088dbad9e90f9998d406b618c16694388a9dfb4


Vulnerable code:

Fixed code:
#include "tensorflow/core/platform/types.h"
      auto input_dims = c->Rank(c->input(0));
      if (axis > input_dims) {
        return errors::InvalidArgument(
            "Axis must be less than input dimension(", input_dims, "), got ",
            axis);
      }
        if (axis >= kint32max) {
          // Check int32 max bound for a corner case to prevent integer flow
          // when input actually has kint32max rank and above bound check is not
          // triggered.
          return errors::InvalidArgument(
              "Axis cannot be >= kint32max value, got ", axis);
        }
  def testOutOfBoundAxis(self):
    input_tensor = constant_op.constant([1., 1.])
    input_min = [0]
    input_max = [1]
    q_input, _, _ = array_ops.quantize(input_tensor, 0, 1, dtypes.qint32)
    error = (errors.InvalidArgumentError, ValueError)
    with self.assertRaisesRegex(error,
                                r".*Axis must be less than input dimension.*"):
      self.evaluate(
          gen_array_ops.dequantize(
              input=q_input,
              min_range=input_min,
              max_range=input_max,
              axis=2**31 - 1))
CVE-2022-21728 (C++, published 2022-02-03T11:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of shape inference for `ReverseSequence` does not fully validate the value of `batch_dim` and can result in a heap OOB read. There is a check to make sure the value of `batch_dim` does not go over the rank of the input, but there is no check for negative values. Negative dimensions are allowed in some cases to mimic Python's negative indexing (i.e., indexing from the end of the array), however if the value is too negative then the implementation of `Dim` would access elements before the start of an array. 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.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/ops/array_ops.cc
Commit message: Fix out of bound error in ReverseSequence Op shape function

PiperOrigin-RevId: 411896080
Change-Id: I7e59a38e2f960886edf2b6c54ed5a84e86a9b193


Vulnerable code:

Fixed code:

      // To prevent out of bound access when calling c->Dim(input, batch_dim),
      // batch_dim range [-1 * input rank, input rank) is allowed. However,
      // the op implementation has a stricter bound for batch_dim requiring >= 0
      // value. Thus, perform strict check here.
      if (batch_dim < 0) {
        return errors::InvalidArgument("batch_dim must be >=0, got ",
                                       batch_dim);
      }
CVE-2022-21729 (Python, published 2022-02-03T13:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `UnravelIndex` is vulnerable to a division by zero caused by an integer overflow bug. 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/unravel_index_op.cc
tensorflow/python/kernel_tests/array_ops/array_ops_test.py
Commit message: Fix integer overflow leading to divide by zero error in Unravel index kernel when dimensions product exceeds max int value.

PiperOrigin-RevId: 413250052
Change-Id: I9450b6e8acecd2e881a64b882e2b7c70e8e9289a


Vulnerable code:
  explicit UnravelIndexOp(OpKernelConstruction* ctx) : OpKernel(ctx) {}

Fixed code:
#include <cstdint>

#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/platform/types.h"
  explicit UnravelIndexOp(OpKernelConstruction* ctx)
      : OpKernel(ctx), dtidx_(DataTypeToEnum<Tidx>::v()) {}
    double prod = 1;
    uint64_t limit;
    if (dtidx_ == DataType::DT_INT64) {
      limit = kint64max;
    } else {
      limit = kint32max;
    }

      OP_REQUIRES(ctx, dims(i) > 0,
                  errors::InvalidArgument(
                      "Input dims cannot be negative. Got dim = ", dims(i),
                      " at index ", i));
      // Check interger overflow
      OP_REQUIRES(
          ctx, prod <= limit / dims(i),
          errors::InvalidArgument("Input dims product is causing integer "
                                  "overflow: (",
                                  dims, ")"));
      prod = (prod * dims(i));
  const DataType dtidx_;
  def testUnravelIndexIntegerOverflow(self):
    with self.cached_session():
      for dtype in [dtypes.int32, dtypes.int64]:
        with self.assertRaisesRegex(
            errors.InvalidArgumentError,
            r"Input dims product is causing integer overflow"):
          indices = constant_op.constant(-0x100000, dtype=dtype)
          if dtype == dtypes.int32:
            value = 0x10000000
          else:
            value = 0x7FFFFFFFFFFFFFFF
          dims = constant_op.constant([value, value], dtype=dtype)
          self.evaluate(array_ops.unravel_index(indices=indices, dims=dims))
CVE-2022-21730 (Python, published 2022-02-03T11:15Z)
Description: value: Tensorflow is an Open Source Machine Learning Framework. The implementation of `FractionalAvgPoolGrad` does not consider cases where the input tensors are invalid allowing an attacker to read from outside of bounds of heap. 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.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/fractional_avg_pool_op.cc
tensorflow/python/kernel_tests/nn_ops/fractional_avg_pool_op_test.py
Commit message: Add negative bound check for row and column pooling_sequence in FractionalAvgPoolGrad op to avoid out of bound heap access

PiperOrigin-RevId: 413837346
Change-Id: I2b86034101df31bee161abcb781755e236c7bccd


Vulnerable code:

Fixed code:

        OP_REQUIRES(context, in_row_start >= 0 && in_row_end >= 0,
                    errors::InvalidArgument(
                        "Row sequence tensor values must not be negative, got ",
                        row_seq_tensor_flat));

          OP_REQUIRES(
              context, in_col_start >= 0 && in_col_end >= 0,
              errors::InvalidArgument(
                  "Column sequence tensor values must not be negative, got ",
                  col_seq_tensor_flat));
from tensorflow.python.framework import errors
  def testNegativeSeqValuesForGradOp(self):
    with self.assertRaisesRegex(
        errors.InvalidArgumentError,
        r"Row sequence tensor values must not be negative.*"):
      y = nn_ops.gen_nn_ops.fractional_avg_pool_grad(
          orig_input_tensor_shape=[2, 2, 2, 2],
          out_backprop=[[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11,
                                                                      12]]]],
          row_pooling_sequence=[-10, 1, 2, 3],
          col_pooling_sequence=[1, 2, 3, 4],
          overlapping=True)

      self.evaluate(y)
      with self.assertRaisesRegex(
          errors.InvalidArgumentError,
          r"Column sequence tensor values must not be negative.*"):
        z = nn_ops.gen_nn_ops.fractional_avg_pool_grad(
            orig_input_tensor_shape=[2, 2, 2, 2],
            out_backprop=[[[[1, 2], [3, 4], [5, 6]], [[7, 8], [9, 10], [11,
                                                                        12]]]],
            row_pooling_sequence=[10, 1, 2, 3],
            col_pooling_sequence=[1, 2, -3, 4],
            overlapping=True)

        self.evaluate(z)