fuzz: torcontrol: drive the control connection over a mocked socket #36822

pull erickcestari wants to merge 3 commits into bitcoin:master from erickcestari:fuzz-torcontrol-socket changing 2 files +293 −24
  1. erickcestari commented at 12:06 AM on November 10, 2026: none

    The torcontrol fuzz target hands made-up replies straight to the TorController callbacks, and caps reply lines at 16 characters. As a result, most success paths can't be reached, and the code that parses the control port (ProcessBuffer(), ReceiveAndProcess()) never runs.

    This rewrites the target around a fake Tor on the other end of a real TorControlConnection, connected through DynSock. Replies go over the wire. The fake Tor answers each command the controller sends with a reply of the matching shape, so inputs can complete the whole handshake: PROTOCOLINFO, authentication (including SAFECOOKIE), GETINFO and ADD_ONION. The harness also checks that reply data never splits a command or injects a new one.

    The first commit fixes DynSock::Wait(), which deleted its own socket. The bug has been there since #30205; this target is the first caller.

    Testing

    Line coverage of src/torcontrol.cpp goes from 52% on master to 81% after a 10-minute local run. The master number is from the qa-assets corpus. Most of what remains is the controller thread itself, which the harness replaces, and socket errors that DynSock can't produce.

    The input format changes, so the corpus in qa-assets needs a refresh.

  2. test: fix DynSock::Wait deleting its own socket
    Wait() wrapped `this` in an owning shared_ptr to call WaitMany(), so the
    socket was deleted once that temporary went out of scope.
    345ffe0dae
  3. DrahtBot added the label Fuzzing on Nov 10, 2026
  4. DrahtBot commented at 12:06 AM on November 10, 2026: contributor

    <!--e57a25ab6845829454e8d69fc972939a-->

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

    <!--006a51241073e994b41acfe9ec718e94-->

    External sites

    <!--021abf342d371248e50ceaed478a90ca-->

    Reviews

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

    Type Reviewers
    ACK jpk68
    Concept ACK winterrdog, brunoerg

    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:

    • #36808 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36808.svg"></sub> (iwyu: Fix warnings in src/test/fuzz and treat them as errors by hebasto)
    • #36743 <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36743.svg"></sub> ([RFC] build: build with -Wmissing-declarations/prototypes by fanquake)

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

  5. jpk68 commented at 2:48 AM on November 10, 2026: contributor

    ACK 14b276e7c9e32570b7bc3af8c77db899a9833230

  6. winterrdog commented at 8:24 AM on November 10, 2026: contributor

    concept ACK

  7. brunoerg commented at 4:55 PM on November 11, 2026: contributor

    Concept ACK

  8. fuzz: torcontrol: use a mocked control connection
    Replies used to be handed straight to the TorController callbacks, with
    lines capped at 16 chars, so most success paths and the control port
    parser were never reached. Drive a real TorControlConnection over a
    DynSock instead, and generate the values the fuzzer can't produce.
    43a0761c9f
  9. fuzz: torcontrol: check and answer sent commands
    Random replies almost never got past PROTOCOLINFO. Answer the oldest
    unanswered command with a reply of the matching shape, including the
    SAFECOOKIE server hash, so inputs can walk the whole handshake. Also
    assert that reply data never splits or injects a command.
    14b276e7c9
  10. in src/test/fuzz/torcontrol.cpp:238 in 8aeca1ea75
     258 |              },
     259 |              [&] {
     260 | -                tor_controller.protocolinfo_cb(conn, tor_control_reply);
     261 | +                (void)conn.WaitForData(0ms);
     262 |              },
     263 |              [&] {
    


    brunoerg commented at 5:02 PM on November 11, 2026:

    I think the direct handler calls here (the CallOneOf over protocolinfo_cb … add_onion_cb) hide the paths that need the wire. As far as I tested, no input got past PROTOCOLINFO over the wire.

    Suggestion from my clanker:

    FakeTor records the verb of each command it sees in ProcessCommands(). A new operation answers the oldest unanswered command with a reply of the matching shape (code usually 250, sometimes one of CODES). It reuses the existing line generators, which are split out of ConsumeReplyLine(). All existing operations stay. The direct-call operation is also gated behind one extra ConsumeBool().

    <details><summary>diff</summary>

    diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp
    index 06b6a6faac..d7e4ff99f0 100644
    --- a/src/test/fuzz/torcontrol.cpp
    +++ b/src/test/fuzz/torcontrol.cpp
    @@ -27,6 +27,7 @@
     #include <cassert>
     #include <chrono>
     #include <cstdint>
    +#include <deque>
     #include <memory>
     #include <string>
     #include <string_view>
    @@ -68,6 +69,10 @@ struct FakeTor {
         std::string sent;
         //! From the last AUTHCHALLENGE command, needed to answer with a matching server hash.
         std::vector<uint8_t> client_nonce;
    +    //! Verbs of the commands sent on this connection, oldest first, that Answer() hasn't replied to.
    +    //! Mirrors the controller's reply handler queue unless other operations complete replies too;
    +    //! then the answers are merely mismatched, which is still valid input.
    +    std::deque<std::string> unanswered;
     
         //! The controller keeps its SAFECOOKIE nonce across reconnects, so we do too.
         void NewConnection()
    @@ -76,6 +81,7 @@ struct FakeTor {
             pending.clear();
             written_tail.clear();
             sent.clear();
    +        unanswered.clear();
         }
     
         //! Writes the first `n` queued bytes to the socket.
    @@ -103,6 +109,7 @@ struct FakeTor {
                 // Reply data must never break a command apart or inject a new one.
                 assert(cmd.find_first_of("\r\n") == std::string_view::npos);
                 assert(std::ranges::any_of(VERBS, [&](std::string_view verb) { return cmd.starts_with(verb); }));
    +            unanswered.emplace_back(cmd.substr(0, cmd.find(' ')));
                 if (cmd.starts_with("AUTHCHALLENGE SAFECOOKIE ")) {
                     client_nonce = ParseHex(cmd.substr(std::string_view{"AUTHCHALLENGE SAFECOOKIE "}.size()));
                 }
    @@ -132,52 +139,67 @@ std::vector<uint8_t> SafeCookieHash(std::string_view key, std::span<const uint8_
         return hash;
     }
     
    +std::string ConsumeAuthLine(FuzzedDataProvider& provider)
    +{
    +    static constexpr std::array<std::string_view, 4> METHODS{"NULL", "COOKIE", "SAFECOOKIE", "HASHEDPASSWORD"};
    +    std::string methods;
    +    LIMITED_WHILE(provider.ConsumeBool(), 4) {
    +        if (!methods.empty()) methods += ',';
    +        methods += provider.PickValueInArray(METHODS);
    +    }
    +    return "AUTH METHODS=" + methods + ' ' + provider.PickValueInArray(g_cookie_args);
    +}
    +
    +std::string ConsumeServiceIdLine(FuzzedDataProvider& provider)
    +{
    +    // The fuzzer can't produce the SHA3 checksum of a v3 onion address on its own.
    +    const std::string onion{OnionToString(ConsumeFixedLengthByteVector(provider, ADDR_TORV3_SIZE))};
    +    return "ServiceID=" + onion.substr(0, onion.size() - std::string_view{".onion"}.size());
    +}
    +
    +std::string ConsumePrivateKeyLine(FuzzedDataProvider& provider)
    +{
    +    return "PrivateKey=ED25519-V3:" + EncodeBase64(ConsumeFixedLengthByteVector(provider, 64));
    +}
    +
    +std::string ConsumeSocksLine(FuzzedDataProvider& provider)
    +{
    +    std::string line{"net/listeners/socks="};
    +    LIMITED_WHILE(provider.ConsumeBool(), 4) {
    +        std::string addr{provider.ConsumeBool() ? strprintf("127.0.0.1:%u", provider.ConsumeIntegral<uint16_t>()) : provider.ConsumeRandomLengthString(32)};
    +        if (provider.ConsumeBool()) addr = '"' + addr + '"';
    +        line += addr + ' ';
    +    }
    +    return line;
    +}
    +
    +std::string ConsumeAuthChallengeLine(FuzzedDataProvider& provider, const FakeTor& tor)
    +{
    +    const auto server_nonce{ConsumeFixedLengthByteVector(provider, 32)};
    +    const auto server_hash{provider.ConsumeBool() ?
    +                               SafeCookieHash("Tor safe cookie authentication server-to-controller hash", tor.client_nonce, server_nonce) :
    +                               ConsumeFixedLengthByteVector(provider, 32)};
    +    return "AUTHCHALLENGE SERVERHASH=" + HexStr(server_hash) + " SERVERNONCE=" + HexStr(server_nonce);
    +}
    +
     std::string ConsumeReplyLine(FuzzedDataProvider& provider, const FakeTor& tor)
     {
         std::string line;
         CallOneOf(
             provider,
    -        [&] {
    -            line = provider.ConsumeRandomLengthString(MAX_LINE_LENGTH);
    -        },
    -        [&] {
    -            static constexpr std::array<std::string_view, 4> METHODS{"NULL", "COOKIE", "SAFECOOKIE", "HASHEDPASSWORD"};
    -            std::string methods;
    -            LIMITED_WHILE(provider.ConsumeBool(), 4) {
    -                if (!methods.empty()) methods += ',';
    -                methods += provider.PickValueInArray(METHODS);
    -            }
    -            line = "AUTH METHODS=" + methods + ' ' + provider.PickValueInArray(g_cookie_args);
    -        },
    -        [&] {
    -            // The fuzzer can't produce the SHA3 checksum of a v3 onion address on its own.
    -            const std::string onion{OnionToString(ConsumeFixedLengthByteVector(provider, ADDR_TORV3_SIZE))};
    -            line = "ServiceID=" + onion.substr(0, onion.size() - std::string_view{".onion"}.size());
    -        },
    -        [&] {
    -            line = "PrivateKey=ED25519-V3:" + EncodeBase64(ConsumeFixedLengthByteVector(provider, 64));
    -        },
    -        [&] {
    -            line = "net/listeners/socks=";
    -            LIMITED_WHILE(provider.ConsumeBool(), 4) {
    -                std::string addr{provider.ConsumeBool() ? strprintf("127.0.0.1:%u", provider.ConsumeIntegral<uint16_t>()) : provider.ConsumeRandomLengthString(32)};
    -                if (provider.ConsumeBool()) addr = '"' + addr + '"';
    -                line += addr + ' ';
    -            }
    -        },
    -        [&] {
    -            const auto server_nonce{ConsumeFixedLengthByteVector(provider, 32)};
    -            const auto server_hash{provider.ConsumeBool() ?
    -                                       SafeCookieHash("Tor safe cookie authentication server-to-controller hash", tor.client_nonce, server_nonce) :
    -                                       ConsumeFixedLengthByteVector(provider, 32)};
    -            line = "AUTHCHALLENGE SERVERHASH=" + HexStr(server_hash) + " SERVERNONCE=" + HexStr(server_nonce);
    -        });
    +        [&] { line = provider.ConsumeRandomLengthString(MAX_LINE_LENGTH); },
    +        [&] { line = ConsumeAuthLine(provider); },
    +        [&] { line = ConsumeServiceIdLine(provider); },
    +        [&] { line = ConsumePrivateKeyLine(provider); },
    +        [&] { line = ConsumeSocksLine(provider); },
    +        [&] { line = ConsumeAuthChallengeLine(provider, tor); });
         return line;
     }
     
    +constexpr std::array<int, 4> CODES{TOR_REPLY_OK, TOR_REPLY_UNRECOGNIZED, TOR_REPLY_SYNTAX_ERROR, /*async event=*/650};
    +
     TorControlReply ConsumeReply(FuzzedDataProvider& provider, const FakeTor& tor)
     {
    -    static constexpr std::array<int, 4> CODES{TOR_REPLY_OK, TOR_REPLY_UNRECOGNIZED, TOR_REPLY_SYNTAX_ERROR, /*async event=*/650};
         TorControlReply reply;
         reply.code = provider.ConsumeBool() ? provider.PickValueInArray(CODES) : provider.ConsumeIntegralInRange<int>(0, 999);
         LIMITED_WHILE(provider.ConsumeBool(), 16) {
    @@ -186,6 +208,28 @@ TorControlReply ConsumeReply(FuzzedDataProvider& provider, const FakeTor& tor)
         return reply;
     }
     
    +//! The reply Tor would send to a `verb` command. Usually 250, but any code keeps error paths
    +//! (like the 512 that triggers the ADD_ONION retry without PoW) reachable.
    +TorControlReply ConsumeAnswer(FuzzedDataProvider& provider, const FakeTor& tor, std::string_view verb)
    +{
    +    TorControlReply reply;
    +    reply.code = provider.ConsumeBool() ? provider.PickValueInArray(CODES) : TOR_REPLY_OK;
    +    if (verb == "PROTOCOLINFO") {
    +        reply.lines = {"PROTOCOLINFO 1", ConsumeAuthLine(provider), R"(VERSION Tor="0.4.8.10")", "OK"};
    +    } else if (verb == "AUTHCHALLENGE") {
    +        reply.lines = {ConsumeAuthChallengeLine(provider, tor)};
    +    } else if (verb == "GETINFO") {
    +        reply.lines = {ConsumeSocksLine(provider), "OK"};
    +    } else if (verb == "ADD_ONION") {
    +        reply.lines = {ConsumeServiceIdLine(provider)};
    +        if (provider.ConsumeBool()) reply.lines.push_back(ConsumePrivateKeyLine(provider));
    +        reply.lines.emplace_back("OK");
    +    } else {
    +        reply.lines = {"OK"};
    +    }
    +    return reply;
    +}
    +
     //! Wire format: "<code>-<line>" for all lines but the last, which uses "<code> <line>".
     std::string ConsumeWireReply(FuzzedDataProvider& provider, const TorControlReply& reply)
     {
    @@ -253,6 +297,15 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol)
         LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 1000) {
             CallOneOf(
                 fuzzed_data_provider,
    +            [&] {
    +                // Answer the oldest unanswered command with a reply of the matching type.
    +                if (tor.unanswered.empty()) return;
    +                const std::string verb{std::move(tor.unanswered.front())};
    +                tor.unanswered.pop_front();
    +                tor.pending += ConsumeWireReply(fuzzed_data_provider, ConsumeAnswer(fuzzed_data_provider, tor, verb));
    +                tor.Write(tor.pending.size());
    +                receive();
    +            },
                 [&] {
                     tor.pending += ConsumeWireReply(fuzzed_data_provider, ConsumeReply(fuzzed_data_provider, tor));
                 },
    @@ -273,6 +326,7 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol)
                 },
                 [&] {
                     // Hand a reply straight to a handler, skipping the exchanges that normally precede it.
    +                if (!fuzzed_data_provider.ConsumeBool()) return;
                     TorControlReply reply{ConsumeReply(fuzzed_data_provider, tor)};
                     for (auto& line : reply.lines) RestrictCookieFiles(line);
                     CallOneOf(
    

    </details>


    erickcestari commented at 8:20 PM on November 11, 2026:

    Thanks! I've applied the diff and removed the direct handler entirely since it's not needed anymore, because the fuzzer should be able to reach those state over the wire.

  11. erickcestari force-pushed on Nov 11, 2026
  12. erickcestari requested review from brunoerg on Nov 11, 2026
  13. DrahtBot requested review from winterrdog on Nov 15, 2026

github-metadata-mirror

This is a metadata mirror of the GitHub repository bitcoin/bitcoin. This site is not affiliated with GitHub. Content is generated from a GitHub metadata backup.
generated: 2026-11-16 00:51 UTC

This site is hosted by @0xB10C
More mirrored repositories can be found on mirror.b10c.me