The following issues were found

c10/core/GeneratorImpl.cpp
2 issues
open - Check when opening files - can an attacker redirect it (via symlinks), force the opening of special file type (e.g., device files), move things around to create a race condition, control its ancestors, or change its contents?
Security

Line: 48 Column: 17 CWE codes: 362

               */
#ifndef _WIN32
static uint64_t readURandomLong() {
  int randDev = open("/dev/urandom", O_RDONLY);
  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
  uint64_t randValue;
  TORCH_CHECK(randDev >= 0, "Unable to open /dev/urandom");
  ssize_t readBytes = read(randDev, &randValue, sizeof(randValue));
  TORCH_CHECK(

            

Reported by FlawFinder.

read - Check buffer boundaries if used in a loop including recursive loops
Security

Line: 52 Column: 23 CWE codes: 120 20

                // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
  uint64_t randValue;
  TORCH_CHECK(randDev >= 0, "Unable to open /dev/urandom");
  ssize_t readBytes = read(randDev, &randValue, sizeof(randValue));
  TORCH_CHECK(
      readBytes >= (ssize_t)sizeof(randValue),
      "Unable to read from /dev/urandom");
  close(randDev);
  return randValue;

            

Reported by FlawFinder.

c10/cuda/CUDACachingAllocator.cpp
2 issues
getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 342 Column: 23 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

                size_t m_max_split_size;

  void parseArgs() {
    const char* val = getenv("PYTORCH_CUDA_ALLOC_CONF");
    if (val != NULL) {
      const std::string config(val);

      std::regex exp("[\\s,]+");
      std::sregex_token_iterator it(config.begin(), config.end(), exp, -1);

            

Reported by FlawFinder.

getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 1453 Column: 7 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              // errors, since the caching allocator foils cuda-memcheck.
bool forceUncachedAllocator() {
  static bool force_uncached =
      getenv("PYTORCH_NO_CUDA_MEMORY_CACHING") != nullptr;
  return force_uncached;
}

static void uncached_delete(void* ptr) {
  C10_CUDA_CHECK(cudaFree(ptr));

            

Reported by FlawFinder.

c10/test/util/Metaprogramming_test.cpp
2 issues
syntax error
Error

Line: 117

              namespace test_extract_arg_by_filtered_index {
class MyClass {};

TEST(MetaprogrammingTest, ExtractArgByFilteredIndex) {
  auto a1 = extract_arg_by_filtered_index<std::is_integral, 0>(
      3, "bla", MyClass(), 4, nullptr, 5);
  auto a2 = extract_arg_by_filtered_index<std::is_integral, 1>(
      3, "bla", MyClass(), 4, nullptr, 5);
  auto a3 = extract_arg_by_filtered_index<std::is_integral, 2>(

            

Reported by Cppcheck.

atoi - Unless checked, the resulting number can exceed the expected range
Security

Line: 447 Column: 14 CWE codes: 190
Suggestion: If source untrusted, check both minimum and maximum, even if the input had no minus sign (large numbers can roll over into negative number; consider saving to an unsigned value if that is intended)

                    return std::to_string(a);
    }
    int32_t operator()(const std::string& a) const {
      return atoi(a.c_str());
    }
  };
  auto result = tuple_map(std::tuple<int32_t, std::string>(3, "4"), Mapper());
  static_assert(
      std::is_same<std::tuple<std::string, int32_t>, decltype(result)>::value,

            

Reported by FlawFinder.

c10/test/util/TypeIndex_test.cpp
2 issues
syntax error
Error

Line: 62

                  string_view::npos != get_fully_qualified_type_name<Dummy>().find("Dummy"),
    "");
#endif
TEST(TypeIndex, TopLevelName) {
  EXPECT_NE(
      string_view::npos, get_fully_qualified_type_name<Dummy>().find("Dummy"));
}
} // namespace test_top_level_name


            

Reported by Cppcheck.

syntax error
Error

Line: 77

                      get_fully_qualified_type_name<Dummy>().find("test_nested_name::Dummy"),
    "");
#endif
TEST(TypeIndex, NestedName) {
  EXPECT_NE(
      string_view::npos,
      get_fully_qualified_type_name<Dummy>().find("test_nested_name::Dummy"));
}
} // namespace test_nested_name

            

Reported by Cppcheck.

c10/util/StringUtil.cpp
2 issues
strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 41 Column: 41 CWE codes: 126

                TORCH_CHECK(to, "");

  size_t numReplaced = 0;
  std::string::size_type lenFrom = std::strlen(from);
  std::string::size_type lenTo = std::strlen(to);
  for (auto pos = s.find(from); pos != std::string::npos;
       pos = s.find(from, pos + lenTo)) {
    s.replace(pos, lenFrom, to);
    numReplaced++;

            

Reported by FlawFinder.

strlen - Does not handle strings that are not \0-terminated; if given one it may perform an over-read (it could cause a crash if unprotected)
Security

Line: 42 Column: 39 CWE codes: 126

              
  size_t numReplaced = 0;
  std::string::size_type lenFrom = std::strlen(from);
  std::string::size_type lenTo = std::strlen(to);
  for (auto pos = s.find(from); pos != std::string::npos;
       pos = s.find(from, pos + lenTo)) {
    s.replace(pos, lenFrom, to);
    numReplaced++;
  }

            

Reported by FlawFinder.

c10/util/Unicode.cpp
2 issues
MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 9 Column: 21 CWE codes: 120

                if (str.empty()) {
    return std::wstring();
  }
  int size_needed = MultiByteToWideChar(
      CP_UTF8, 0, str.c_str(), static_cast<int>(str.size()), NULL, 0);
  TORCH_CHECK(size_needed > 0, "Error converting the content to Unicode");
  std::wstring wstr(size_needed, 0);
  MultiByteToWideChar(
      CP_UTF8,

            

Reported by FlawFinder.

MultiByteToWideChar - Requires maximum length in CHARACTERS, not bytes
Security

Line: 13 Column: 3 CWE codes: 120

                    CP_UTF8, 0, str.c_str(), static_cast<int>(str.size()), NULL, 0);
  TORCH_CHECK(size_needed > 0, "Error converting the content to Unicode");
  std::wstring wstr(size_needed, 0);
  MultiByteToWideChar(
      CP_UTF8,
      0,
      str.c_str(),
      static_cast<int>(str.size()),
      &wstr[0],

            

Reported by FlawFinder.

caffe2/contrib/fakelowp/layernorm_fp16_fake_op.h
2 issues
memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 135 Column: 14 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                    for (int i = 0; i < M; ++i) {
        // fma_fp16(A, B, Out) -> Out = A * B + Out
        std::vector<float> out(N);
        std::memcpy(out.data(), bias_data.data(), sizeof(float) * N);
        fake_fp16::fma_fp16(N, Y_data + i * N, scale_data.data(), out.data());
        std::memcpy(Y_data + i * N, out.data(), sizeof(float) * N);
      }
    }


            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 137 Column: 14 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                      std::vector<float> out(N);
        std::memcpy(out.data(), bias_data.data(), sizeof(float) * N);
        fake_fp16::fma_fp16(N, Y_data + i * N, scale_data.data(), out.data());
        std::memcpy(Y_data + i * N, out.data(), sizeof(float) * N);
      }
    }

    // Quantize
    // We should be using the same quantization fucntion from int8quantize,

            

Reported by FlawFinder.

caffe2/core/context.h
2 issues
random - This function is not sufficiently random for security-related functions such as key and nonce creation
Security

Line: 56 Column: 14 CWE codes: 327
Suggestion: Use a more secure technique for acquiring random values

                  explicit rand_gen_type(uint64_t seed_in = default_rng_seed_val)
        : engine_{seed_in} {}

    uint32_t random() {
      return engine_();
    }
    uint64_t random64() {
      uint32_t random1 = engine_();
      uint32_t random2 = engine_();

            

Reported by FlawFinder.

memcpy - Does not check for buffer overflows when copying to destination
Security

Line: 221 Column: 3 CWE codes: 120
Suggestion: Make sure destination can always hold the source data

                }
  CAFFE_ENFORCE(src);
  CAFFE_ENFORCE(dst);
  memcpy(dst, src, nbytes);
}

} // namespace caffe2

#endif // CAFFE2_CORE_CONTEXT_H_

            

Reported by FlawFinder.

caffe2/core/init_omp.cc
2 issues
getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 32 Column: 8 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              
#ifdef _OPENMP
bool Caffe2SetOpenMPThreads(int*, char***) {
  if (!getenv("OMP_NUM_THREADS")) {
    // OMP_NUM_THREADS not passed explicitly, so *disable* OMP by
    // default. The user can use the CLI flag to override.
    VLOG(1) << "OMP_NUM_THREADS not passed, defaulting to 1 thread";
    omp_set_num_threads(1);
  }

            

Reported by FlawFinder.

getenv - Environment variables are untrustable input if they can be set by an attacker. They can have any content and length, and the same variable can be set more than once
Security

Line: 53 Column: 8 CWE codes: 807 20
Suggestion: Check environment variables carefully before using them

              
#ifdef CAFFE2_USE_MKL
bool Caffe2SetMKLThreads(int*, char***) {
  if (!getenv("MKL_NUM_THREADS")) {
    VLOG(1) << "MKL_NUM_THREADS not passed, defaulting to 1 thread";
    mkl_set_num_threads(1);
  }

  // If caffe2_omp_num_threads is set, we use that for MKL as well.

            

Reported by FlawFinder.

caffe2/core/nomnigraph/include/nomnigraph/Transformations/Match.h
2 issues
equal - Function does not check the second iterator for over-read conditions
Security

Line: 23 Column: 15 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

              
template <typename T>
struct NodeEqualityDefault {
  static bool equal(const T& a, const T& b) {
    return a->data() == b->data();
  }
};

template <

            

Reported by FlawFinder.

equal - Function does not check the second iterator for over-read conditions
Security

Line: 46 Column: 24 CWE codes: 126
Suggestion: This function is often discouraged by most C++ coding standards in favor of its safer alternatives provided since C++14. Consider using a form of this function that checks the second iterator before potentially overflowing it

                    typename G::NodeRef candidateNode,
      std::vector<typename G::NodeRef> stack,
      SubgraphType currentSubgraph) {
    if (EqualityClass::equal(stack.back(), candidateNode)) {
      currentSubgraph.addNode(candidateNode);

      // Base case
      if (stack.size() == MatchNodeList.size()) {
        return std::vector<SubgraphType>{currentSubgraph};

            

Reported by FlawFinder.