Skip to content

net: reject oversized locators before allocating - #35936

Open
l0rinc wants to merge 4 commits into
bitcoin:masterfrom
l0rinc:l0rinc/reject-oversized-locators
Open

l0rinc wants to merge 4 commits into
bitcoin:masterfrom
l0rinc:l0rinc/reject-oversized-locators

Conversation

@l0rinc

@l0rinc l0rinc commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

Problem: getblocks and getheaders enforce MAX_LOCATOR_SZ only after deserializing locator hashes.
A truncated locator advertising an oversized count makes generic vector deserialization fail before the disconnect check, leaving the peer connected.

Fix: Read the advertised count before allocating hashes and disconnect when it exceeds MAX_LOCATOR_SZ, catching only the size-limit error so other deserialization failures remain non-disconnecting.
Complete oversized locators continue to disconnect without discouragement.

@DrahtBot DrahtBot added the P2P label Aug 7, 2026
@DrahtBot

DrahtBot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

The following sections might be updated with supplementary metadata relevant to reviewers and maintainers.

External sites

Reviews

See the guideline and AI policy for information on the review process.

Type Reviewers
Stale ACK achow101, jeanpablojp

If your review is incorrectly listed, please copy-paste <!--meta-tag:bot-skip--> into the comment that the bot should ignore.

Conflicts

Reviewers, this pull request conflicts with the following ones:

  • #36954 (net: make address overlap impossible when relaying addresses by vasild)
  • #35502 (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt)
  • #35027 (net: add -outboundbind option for outgoing source address by 8144225309)

If you consider this pull request important, please also help to review the conflicting pull requests. Ideally, start with the one that should be merged first.

@DrahtBot

DrahtBot commented Aug 8, 2026

Copy link
Copy Markdown
Contributor

🚧 At least one of the CI tasks failed.
Task iwyu: https://github.com/bitcoin/bitcoin/actions/runs/31227149534/job/93023654808
LLM reason (✨ experimental): CI failed because IWYU reported a headers/include issue (generated “Failure generated from IWYU” and exited non-zero on src/primitives/block.h).

Hints

Try to run the tests locally, according to the documentation. However, a CI failure may still
happen due to a number of reasons, for example:

  • Possibly due to a silent merge conflict (the changes in this pull request being
    incompatible with the current code in the target branch). If so, make sure to rebase on the latest
    commit of the target branch.

  • A sanitizer issue, which can only be found by compiling with the sanitizer and running the
    affected test.

  • An intermittent issue.

Leave a comment here, if you need help tracking down a confusing failure.

@jeanpablojp

Copy link
Copy Markdown
Contributor

Approach ACK. The dedicated exception subtype is the right shape, and the truncated case it targets is fixed.

The same message still leaves the peer connected once the count goes above MAX_SIZE. LIMITED_VECTOR only sees counts that ReadCompactSize accepts, and ReadCompactSize range-checks against MAX_SIZE first, throwing a plain std::ios_base::failure, so a locator advertising more than 33554432 hashes reaches the generic handler in ProcessMessages. I ran your test with COMPACTSIZE(uint64_t{MAX_SIZE} + 1) in place of COMPACTSIZE(MAX_SIZE / sizeof(uint256)): getblocks and getheaders both end with fDisconnect false on 725bf35. Both counts are the same 5 bytes on the wire.

Reading the count without the range check makes Limit the only bound, and that case disconnects too:

-        size_t size = ReadCompactSize(s);
+        const uint64_t size{ReadCompactSize(s, /*range_check=*/false)};
         if (size > Limit) {
             throw LimitedVectorExceededError{size};
         }
-        v.reserve(size);
+        v.reserve(static_cast<size_t>(size));

m_size has to widen to uint64_t with it, since size_t truncates on the 32-bit builds. With that applied the unit suite, p2p_invalid_locator.py and p2p_invalid_messages.py pass.

Reverting only src/net_processing.cpp to 1f53cab and keeping the new test makes net_tests/oversized_locator_handling fail on node.fDisconnect for both message types.

I have tested the code on your head merged onto master 128456b.

Is the case above MAX_SIZE out of scope here on purpose?

@ajtowns ajtowns left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Untested, but looks fine to me.

Comment thread src/primitives/block.h Resolved
@achow101

Copy link
Copy Markdown
Member

ACK 725bf35

@jeanpablojp

Copy link
Copy Markdown
Contributor

tACK 725bf35

@sedited
sedited requested a review from mzumsande August 29, 2026 09:03
Comment thread src/primitives/block.h Outdated
template <size_t Limit, typename Stream>
void LimitedRead(Stream& s)
{
s.ignore(sizeof(DUMMY_VERSION));

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm not very familiar with the serialization code, so I don't have a strong opinion - just a question:
Why did you choose this approach (having to touch CBlockLocator the and serialization code), instead of the existing HEADERS approach that does it locally in net_processing? Should we use one of the two approaches in multiple places for consistency?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think I'd have a slight preference towards using the same approach. Adding another exception, to what should just be normal control flow reads a bit clunky.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

HEADERS processing does it manually because there's a discrepancy between the serialize and deserialize formats -- it's serialized as a vector of cblocks with no transactions since sending the message predated the CBlockHeader structure, but is deserialized as essentially a vector of pairs of CBlockHeader and an ignored compactsize value.

The difference would be something like:

    try {
        locator.LimitedRead<MAX_LOCATOR_SZ>(stream);
        stream >> hash_stop;
        return true;
    } catch (LimitedVectorExceededError& e) {
        LogDebug(BCLog::NET, "%s locator size %u > %u, %s", msg_type, e.m_size, MAX_LOCATOR_SZ, node.DisconnectMsg());
        node.fDisconnect = true;
        return false;
    }

vs

    stream.ignore(4); // dummy version
    size_t loc_sz = ReadCompactSize(stream);
    if (loc_sz > MAX_LOCATOR_SZ) {
        LogDebug(BCLog::NET, "%s locator size %u > %u, %s", msg_type, e.m_size, MAX_LOCATOR_SZ, node.DisconnectMsg());
        node.fDisconnect = true;
        return false;
    }
    locator.vHave.reserve(loc_sz);
    while (loc_sz-- > 0) {
        locator.vHave.emplace_back();
        stream >> locator.vHave.back();
    }
    return true;

which seems worse to me. I don't think the "exception" overhead versus "normal control flow" is a loss here, but losing the encapsulation of dummy-version and vector deserialization is something of a loss.

Just using LIMITED_VECTOR directly in the CBlockLocator serialization function would be slightly simpler than introducing the LimitedRead function, making the non-exceptional path just try { stream >> locator >> hash_stop; return true; }. Would probably change fuzz test behaviour though.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the comments, as @ajtowns also mentioned checking the count locally means we can no longer use ordinary vector deserialization since we've consumed the size already and have to reproduce the element-reading loop in net_processing.

I'm also not a fan of exceptions for control flow, but this is arguably an exceptional case - but I don't think it really matters. Let me know if you have strong opinions and concrete alternative suggestions.

@l0rinc
l0rinc force-pushed the l0rinc/reject-oversized-locators branch 2 times, most recently from 1389e2c to e327916 Compare September 4, 2026 21:03

@l0rinc l0rinc left a comment

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Rebased and addressed @jeanpablojp's finding: counts above MAX_SIZE now also disconnect, with regression coverage alongside the original truncated-locator case. The count remains uint64_t through the limit check to avoid truncation on 32-bit builds. Thanks!

Comment thread src/primitives/block.h Outdated
template <size_t Limit, typename Stream>
void LimitedRead(Stream& s)
{
s.ignore(sizeof(DUMMY_VERSION));

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the comments, as @ajtowns also mentioned checking the count locally means we can no longer use ordinary vector deserialization since we've consumed the size already and have to reproduce the element-reading loop in net_processing.

I'm also not a fan of exceptions for control flow, but this is arguably an exceptional case - but I don't think it really matters. Let me know if you have strong opinions and concrete alternative suggestions.

l0rinc and others added 3 commits December 3, 2026 15:30
Record that truncated `getblocks` and `getheaders` locators leave the peer connected when their advertised count exceeds `MAX_LOCATOR_SZ` and generic vector deserialization fails.

Also characterize the existing `MAX_SIZE` cap when `LIMITED_VECTOR` has a higher explicit limit.
`LIMITED_VECTOR` throws a generic stream failure when the advertised count exceeds its limit.
Add a dedicated subtype so callers can catch that condition without handling unrelated deserialization errors.

Check the formatter limit before the generic `MAX_SIZE` cap so callers get the dedicated error even for counts above `MAX_SIZE`.
Retain the full `uint64_t` count until after both checks, preserving the reported count on 32-bit builds.

Co-authored-by: Anthony Towns <[email protected]>
Co-authored-by: JP <[email protected]>
Share locator deserialization and the existing `MAX_LOCATOR_SZ` check between `getblocks` and `getheaders`.
`getblocks` and `getheaders` apply `MAX_LOCATOR_SZ` only after deserializing locator hashes.
A truncated locator with an oversized count fails generic vector deserialization before that check, leaving the peer connected.

Use `LIMITED_VECTOR` in the shared locator reader to detect the oversized count before allocating hashes.
The shared reader catches only `LimitedVectorExceededError` and disconnects the peer.
Other deserialization failures keep following the generic non-disconnecting exception path.

Complete oversized locators continue to disconnect without discouragement.
`p2p_invalid_locator.py` verifies that both messages accept 101 hashes and disconnect at 102.

Co-authored-by: Anthony Towns <[email protected]>
@l0rinc
l0rinc force-pushed the l0rinc/reject-oversized-locators branch from e327916 to 23293a4 Compare December 3, 2026 14:30
@l0rinc

l0rinc commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Rebased and simplified a bit more. Oversized getblocks and getheaders locators now disconnect before allocation, including counts above MAX_SIZE, while unrelated deserialization failures keep their existing behavior. The limit handling stays local to the shared locator reader, preserves LIMITED_VECTOR’s global cap, and avoids the extra CBlockLocator API.

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.

7 participants