Skip to content
Permalink
Browse files Browse the repository at this point in the history
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
  • Loading branch information
spalamarchuk authored and facebook-github-bot committed Jan 28, 2020
1 parent 099fe6f commit 3f15620
Show file tree
Hide file tree
Showing 7 changed files with 147 additions and 0 deletions.
7 changes: 7 additions & 0 deletions thrift/lib/cpp/protocol/TProtocolException.cpp
Expand Up @@ -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
1 change: 1 addition & 0 deletions thrift/lib/cpp/protocol/TProtocolException.h
Expand Up @@ -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:
/**
Expand Down
9 changes: 9 additions & 0 deletions thrift/lib/cpp2/protocol/NimbleProtocol.h
Expand Up @@ -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 */,
Expand Down
17 changes: 17 additions & 0 deletions thrift/lib/cpp2/protocol/Protocol.h
Expand Up @@ -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.
*
Expand Down
11 changes: 11 additions & 0 deletions thrift/lib/cpp2/protocol/detail/protocol_methods.h
Expand Up @@ -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) ||
Expand Down Expand Up @@ -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);
};
Expand Down Expand Up @@ -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);
};
Expand Down
23 changes: 23 additions & 0 deletions 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,
}
79 changes: 79 additions & 0 deletions 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 */);
}

0 comments on commit 3f15620

Please sign in to comment.