CVE-2019-3553: Allocation of Resources Without Limits or Throttling (CWE-770)
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.
CWE description: 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.
CVSS v3 base score: 7.5
Published: 2020-03-10T21:15Z
Repository: https://github.com/facebook/fbthrift
Language: C
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 date: 2020-01-27 17:30:36 -0800
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

Diff: diff --git a/thrift/lib/cpp/protocol/TProtocolException.cpp b/thrift/lib/cpp/protocol/TProtocolException.cpp
index edca7c6a88..eac4c4becb 100644
--- a/thrift/lib/cpp/protocol/TProtocolException.cpp
+++ b/thrift/lib/cpp/protocol/TProtocolException.cpp
@@ -73,8 +73,15 @@ namespace protocol {
 [[noreturn]] void TProtocolException::throwInvalidFieldData() {
   throw TProtocolException(
       TProtocolException::INVALID_DATA,
       "The field stream contains corrupted data");
 }
+
+[[noreturn]] void TProtocolException::throwTruncatedData() {
+  throw TProtocolException(
+      TProtocolException::INVALID_DATA,
+      "Not enough bytes to read the entire message, the data appears to be "
+      "truncated");
+}
 } // namespace protocol
 } // namespace thrift
 } // namespace apache
diff --git a/thrift/lib/cpp/protocol/TProtocolException.h b/thrift/lib/cpp/protocol/TProtocolException.h
index 90afd81a13..fc9186b3f5 100644
--- a/thrift/lib/cpp/protocol/TProtocolException.h
+++ b/thrift/lib/cpp/protocol/TProtocolException.h
@@ -105,10 +105,11 @@ class TProtocolException : public apache::thrift::TLibraryException {
       folly::StringPiece field,
       folly::StringPiece type);
   [[noreturn]] static void throwBoolValueOutOfRange(uint8_t value);
   [[noreturn]] static void throwInvalidSkipType(TType type);
   [[noreturn]] static void throwInvalidFieldData();
+  [[noreturn]] static void throwTruncatedData();
 
  protected:
   /**
    * Error code
    */
diff --git a/thrift/lib/cpp2/protocol/NimbleProtocol.h b/thrift/lib/cpp2/protocol/NimbleProtocol.h
index 25ac766908..bc07d9d8c7 100644
--- a/thrift/lib/cpp2/protocol/NimbleProtocol.h
+++ b/thrift/lib/cpp2/protocol/NimbleProtocol.h
@@ -379,10 +379,19 @@ struct ProtocolReaderWireTypeInfo<NimbleProtocolReader> {
   }
 };
 
 } // namespace detail
 
+template <>
+inline bool canReadNElements(
+    NimbleProtocolReader& /* prot */,
+    uint32_t /* n */,
+    std::initializer_list<detail::nimble::NimbleType> /* types */) {
+  // TODO: implement canReadNElements for NimbleProtocol
+  return true;
+}
+
 template <>
 inline void skip<NimbleProtocolReader, detail::nimble::NimbleType>(
     NimbleProtocolReader& /* prot */,
     detail::nimble::NimbleType /* arg_type */) {
   // Fool the noreturn warning; we can't add the annotation without breaking
diff --git a/thrift/lib/cpp2/protocol/Protocol.h b/thrift/lib/cpp2/protocol/Protocol.h
index b9f8fa647f..d1b27807e1 100644
--- a/thrift/lib/cpp2/protocol/Protocol.h
+++ b/thrift/lib/cpp2/protocol/Protocol.h
@@ -183,10 +183,27 @@ void skip(Protocol_& prot, WireType arg_type) {
       TProtocolException::throwInvalidSkipType(arg_type);
     }
   }
 }
 
+/**
+ * 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());
+}
+
 /*
  * Skip n tuples - used for skpping lists, sets, maps.
  *
  * As with skip(), protocols can specialize.
  */
diff --git a/thrift/lib/cpp2/protocol/detail/protocol_methods.h b/thrift/lib/cpp2/protocol/detail/protocol_methods.h
index a7bdc55142..cfaecfb88f 100644
--- a/thrift/lib/cpp2/protocol/detail/protocol_methods.h
+++ b/thrift/lib/cpp2/protocol/detail/protocol_methods.h
@@ -530,10 +530,14 @@ struct protocol_methods<type_class::list<ElemClass>, Type> {
       }
     } else {
       if (reported_type != WireTypeInfo::fromTType(elem_methods::ttype_value)) {
         apache::thrift::skip_n(protocol, list_size, {reported_type});
       } else {
+        if (!canReadNElements(protocol, list_size, {reported_type})) {
+          protocol::TProtocolException::throwTruncatedData();
+        }
+
         using traits = std::iterator_traits<typename Type::iterator>;
         using cat = typename traits::iterator_category;
         if (reserve_if_possible(&out, list_size) ||
             std::is_same<cat, std::bidirectional_iterator_tag>::value) {
           // use bidi as a hint for doubly linked list containers like std::list
@@ -617,10 +621,13 @@ struct protocol_methods<type_class::set<ElemClass>, Type> {
       }
     } else {
       if (reported_type != WireTypeInfo::fromTType(elem_methods::ttype_value)) {
         apache::thrift::skip_n(protocol, set_size, {reported_type});
       } else {
+        if (!canReadNElements(protocol, set_size, {reported_type})) {
+          protocol::TProtocolException::throwTruncatedData();
+        }
         auto const vreader = [&protocol](auto& value) {
           elem_methods::read(protocol, value);
         };
         deserialize_known_length_set(out, set_size, vreader);
       }
@@ -720,10 +727,14 @@ struct protocol_methods<type_class::map<KeyClass, MappedClass>, Type> {
            WireTypeInfo::fromTType(mapped_methods::ttype_value) !=
                rpt_mapped_type)) {
         apache::thrift::skip_n(
             protocol, map_size, {rpt_key_type, rpt_mapped_type});
       } else {
+        if (!canReadNElements(
+                protocol, map_size, {rpt_key_type, rpt_mapped_type})) {
+          protocol::TProtocolException::throwTruncatedData();
+        }
         auto const kreader = [&protocol](auto& key) {
           key_methods::read(protocol, key);
         };
         auto const vreader = [&protocol](auto& value) {
           mapped_methods::read(protocol, value);
diff --git a/thrift/test/ProtocolTruncatedData.thrift b/thrift/test/ProtocolTruncatedData.thrift
new file mode 100644
index 0000000000..bd1f6a2722
--- /dev/null
+++ b/thrift/test/ProtocolTruncatedData.thrift
@@ -0,0 +1,23 @@
+/*
+ * 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,
+}
diff --git a/thrift/test/ProtocolTruncatedDataTest.cpp b/thrift/test/ProtocolTruncatedDataTest.cpp
new file mode 100644
index 0000000000..890355729c
--- /dev/null
+++ b/thrift/test/ProtocolTruncatedDataTest.cpp
@@ -0,0 +1,79 @@
+/*
+ * 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 */);
+}

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 */);
}