CVE-2019-3553 (published 2020-03-10T21:15Z)

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 v2 base score: 5.0 (AV:N/AC:L/Au:N/C:N/I:N/A:P)
CVSS v3 base score: 7.5, HIGH (CVSS:3.1/AV:N/AC:L/PR:N/UI:N/S:U/C:N/I:N/A:H)

Weakness information:
cwe_id: CWE-770
cwe_name: Allocation of Resources Without Limits or Throttling
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.
extended_description: Code frequently has to work with limited resources, so programmers must be careful to ensure that resources are not consumed too quickly, or too easily.  Without use of quotas, resource limits, or other protection mechanisms, it can be easy for an attacker to consume many resources by rapidly making many requests, or causing larger resources to be used than is needed. When too many resources are allocated, or if a single resource is too large, then it can prevent the code from working correctly, possibly leading to a denial of service.
         

Fix information:
repo_url: https://github.com/facebook/fbthrift
commit_details: repo_url: https://github.com/facebook/fbthrift
author: Stepan Palamarchuk
author_date: 2020-01-27 17:29:04-08:00
msg: 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
repository: repo_url: https://github.com/facebook/fbthrift
repo_name: facebook/fbthrift
description: Facebook's branch of Apache Thrift, including a new C++ server.
repo_language: C++
owner: facebook
file_changes: filename: TProtocolException.cpp
change_type: ModificationType.MODIFY
diff: @@ -75,6 +75,13 @@ namespace protocol {
       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

programming_language: C++
filename: TProtocolException.h
change_type: ModificationType.MODIFY
diff: @@ -107,6 +107,7 @@ class TProtocolException : public apache::thrift::TLibraryException {
   [[noreturn]] static void throwBoolValueOutOfRange(uint8_t value);
   [[noreturn]] static void throwInvalidSkipType(TType type);
   [[noreturn]] static void throwInvalidFieldData();
+  [[noreturn]] static void throwTruncatedData();
 
  protected:
   /**

programming_language: C++
filename: NimbleProtocol.h
change_type: ModificationType.MODIFY
diff: @@ -381,6 +381,15 @@ 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 */,

programming_language: C++
filename: Protocol.h
change_type: ModificationType.MODIFY
diff: @@ -185,6 +185,23 @@ void skip(Protocol_& prot, WireType 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.
  *

programming_language: C++
filename: protocol_methods.h
change_type: ModificationType.MODIFY
diff: @@ -532,6 +532,10 @@ struct protocol_methods<type_class::list<ElemClass>, Type> {
       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) ||
@@ -619,6 +623,9 @@ struct protocol_methods<type_class::set<ElemClass>, Type> {
       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);
         };
@@ -722,6 +729,10 @@ struct protocol_methods<type_class::map<KeyClass, MappedClass>, 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);
         };

programming_language: C++
filename: ProtocolTruncatedData.thrift
change_type: ModificationType.ADD
diff: @@ -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,
+}

programming_language: Scala
filename: ProtocolTruncatedDataTest.cpp
change_type: ModificationType.ADD
diff: @@ -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 */);
+}

programming_language: C++
repo_url: https://github.com/facebook/fbthrift
commit_details: repo_url: https://github.com/facebook/fbthrift
author: Stepan Palamarchuk
author_date: 2020-01-28 08:30:50-08:00
msg: Better handling of truncated data when reading strings

Summary:
Currently we read string size and blindly pre-allocate it. This allows malicious attacker to send a few bytes message and cause server to allocate huge amount of memory (>1GB).

This diff changes the logic to check if we have enough data in the buffer before allocating the string.

This is a second part of a fix for CVE-2019-3553.

Reviewed By: vitaut

Differential Revision: D14393393

fbshipit-source-id: e2046d2f5b087d3abc9a9d2c6c107cf088673057
repository: repo_url: https://github.com/facebook/fbthrift
repo_name: facebook/fbthrift
description: Facebook's branch of Apache Thrift, including a new C++ server.
repo_language: C++
owner: facebook
file_changes: filename: BinaryProtocol-inl.h
change_type: ModificationType.MODIFY
diff: @@ -553,6 +553,9 @@ void BinaryProtocolReader::readStringBody(StrType& str, int32_t size) {
   }
 
   if (static_cast<int32_t>(in_.length()) < size) {
+    if (!in_.canAdvance(size)) {
+      protocol::TProtocolException::throwTruncatedData();
+    }
     str.reserve(size); // only reserve for multi iter case below
   }
   str.clear();

programming_language: C++
filename: CompactProtocol-inl.h
change_type: ModificationType.MODIFY
diff: @@ -672,6 +672,9 @@ void CompactProtocolReader::readStringSize(int32_t& size) {
 template <typename StrType>
 void CompactProtocolReader::readStringBody(StrType& str, int32_t size) {
   if (static_cast<int32_t>(in_.length()) < size) {
+    if (!in_.canAdvance(size)) {
+      protocol::TProtocolException::throwTruncatedData();
+    }
     str.reserve(size); // only reserve for multi iter case below
   }
   str.clear();

programming_language: C++
filename: ProtocolTruncatedData.thrift
change_type: ModificationType.MODIFY
diff: @@ -20,4 +20,5 @@ struct TestStruct {
   1: optional list<i64> i64_list,
   2: optional set<i32> i32_set,
   3: optional map<i32,i16> i32_i16_map,
+  4: optional string a_string,
 }

programming_language: Scala
filename: ProtocolTruncatedDataTest.cpp
change_type: ModificationType.MODIFY
diff: @@ -77,3 +77,19 @@ TEST(ProtocolTruncatedDataTest, TruncatedMap) {
   testPartialDataHandling<CompactSerializer>(
       s, 3 /* headers */ + 30 * 2 /* 2b / kv pair */);
 }
+
+TEST(ProtocolTruncatedDataTest, TuncatedString_Compact) {
+  TestStruct s;
+  s.a_string_ref() = "foobarbazstring";
+
+  testPartialDataHandling<CompactSerializer>(
+      s, 2 /* field & length header */ + s.a_string_ref()->size());
+}
+
+TEST(ProtocolTruncatedDataTest, TuncatedString_Binary) {
+  TestStruct s;
+  s.a_string_ref() = "foobarbazstring";
+
+  testPartialDataHandling<BinarySerializer>(
+      s, 7 /* field & length header */ + s.a_string_ref()->size());
+}

programming_language: C++