Skip to content

fuzz: Add a target that feeds arbitrary bytes to V2Transport - #36635

Open
fametrano wants to merge 1 commit into
bitcoin:masterfrom
fametrano:fuzz-v2-transport-arbitrary-bytes
Open

fametrano wants to merge 1 commit into
bitcoin:masterfrom
fametrano:fuzz-v2-transport-arbitrary-bytes

Conversation

@fametrano

@fametrano fametrano commented Oct 23, 2026 •

Copy link
Copy Markdown

No fuzz target feeds V2Transport bytes that an honest peer would not send past the v2 key exchange. I add p2p_transport_v2_receive. It knows the transport's keys, builds the input from arbitrary bytes and from parts of a valid handshake (the peer key, garbage, the terminator, encrypted packets that may be corrupted, and runs of empty decoys that force a rekey), and feeds it in pieces of arbitrary size. Once the transport reports v2, it checks that its session id matches the peer's.

It reaches the v2 receive states and their failures, except the fallback to v1 and the wrong-magic disconnect, which need a v1 version header at the start of the stream; p2p_transport_bidirectional_v1v2 reaches the first. 15 minutes with libFuzzer, ASan and UBSan found no crash.

@DrahtBot

DrahtBot commented Oct 23, 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
Concept ACK jeanpablojp

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

Conflicts

No conflicts as of last run.

const auto& [bytes, more, msg_type] = transport.GetBytesToSend(/*have_next_message=*/false);
if (!bytes.empty()) transport.MarkBytesSent(provider.ConsumeIntegralInRange<size_t>(0, bytes.size()));
}
transport.GetInfo();

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The target calls transport.GetInfo() and drops the result.

The transport reports v2 once it verifies the version packet:

bitcoin/src/net.cpp

Lines 1595 to 1600 in a773e1e

// Do not report v2 and session ID until the version packet has been received
// and verified (confirming that the other side very likely has the same keys as us).
if (m_recv_state != RecvState::KEY_MAYBE_V1 && m_recv_state != RecvState::KEY &&
m_recv_state != RecvState::GARB_GARBTERM && m_recv_state != RecvState::VERSION) {
info.transport_type = TransportProtocolType::V2;
info.session_id = uint256(MakeUCharSpan(m_cipher.GetSessionID()));

At that point its session id should match the peer's. Would an assert on that work? I ran the check for 4 minutes and it didn't fail.

Suggested change
transport.GetInfo();
const auto info{transport.GetInfo()};
if (info.transport_type == TransportProtocolType::V2) {
assert(info.session_id == uint256{MakeUCharSpan(peer.GetSessionID())});
}

Comment on lines +423 to +426
auto ent = provider.ConsumeBytes<std::byte>(32);
ent.resize(32);
auto peer_ent = provider.ConsumeBytes<std::byte>(32);
peer_ent.resize(32);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Suggested change
auto ent = provider.ConsumeBytes<std::byte>(32);
ent.resize(32);
auto peer_ent = provider.ConsumeBytes<std::byte>(32);
peer_ent.resize(32);
const auto ent{ConsumeFixedLengthByteVector<std::byte>(provider, 32)};
const auto peer_ent{ConsumeFixedLengthByteVector<std::byte>(provider, 32)};

nit: I think ConsumeFixedLengthByteVector<std::byte>(provider, 32) does the same consume-then-resize and lets these be const:

[[nodiscard]] inline std::vector<B> ConsumeFixedLengthByteVector(FuzzedDataProvider& fuzzed_data_provider, const size_t length) noexcept

It should read the input the same way.

peer_ent.resize(32);
V2Transport transport{NodeId{0}, initiating, key, ent, /*garbage=*/{}};
BIP324Cipher peer{peer_key, peer_ent};
peer.Initialize(BIP324Cipher{key, ent}.GetOurPubKey(), /*initiator=*/!initiating);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: the BIP324Cipher(key, ent) constructor calls key.EllSwiftCreate(ent) and nothing else:

bitcoin/src/bip324.cpp

Lines 25 to 29 in a773e1e

BIP324Cipher::BIP324Cipher(const CKey& key, std::span<const std::byte> ent32) noexcept
: m_key(key)
{
m_our_pubkey = m_key.EllSwiftCreate(ent32);
}

Maybe call that instead of building a second cipher? It gives the same public key.

Suggested change
peer.Initialize(BIP324Cipher{key, ent}.GetOurPubKey(), /*initiator=*/!initiating);
peer.Initialize(key.EllSwiftCreate(ent), /*initiator=*/!initiating);

Comment on lines +432 to +474
std::vector<uint8_t> stream;
// Garbage appended since the last key, which the first packet after the terminator must
// authenticate.
std::vector<uint8_t> aad;
auto append_fn = [&](std::span<const std::byte> bytes) {
stream.insert(stream.end(), UCharCast(bytes.data()), UCharCast(bytes.data() + bytes.size()));
};
// Flip a bit in stream, at or after position start.
auto flip_fn = [&](size_t start) {
stream[provider.ConsumeIntegralInRange<size_t>(start, stream.size() - 1)] ^= 1 << provider.ConsumeIntegralInRange<unsigned>(0, 7);
};
LIMITED_WHILE (provider.remaining_bytes(), 100) {
CallOneOf(provider,
// Arbitrary bytes.
[&] {
auto bytes = provider.ConsumeBytes<uint8_t>(provider.ConsumeIntegralInRange<size_t>(0, 256));
stream.insert(stream.end(), bytes.begin(), bytes.end());
},
// The peer's key.
[&] {
append_fn(std::span{peer.GetOurPubKey().data(), EllSwiftPubKey::size()});
aad.clear();
},
// Garbage.
[&] {
auto bytes = provider.ConsumeBytes<uint8_t>(provider.ConsumeIntegralInRange<size_t>(0, V2Transport::MAX_GARBAGE_LEN));
stream.insert(stream.end(), bytes.begin(), bytes.end());
aad.insert(aad.end(), bytes.begin(), bytes.end());
},
// The garbage terminator, possibly corrupted.
[&] {
const auto start = stream.size();
append_fn(peer.GetSendGarbageTerminator());
if (provider.ConsumeBool()) flip_fn(start);
},
// A packet, possibly corrupted. The first one after the garbage authenticates it.
[&] {
auto contents = provider.ConsumeBytes<std::byte>(provider.ConsumeIntegralInRange<size_t>(0, 1000));
const bool ignore = provider.ConsumeBool();
const bool corrupt = provider.ConsumeBool();
const auto start = stream.size();
stream.resize(start + contents.size() + BIP324Cipher::EXPANSION);
peer.Encrypt(contents, MakeByteSpan(aad), ignore, MakeWritableByteSpan(stream).subspan(start));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: stream and aad hold uint8_t, but most bytes going in are std::byte. That forces casts both ways: UCharCast in append_fn, and MakeByteSpan / MakeWritableByteSpan for Encrypt.

Maybe store std::byte and convert once with MakeUCharSpan(stream) before ReceivedBytes()? I think that also removes the duplicate insert in the "Arbitrary bytes" and "Garbage" branches, and it reads the input the same way.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

diff:

diff --git a/src/test/fuzz/p2p_transport_serialization.cpp b/src/test/fuzz/p2p_transport_serialization.cpp
index 852994afe..d6e0bd5c5 100644
--- a/src/test/fuzz/p2p_transport_serialization.cpp
+++ b/src/test/fuzz/p2p_transport_serialization.cpp
@@ -429,34 +429,33 @@ FUZZ_TARGET(p2p_transport_v2_receive, .init = initialize_p2p_transport_serializa
     peer.Initialize(BIP324Cipher{key, ent}.GetOurPubKey(), /*initiator=*/!initiating);
 
     // Build the byte stream.
-    std::vector<uint8_t> stream;
+    std::vector<std::byte> stream;
     // Garbage appended since the last key, which the first packet after the terminator must
     // authenticate.
-    std::vector<uint8_t> aad;
+    std::vector<std::byte> aad;
     auto append_fn = [&](std::span<const std::byte> bytes) {
-        stream.insert(stream.end(), UCharCast(bytes.data()), UCharCast(bytes.data() + bytes.size()));
+        stream.insert(stream.end(), bytes.begin(), bytes.end());
     };
     // Flip a bit in stream, at or after position start.
     auto flip_fn = [&](size_t start) {
-        stream[provider.ConsumeIntegralInRange<size_t>(start, stream.size() - 1)] ^= 1 << provider.ConsumeIntegralInRange<unsigned>(0, 7);
+        stream[provider.ConsumeIntegralInRange<size_t>(start, stream.size() - 1)] ^= std::byte{1} << provider.ConsumeIntegralInRange<unsigned>(0, 7);
     };
     LIMITED_WHILE (provider.remaining_bytes(), 100) {
         CallOneOf(provider,
             // Arbitrary bytes.
             [&] {
-                auto bytes = provider.ConsumeBytes<uint8_t>(provider.ConsumeIntegralInRange<size_t>(0, 256));
-                stream.insert(stream.end(), bytes.begin(), bytes.end());
+                append_fn(provider.ConsumeBytes<std::byte>(provider.ConsumeIntegralInRange<size_t>(0, 256)));
             },
             // The peer's key.
             [&] {
-                append_fn(std::span{peer.GetOurPubKey().data(), EllSwiftPubKey::size()});
+                append_fn(peer.GetOurPubKey());
                 aad.clear();
             },
             // Garbage.
             [&] {
-                auto bytes = provider.ConsumeBytes<uint8_t>(provider.ConsumeIntegralInRange<size_t>(0, V2Transport::MAX_GARBAGE_LEN));
-                stream.insert(stream.end(), bytes.begin(), bytes.end());
-                aad.insert(aad.end(), bytes.begin(), bytes.end());
+                const auto garbage{provider.ConsumeBytes<std::byte>(provider.ConsumeIntegralInRange<size_t>(0, V2Transport::MAX_GARBAGE_LEN))};
+                append_fn(garbage);
+                aad.insert(aad.end(), garbage.begin(), garbage.end());
             },
             // The garbage terminator, possibly corrupted.
             [&] {
@@ -471,7 +470,7 @@ FUZZ_TARGET(p2p_transport_v2_receive, .init = initialize_p2p_transport_serializa
                 const bool corrupt = provider.ConsumeBool();
                 const auto start = stream.size();
                 stream.resize(start + contents.size() + BIP324Cipher::EXPANSION);
-                peer.Encrypt(contents, MakeByteSpan(aad), ignore, MakeWritableByteSpan(stream).subspan(start));
+                peer.Encrypt(contents, aad, ignore, std::span{stream}.subspan(start));
                 aad.clear();
                 if (corrupt) flip_fn(start);
             }
@@ -479,7 +478,7 @@ FUZZ_TARGET(p2p_transport_v2_receive, .init = initialize_p2p_transport_serializa
     }
 
     // Receive the stream in pieces, and send what the transport wants to send in between.
-    std::span<const uint8_t> to_recv{stream};
+    std::span<const uint8_t> to_recv{MakeUCharSpan(stream)};
     while (!to_recv.empty()) {
         const size_t piece_len = provider.ConsumeIntegralInRange<size_t>(1, to_recv.size());
         std::span<const uint8_t> piece = to_recv.first(piece_len);

// Bytes must be consumed, or a message returned.
assert(progress);
}
const auto& [bytes, more, msg_type] = transport.GetBytesToSend(/*have_next_message=*/false);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

nit: the code doesn't use more or msg_type.

Suggested change
const auto& [bytes, more, msg_type] = transport.GetBytesToSend(/*have_next_message=*/false);
const auto& [bytes, _more, _msg_type] = transport.GetBytesToSend(/*have_next_message=*/false);

stream.resize(start + contents.size() + BIP324Cipher::EXPANSION);
peer.Encrypt(contents, MakeByteSpan(aad), ignore, MakeWritableByteSpan(stream).subspan(start));
aad.clear();
if (corrupt) flip_fn(start);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

I think the transport never rekeys here. The loop stops at 100 actions, so a stream holds fewer than 100 packets, and the transport rekeys every 224:

static constexpr unsigned REKEY_INTERVAL{224};

Maybe add an action that appends a run of empty decoys? With the diff below, libFuzzer's coverage report shows this rekey branch hit:

void FSChaCha20Poly1305::NextPacket() noexcept
{
if (++m_packet_counter == m_rekey_interval) {

diff --git a/src/test/fuzz/p2p_transport_serialization.cpp b/src/test/fuzz/p2p_transport_serialization.cpp
index 852994afe..c823f669d 100644
--- a/src/test/fuzz/p2p_transport_serialization.cpp
+++ b/src/test/fuzz/p2p_transport_serialization.cpp
@@ -474,6 +474,16 @@ FUZZ_TARGET(p2p_transport_v2_receive, .init = initialize_p2p_transport_serializa
                 peer.Encrypt(contents, MakeByteSpan(aad), ignore, MakeWritableByteSpan(stream).subspan(start));
                 aad.clear();
                 if (corrupt) flip_fn(start);
+            },
+            // A run of empty decoys, so the transport has to rekey (every REKEY_INTERVAL packets).
+            [&] {
+                const auto count{provider.ConsumeIntegralInRange<unsigned>(1, BIP324Cipher::REKEY_INTERVAL)};
+                for (unsigned i{0}; i < count; ++i) {
+                    const auto start = stream.size();
+                    stream.resize(start + BIP324Cipher::EXPANSION);
+                    peer.Encrypt({}, MakeByteSpan(aad), /*ignore=*/true, MakeWritableByteSpan(stream).subspan(start));
+                    aad.clear();
+                }
             }
         );
     }

@fametrano

Copy link
Copy Markdown
Author

@uqlidi thanks, all seven comments are applied in 984a016.

Once the transport reports v2, the target asserts that its session id matches the peer's; with the check inverted it aborts on the new corpus, so the assert is reached. The old target never rekeyed: a new action appends a run of empty decoys, and replaying the corpora counted 0 rekeys before and 854 after, at about half the exec rate. Both entropies are const, from ConsumeFixedLengthByteVector. The peer is initialized from key.EllSwiftCreate(ent). stream and aad hold std::byte. The unused bindings are _more and _msg_type. The refactors read the input the same way: a hash of the stream, the entropy and the bytes left was identical before and after them on all 601 old-corpus inputs with valid keys.

One note on Ralph's report on 0b0fa36: its verifier says the target reaches the wrong-magic disconnect. That branch's log line, net.cpp:1144 at 984a016, had 0 hits in the gist's 10-minute run of the new target and its 5-minute run of the final one (results.txt). This is why the description says the target does not reach it: that path needs a v1 version header at the start of the stream.

I also rebased: master gave initialize_p2p_transport_serialization a reachability goal this target never observes, so it now uses initialize_p2p_transport. Commands and output: https://gist.github.com/fametrano/b1d9da3c3312cae5b1029679828ee023/e168d09e55328bc3b2955680154ea4b4687b8e5c

No fuzz target feeds V2Transport bytes that an honest peer would not
send past the v2 key exchange.

Add p2p_transport_v2_receive. It knows the keys of the transport it
tests, and builds a byte stream from arbitrary bytes and from the parts
of a valid handshake: the peer key, garbage, the garbage terminator,
encrypted packets, which may be corrupted, and runs of empty decoys,
which make the transport rekey. The stream is received in pieces of
arbitrary size.
This reaches the v2 receive states and their failures, except two
that need the 16-byte v1 prefix: the fallback to v1, which
p2p_transport_bidirectional_v1v2 reaches, and the disconnect of a v1
peer with the wrong magic. Once the transport reports v2, its session
id must match the peer's.

@jeanpablojp jeanpablojp 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.

Concept ACK

// Receive the stream in pieces, and send what the transport wants to send in between.
std::span<const uint8_t> to_recv{MakeUCharSpan(stream)};
while (!to_recv.empty()) {
const size_t piece_len = provider.ConsumeIntegralInRange<size_t>(1, to_recv.size());

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.

The description says the stream is fed in pieces of arbitrary size, but once the build loop has used up the input ConsumeIntegralInRange returns 1 here, so 403 of the 430 inputs in your gist's corpus that build a stream are received one byte at a time.

Should the pieces vary for every input, or should the description and the comment at the top of the target say they don't?

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.

4 participants