net: reject oversized locators before allocating #35936

Open
l0rinc wants to merge 4 commits from l0rinc/reject-oversized-locators into master AGit
l0rinc commented 2026-08-07 23:26:46 +00:00 (Migrated from github.com)

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.

**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 commented 2026-08-07 23:26:53 +00:00 (Migrated from github.com)

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.

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/35936 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/35936.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/35936#author-ralph <!--021abf342d371248e50ceaed478a90ca--> ### Reviews See [the guideline](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#code-review) and [AI policy](https://github.com/bitcoin/bitcoin/blob/master/doc/AI_POLICY.md) for information on the review process. | Type | Reviewers | | ---- | --------- | | Stale ACK | [achow101](https://github.com/bitcoin/bitcoin/pull/35936#issuecomment-5320659000), [jeanpablojp](https://github.com/bitcoin/bitcoin/pull/35936#issuecomment-5348373195) | If your review is incorrectly listed, please copy-paste <code>&lt;!--meta-tag:bot-skip--&gt;</code> into the comment that the bot should ignore. <!--174a7506f384e20aa4161008e828411d--> ### Conflicts Reviewers, this pull request conflicts with the following ones: * [#36954](https://github.com/bitcoin/bitcoin/pull/36954) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36954.svg"></sub> (net: make address overlap impossible when relaying addresses by vasild) * [#35502](https://github.com/bitcoin/bitcoin/pull/35502) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35502.svg"></sub> (refactor: extract per-message helpers from ProcessMessage (move-only) by w0xlt) * [#35027](https://github.com/bitcoin/bitcoin/pull/35027) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35027.svg"></sub> (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. <!--5faf32d7da4f0f540f40219e4f7537a3-->
DrahtBot commented 2026-08-08 00:20:23 +00:00 (Migrated from github.com)

🚧 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.

<!--85328a0da195eb286784d51f73fa0af9--> 🚧 At least one of the CI tasks failed. <sub>Task `iwyu`: https://github.com/bitcoin/bitcoin/actions/runs/31227149534/job/93023654808</sub> <sub>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`).</sub> <details><summary>Hints</summary> 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. </details>
jeanpablojp commented 2026-08-09 14:12:51 +00:00 (Migrated from github.com)

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 725bf357d9ef652eacd809a1bf2f6f79ec73a0b4. 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?

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 725bf357d9ef652eacd809a1bf2f6f79ec73a0b4. 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: ```diff - 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 (Migrated from github.com) reviewed 2026-08-09 23:50:52 +00:00
ajtowns (Migrated from github.com) left a comment

Untested, but looks fine to me.

Untested, but looks fine to me.
ajtowns (Migrated from github.com) commented 2026-08-09 23:49:03 +00:00

I think s.ignore(4); would be better; we don't do ignore(sizeof(..)) anywhere else, as far as I can see, and it just seems to be added indirection.

I think `s.ignore(4);` would be better; we don't do `ignore(sizeof(..))` anywhere else, as far as I can see, and it just seems to be added indirection.
l0rinc (Migrated from github.com) reviewed 2026-08-10 01:56:27 +00:00
l0rinc (Migrated from github.com) commented 2026-08-10 01:56:27 +00:00

it just seems to be added indirection

I wanted to ignore adding a code comment here explaining the meaning of the magic constant, which DUMMY_VERSION already does.
We're basically skipping over the version field which "ignore size of version" documents with code nicely.
Let me know if you feel strongly about it and I'll change it, but I did this deliberately.

> it just seems to be added indirection I wanted to ignore adding a code comment here explaining the meaning of the magic constant, which `DUMMY_VERSION` already does. We're basically skipping over the version field which "ignore size of version" documents with code nicely. Let me know if you feel strongly about it and I'll change it, but I did this deliberately.
achow101 commented 2026-08-17 21:48:40 +00:00 (Migrated from github.com)

ACK 725bf357d9ef652eacd809a1bf2f6f79ec73a0b4

ACK 725bf357d9ef652eacd809a1bf2f6f79ec73a0b4
jeanpablojp commented 2026-08-19 21:45:31 +00:00 (Migrated from github.com)

tACK 725bf357d9ef652eacd809a1bf2f6f79ec73a0b4

tACK 725bf357d9ef652eacd809a1bf2f6f79ec73a0b4
mzumsande (Migrated from github.com) reviewed 2026-09-01 13:36:54 +00:00
mzumsande (Migrated from github.com) commented 2026-09-01 13:36:00 +00:00

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?

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?
sedited (Migrated from github.com) reviewed 2026-09-01 16:22:23 +00:00
sedited (Migrated from github.com) commented 2026-09-01 16:22:23 +00:00

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.

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.
ajtowns (Migrated from github.com) reviewed 2026-09-01 20:54:24 +00:00
ajtowns (Migrated from github.com) commented 2026-09-01 20:54:24 +00:00

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.

`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: ```c++ 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 ```c++ 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.
l0rinc (Migrated from github.com) reviewed 2026-09-04 21:05:28 +00:00
l0rinc (Migrated from github.com) left a comment

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!

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!
l0rinc (Migrated from github.com) commented 2026-09-04 20:51:08 +00:00

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.

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.
First-time contributor

Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments.

🔵 Suggestion · limited_vector tests do not check allocation-free rejection

Although the formatter currently rejects before reserve(), its new tests can still pass if that allocation moves above the size checks.

Location: src/test/serialize_tests.cpp:329 (head).

Review coverage was incomplete.


Reviewed: 23293a4d8a00 · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:e1a29e5e677c47d383756f0fcf8f3760725c91d1104dd3ccb2f333b6217eba26:47880f5569fd2047d249266f337c4f2a509adf7d96c3ccb1c7644c2c2a650bff --> <!-- ralph-base:19209e520634ea5e55757895229fe2881105b71e --> <!-- ralph-head:23293a4d8a00a960c96f5b709f62d75ea58e7ca9 --> <!-- ralph-case:618b1870a1b91961db277446afedbc448a07fe60d2980c526308e6e7f4bcbfbb --> Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · `limited_vector` tests do not check allocation-free rejection** Although the formatter currently rejects before `reserve()`, its new tests can still pass if that allocation moves above the size checks. Location: [`src/test/serialize_tests.cpp:329`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/23293a4d8a00a960c96f5b709f62d75ea58e7ca9/src/test/serialize_tests.cpp#L329>) (head). Review coverage was incomplete. <!-- Review tier: sensitive --> --- Reviewed: [`23293a4d8a00`](<https://git.fish.foo/bitcoin/bitcoin/commit/23293a4d8a00a960c96f5b709f62d75ea58e7ca9>) · [Review report](<https://review.fish.foo/report/35936-23293a4d8a00a960c96f5b709f62d75ea58e7ca9-3487-3.html>) · [Previous reports](<https://review.fish.foo/traces/35936/>) [permalink](<https://review.fish.foo/report/35936-23293a4d8a00a960c96f5b709f62d75ea58e7ca9-3487-3.html>)
l0rinc commented 2026-12-03 14:33:49 +00:00 (Migrated from github.com)

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.

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 in to join this conversation.
No reviewers
No milestone
No project
No assignees
2 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set

Reference
bitcoin/bitcoin!35936
No description provided.