CVE-2019-3553 (C, published 2020-03-10T21:15Z)
Description: value: C++ Facebook Thrift servers would not error upon receiving messages declaring containers of sizes larger than the payload. As a result, malicious clients could send short messages which would result in a large memory allocation, potentially leading to denial of service. This issue affects Facebook Thrift prior to v2020.02.03.00.
Severity: MEDIUM (CVSS v3 base score: 7.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/facebook/fbthrift
Files changed:
thrift/lib/cpp/protocol/TProtocolException.cpp
thrift/lib/cpp/protocol/TProtocolException.h
thrift/lib/cpp2/protocol/NimbleProtocol.h
thrift/lib/cpp2/protocol/Protocol.h
thrift/lib/cpp2/protocol/detail/protocol_methods.h
thrift/test/ProtocolTruncatedData.thrift
thrift/test/ProtocolTruncatedDataTest.cpp
Commit message: Better handling of truncated data when reading containers

Summary:
Currently we read the container size and blindly pre-allocate the container of that size. This allows malicious attacker to send few bytes message and cause server to allocate GBs of memory.

This diff changes the logic to check if we have at least 1b/element in our buffer, thus forcing attacker to send that much data.

This is a partial fix for CVE-2019-3553.

Reviewed By: yfeldblum, vitaut

Differential Revision: D14392438

fbshipit-source-id: b92e300a98e29faee564e2f5069027b28cb2cca4


Vulnerable code:

Fixed code:

[[noreturn]] void TProtocolException::throwTruncatedData() {
  throw TProtocolException(
      TProtocolException::INVALID_DATA,
      "Not enough bytes to read the entire message, the data appears to be "
      "truncated");
}
  [[noreturn]] static void throwTruncatedData();
template <>
inline bool canReadNElements(
    NimbleProtocolReader& /* prot */,
    uint32_t /* n */,
    std::initializer_list<detail::nimble::NimbleType> /* types */) {
  // TODO: implement canReadNElements for NimbleProtocol
  return true;
}

/**
 * Check if the remaining part of buffers contain least necessary amount of
 * bytes to encode N elements of given type.
 *
 * Note: this is a lightweight lower bound check, it doesn't necessary mean
 *       that we would actually succeed at reading N items.
 */
template <class Protocol_>
inline bool canReadNElements(
    Protocol_& prot,
    uint32_t n,
    std::initializer_list<
        typename detail::ProtocolReaderWireTypeInfo<Protocol_>::WireType>
        types) {
  return prot.getCursor().canAdvance(n * types.size());
}

        if (!canReadNElements(protocol, list_size, {reported_type})) {
          protocol::TProtocolException::throwTruncatedData();
        }

        if (!canReadNElements(protocol, set_size, {reported_type})) {
          protocol::TProtocolException::throwTruncatedData();
        }
        if (!canReadNElements(
                protocol, map_size, {rpt_key_type, rpt_mapped_type})) {
          protocol::TProtocolException::throwTruncatedData();
        }
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

namespace cpp2 thrift.test

struct TestStruct {
  1: optional list<i64> i64_list,
  2: optional set<i32> i32_set,
  3: optional map<i32,i16> i32_i16_map,
}
/*
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <gtest/gtest.h>

#include <thrift/lib/cpp2/protocol/Serializer.h>
#include <thrift/test/gen-cpp2/ProtocolTruncatedData_types.h>

using namespace apache::thrift;
using namespace thrift::test;

template <class Serializer, class T>
void testPartialDataHandling(const T& val, size_t bytesToPassTheCheck) {
  auto buf = Serializer::template serialize<folly::IOBufQueue>(val).move();
  buf->coalesce();

  // Check that deserializing doesn't throw.
  EXPECT_NO_THROW(Serializer::template deserialize<T>(buf.get()));

  // Trim the buffer to the point that is *just enough* to pass the check for
  // minimum required bytes.
  buf->trimEnd(buf->length() - bytesToPassTheCheck);
  // We'll hit underflow exception when pulling yet another element.
  EXPECT_THROW(
      Serializer::template deserialize<T>(buf.get()), std::out_of_range);

  // Trim one more byte.
  buf->trimEnd(1);
  // We'll fail the deserialization straight when we read the length.
  EXPECT_THROW(
      Serializer::template deserialize<T>(buf.get()),
      apache::thrift::protocol::TProtocolException);
}

TEST(ProtocolTruncatedDataTest, TruncatedList) {
  TestStruct s;
  s.i64_list_ref() = {};
  for (size_t i = 0; i < 30; ++i) {
    s.i64_list_ref()->emplace_back((1ull << i));
  }

  testPartialDataHandling<CompactSerializer>(
      s, 3 /* headers */ + 30 /* 1b / element */);
}

TEST(ProtocolTruncatedDataTest, TruncatedSet) {
  TestStruct s;
  s.i32_set_ref() = {};
  for (size_t i = 0; i < 30; ++i) {
    s.i32_set_ref()->emplace((1ull << i));
  }

  testPartialDataHandling<CompactSerializer>(
      s, 3 /* headers */ + 30 /* 1b / element */);
}

TEST(ProtocolTruncatedDataTest, TruncatedMap) {
  TestStruct s;
  s.i32_i16_map_ref() = {};
  for (size_t i = 0; i < 30; ++i) {
    s.i32_i16_map_ref()->emplace((1ull << i), i);
  }

  testPartialDataHandling<CompactSerializer>(
      s, 3 /* headers */ + 30 * 2 /* 2b / kv pair */);
}