Skip to content

Hardening: add null guards, bounds checks, and buffer underflow safety to flexbuffers - #9374

Open
anagnorisis2peripeteia wants to merge 1 commit into
google:masterfrom
anagnorisis2peripeteia:fix-flexbuffers-null-guards-and-bounds-safety
Open

anagnorisis2peripeteia wants to merge 1 commit into
google:masterfrom
anagnorisis2peripeteia:fix-flexbuffers-null-guards-and-bounds-safety

Conversation

@anagnorisis2peripeteia

Copy link
Copy Markdown

Summary

This PR hardens include/flatbuffers/flexbuffers.h against null pointer dereferences, buffer underflows, and out-of-bounds access across the reader, builder, and verifier APIs:

  1. GetRoot Underflow & Truncation Protection:

    • GetRoot(buffer, size) requires at least 3 bytes (size >= 3) and validates size >= static_cast<size_t>(byte_width) + 2 before decrementing pointers. Previously, passing a null or zero-length buffer caused pointer arithmetic before the buffer (*--end), triggering heap/stack buffer underflow.
  2. Null Guards in Scalar & Indirect Decoders:

    • ReadSizedScalar, ReadInt64, ReadUInt64, ReadDouble guard against data == nullptr and return safe defaults (0 / 0.0).
    • Indirect checks !offset || byte_width == 0 and returns nullptr.
  3. Null-safe Reference, Vector, and Map Access:

    • Sized::read_size() guards !data_ || byte_width_ == 0.
    • Reference accessor methods (AsInt64, AsDouble, AsBool, AsKey, AsString, AsBlob, AsVector, etc.) guard against !data_ and validate indirect offsets before dereferencing.
    • Reference::Mutate* checks data_ != nullptr, dest != nullptr, and input pointers.
    • Vector::operator[], TypedVector::operator[], FixedTypedVector::operator[] guard !data_.
    • Map::operator[](const char* key) guards against null key and null keys.data_, preventing crashes in std::bsearch and KeyCompare.
  4. Builder and Verifier Input Validation:

    • Builder::Key and Builder::String safely handle null string pointers.
    • Builder::WriteBytes and Builder::CreateAlignedBlob handle null data.
    • Builder::EndVector and Builder::EndMap guard against start > stack_.size().
    • Verifier::VerifyOffset and Verifier::VerifyBuffer validate buf_ != nullptr before pointer comparisons and buffer size checks.
  5. Unit Tests:

    • Added FlexBuffersSafetyTest() in tests/flexbuffers_test.cpp verifying behavior with null buffers, truncated inputs, null map keys, and empty builder calls.
    • Verified clean compilation with -DFLATBUFFERS_STRICT_MODE=ON, flattests, and flatc_cpp_tests.py.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant