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

Open
erickcestari wants to merge 8 commits from fuzz-torcontrol-socket into master AGit
erickcestari commented 2026-11-10 00:06:02 +00:00 (Migrated from github.com)

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.

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.
DrahtBot commented 2026-11-10 00:06:11 +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
ACK winterrdog
Concept ACK brunoerg
Stale ACK jpk68

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.

<!--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/36822 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36822.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36822#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 | | ---- | --------- | | ACK | [winterrdog](https://github.com/bitcoin/bitcoin/pull/36822#pullrequestreview-6176214122) | | Concept ACK | [brunoerg](https://github.com/bitcoin/bitcoin/pull/36822#issuecomment-6801919012) | | Stale ACK | [jpk68](https://github.com/bitcoin/bitcoin/pull/36822#issuecomment-6757554695) | 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 No conflicts as of last run. <!--5faf32d7da4f0f540f40219e4f7537a3-->
First-time contributor

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

🔵 Suggestion · Offered() counts authentication methods from discarded replies

The fuzz oracle accepts methods advertised only in discarded replies or superseded METHODS lists, so it can miss regressions that authenticate using data the controller should ignore.

Location: src/test/fuzz/torcontrol.cpp:190 (head).

🔵 Suggestion · Command splitting hides embedded delimiters from the framing check

The fuzz target's framing assertions can accept an injected command beginning with an allowed verb because they run after \r\n splitting; no current production injection is established.

Location: src/test/fuzz/torcontrol.cpp:233 (head).

Review coverage was incomplete.


Reviewed: fdc08cbc96af · Review report · Previous reports

permalink

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:e1a29e5e677c47d383756f0fcf8f3760725c91d1104dd3ccb2f333b6217eba26:47880f5569fd2047d249266f337c4f2a509adf7d96c3ccb1c7644c2c2a650bff --> <!-- ralph-base:8e5a5a25dad4744219c579589231feff3f0b6d47 --> <!-- ralph-head:fdc08cbc96af4aae8e5b0f943ca2066e416b432f --> <!-- ralph-case:c021e42f3e456b8aca9f7ac26d6cb74f63f7c99a95943744fafa7087287e83ea --> Earlier concerns neither republished nor resolved: 1 suggestion. See the Run archive linked from the Review report for their assessments. **🔵 Suggestion · `Offered()` counts authentication methods from discarded replies** The fuzz oracle accepts methods advertised only in discarded replies or superseded `METHODS` lists, so it can miss regressions that authenticate using data the controller should ignore. Location: [`src/test/fuzz/torcontrol.cpp:190`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fdc08cbc96af4aae8e5b0f943ca2066e416b432f/src/test/fuzz/torcontrol.cpp#L190>) (head). **🔵 Suggestion · Command splitting hides embedded delimiters from the framing check** The fuzz target's framing assertions can accept an injected command beginning with an allowed verb because they run after `\r\n` splitting; no current production injection is established. Location: [`src/test/fuzz/torcontrol.cpp:233`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/fdc08cbc96af4aae8e5b0f943ca2066e416b432f/src/test/fuzz/torcontrol.cpp#L233>) (head). Review coverage was incomplete. <!-- Review tier: standard --> --- Reviewed: [`fdc08cbc96af`](<https://git.fish.foo/bitcoin/bitcoin/commit/fdc08cbc96af4aae8e5b0f943ca2066e416b432f>) · [Review report](<https://review.fish.foo/report/36822-fdc08cbc96af4aae8e5b0f943ca2066e416b432f-3448-7.html>) · [Previous reports](<https://review.fish.foo/traces/36822/>) [permalink](<https://review.fish.foo/report/36822-fdc08cbc96af4aae8e5b0f943ca2066e416b432f-3448-7.html>)
jpk68 commented 2026-11-10 02:48:40 +00:00 (Migrated from github.com)
ACK 14b276e7c9e32570b7bc3af8c77db899a9833230
winterrdog (Migrated from github.com) reviewed 2026-11-10 08:24:47 +00:00
winterrdog (Migrated from github.com) left a comment

concept ACK

concept ACK
brunoerg commented 2026-11-11 16:55:10 +00:00 (Migrated from github.com)

Concept ACK

Concept ACK
brunoerg (Migrated from github.com) reviewed 2026-11-11 17:02:18 +00:00
brunoerg (Migrated from github.com) commented 2026-11-11 17:02:18 +00:00

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().

diff
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(
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 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 (Migrated from github.com) reviewed 2026-11-11 20:20:38 +00:00
erickcestari (Migrated from github.com) commented 2026-11-11 20:20:38 +00:00

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.

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.
frankomosh (Migrated from github.com) reviewed 2026-11-17 09:42:13 +00:00
frankomosh (Migrated from github.com) left a comment

Reviewed 345ffe0dae

Reviewed 345ffe0dae75b5929e8285d1dcedf182ca5d0328
frankomosh (Migrated from github.com) commented 2026-11-17 09:38:49 +00:00

Could we drop DynSock::Wait() entirely instead? The base Sock::Wait() already handles this without taking ownership of the socket, and DynSock::WaitMany() always returns true, so the behavior should remain unchanged.

Leaving this to the base Sock implementation might also make things simpler for anyone working in this area in the future.

If you agree, perhaps something like this would work:

diff
--- a/src/test/util/net.cpp
+++ b/src/test/util/net.cpp
@@ -330,20 +330,6 @@ std::unique_ptr<Sock> DynSock::Accept(sockaddr* addr, socklen_t* addr_len) const
     return m_accept_sockets->Pop().value_or(nullptr);
 }
-bool DynSock::Wait(std::chrono::milliseconds timeout,
-                   Event requested,
-                   Event* occurred) const
-{
-    EventsPerSock ev;
-    // Non-owning: an owning shared_ptr would delete this socket when `ev` goes out of scope.
-    ev.emplace(std::shared_ptr<const Sock>{this, [](const Sock*) {}}, Events{requested});
-    const bool ret{WaitMany(timeout, ev)};
-    if (occurred != nullptr) {
-        *occurred = ev.begin()->second.occurred;
-    }
-    return ret;
-}
-
 bool DynSock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const
 {
     const auto deadline = std::chrono::steady_clock::now() + timeout;

--- a/src/test/util/net.h
+++ b/src/test/util/net.h
@@ -334,10 +334,6 @@ public:
     std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override;
-    bool Wait(std::chrono::milliseconds timeout,
-              Event requested,
-              Event* occurred = nullptr) const override;
-
     bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override;
 private:
Could we drop `DynSock::Wait()` entirely instead? The base `Sock::Wait()` already handles this without taking ownership of the socket, and `DynSock::WaitMany()` always returns `true`, so the behavior should remain unchanged. Leaving this to the base `Sock` implementation might also make things simpler for anyone working in this area in the future. If you agree, perhaps something like this would work: <details> <summary> diff </summary> ```diff --- a/src/test/util/net.cpp +++ b/src/test/util/net.cpp @@ -330,20 +330,6 @@ std::unique_ptr<Sock> DynSock::Accept(sockaddr* addr, socklen_t* addr_len) const return m_accept_sockets->Pop().value_or(nullptr); } -bool DynSock::Wait(std::chrono::milliseconds timeout, - Event requested, - Event* occurred) const -{ - EventsPerSock ev; - // Non-owning: an owning shared_ptr would delete this socket when `ev` goes out of scope. - ev.emplace(std::shared_ptr<const Sock>{this, [](const Sock*) {}}, Events{requested}); - const bool ret{WaitMany(timeout, ev)}; - if (occurred != nullptr) { - *occurred = ev.begin()->second.occurred; - } - return ret; -} - bool DynSock::WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const { const auto deadline = std::chrono::steady_clock::now() + timeout; --- a/src/test/util/net.h +++ b/src/test/util/net.h @@ -334,10 +334,6 @@ public: std::unique_ptr<Sock> Accept(sockaddr* addr, socklen_t* addr_len) const override; - bool Wait(std::chrono::milliseconds timeout, - Event requested, - Event* occurred = nullptr) const override; - bool WaitMany(std::chrono::milliseconds timeout, EventsPerSock& events_per_sock) const override; private: ``` </details>
erickcestari (Migrated from github.com) reviewed 2026-11-17 12:59:43 +00:00
erickcestari (Migrated from github.com) commented 2026-11-17 12:59:43 +00:00

Thanks for the review! Makes sense for me, but DynSock inherits from ZeroSock, whose Wait() returns all requested events immediately, so removing the override would make Wait() resolve to ZeroSock::Wait() rather than Sock::Wait(). I've instead made DynSock::Wait() delegate directly to Sock::Wait(), which reuses its non-owning wrap.

Thanks for the review! Makes sense for me, but `DynSock` inherits from `ZeroSock`, whose `Wait()` returns all requested events immediately, so removing the override would make `Wait()` resolve to `ZeroSock::Wait()` rather than `Sock::Wait()`. I've instead made `DynSock::Wait()` delegate directly to `Sock::Wait()`, which reuses its non-owning wrap.
frankomosh (Migrated from github.com) reviewed 2026-11-19 10:23:04 +00:00
frankomosh (Migrated from github.com) commented 2026-11-19 09:37:46 +00:00

In SAFECOOKIE authentication, the controller should only send its AUTHENTICATE proof after verifying Tor's SERVERHASH (torcontrol.cpp:639). Currently, flipping that check either way still passes this target as well as other tests I have looked at.

FakeTor already knows when it has sent a correct server hash, so it could record the corresponding expected client hash and assert that every AUTHENTICATE <hash> matches one of those recorded hashes.

Patch if useful
@@ -29,6 +29,7 @@
 #include <cstdint>
 #include <deque>
 #include <memory>
+#include <set>
 #include <string>
 #include <string_view>
 #include <vector>
@@ -73,6 +74,9 @@ struct FakeTor {
     //! Verbs of the commands not yet answered on this connection, oldest first. Other operations can
     //! also complete replies, so this may drift from the controller's queue; that's still valid input.
     std::deque<std::string> unanswered;
+    //! Client hashes for server nonces we answered with a correct SERVERHASH. Mutable, as the reply
+    //! generators only get a const FakeTor.
+    mutable std::set<std::string> proven_client_hashes;

     void NewConnection()
     {
@@ -110,6 +114,10 @@ struct FakeTor {
             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(' ')));
+            // SAFECOOKIE: the controller may only send its proof to a server that proved it knows the cookie.
+            if (cmd.starts_with("AUTHENTICATE ") && !cmd.starts_with("AUTHENTICATE \"")) {
+                assert(proven_client_hashes.contains(std::string{cmd.substr(std::string_view{"AUTHENTICATE "}.size())}));
+            }
             if (cmd.starts_with("AUTHCHALLENGE SAFECOOKIE ")) {
                 client_nonce = ParseHex(cmd.substr(std::string_view{"AUTHCHALLENGE SAFECOOKIE "}.size()));
             }
@@ -176,9 +184,11 @@ std::string ConsumeSocksLine(FuzzedDataProvider& provider)
 std::string ConsumeAuthChallengeLine(FuzzedDataProvider& provider, const FakeTor& tor)
 {
     const auto server_nonce{ConsumeFixedLengthByteVector(provider, 32)};
-    const auto server_hash{provider.ConsumeBool() ?
+    const bool correct{provider.ConsumeBool()};
+    const auto server_hash{correct ?
                                SafeCookieHash("Tor safe cookie authentication server-to-controller hash", tor.client_nonce, server_nonce) :
                                ConsumeFixedLengthByteVector(provider, 32)};
+    if (correct) tor.proven_client_hashes.insert(HexStr(SafeCookieHash("Tor safe cookie authentication controller-to-server hash", tor.client_nonce, server_nonce)));
     return "AUTHCHALLENGE SERVERHASH=" + HexStr(server_hash) + " SERVERNONCE=" + HexStr(server_nonce);
 }
In SAFECOOKIE authentication, the controller should only send its `AUTHENTICATE` proof after verifying Tor's `SERVERHASH` (`torcontrol.cpp:639`). Currently, flipping that check either way still passes this target as well as other tests I have looked at. `FakeTor` already knows when it has sent a correct server hash, so it could record the corresponding expected client hash and assert that every `AUTHENTICATE <hash>` matches one of those recorded hashes. <details> <summary>Patch if useful</summary> ```diff @@ -29,6 +29,7 @@ #include <cstdint> #include <deque> #include <memory> +#include <set> #include <string> #include <string_view> #include <vector> @@ -73,6 +74,9 @@ struct FakeTor { //! Verbs of the commands not yet answered on this connection, oldest first. Other operations can //! also complete replies, so this may drift from the controller's queue; that's still valid input. std::deque<std::string> unanswered; + //! Client hashes for server nonces we answered with a correct SERVERHASH. Mutable, as the reply + //! generators only get a const FakeTor. + mutable std::set<std::string> proven_client_hashes; void NewConnection() { @@ -110,6 +114,10 @@ struct FakeTor { 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(' '))); + // SAFECOOKIE: the controller may only send its proof to a server that proved it knows the cookie. + if (cmd.starts_with("AUTHENTICATE ") && !cmd.starts_with("AUTHENTICATE \"")) { + assert(proven_client_hashes.contains(std::string{cmd.substr(std::string_view{"AUTHENTICATE "}.size())})); + } if (cmd.starts_with("AUTHCHALLENGE SAFECOOKIE ")) { client_nonce = ParseHex(cmd.substr(std::string_view{"AUTHCHALLENGE SAFECOOKIE "}.size())); } @@ -176,9 +184,11 @@ std::string ConsumeSocksLine(FuzzedDataProvider& provider) std::string ConsumeAuthChallengeLine(FuzzedDataProvider& provider, const FakeTor& tor) { const auto server_nonce{ConsumeFixedLengthByteVector(provider, 32)}; - const auto server_hash{provider.ConsumeBool() ? + const bool correct{provider.ConsumeBool()}; + const auto server_hash{correct ? SafeCookieHash("Tor safe cookie authentication server-to-controller hash", tor.client_nonce, server_nonce) : ConsumeFixedLengthByteVector(provider, 32)}; + if (correct) tor.proven_client_hashes.insert(HexStr(SafeCookieHash("Tor safe cookie authentication controller-to-server hash", tor.client_nonce, server_nonce))); return "AUTHCHALLENGE SERVERHASH=" + HexStr(server_hash) + " SERVERNONCE=" + HexStr(server_nonce); } ``` </details>
frankomosh (Migrated from github.com) commented 2026-11-19 10:17:55 +00:00

Yes, that looks good, sorry I missed the ZeroSock, thanks.

As a possible follow-up, a small unit test that DynSock::Wait() reports not-ready on an empty pipe and ready once data arrives.., would lock in both this fix and the ZeroSock distinction.

Yes, that looks good, sorry I missed the `ZeroSock`, thanks. As a possible follow-up, a small unit test that `DynSock::Wait()` reports not-ready on an empty pipe and ready once data arrives.., would lock in both this fix and the `ZeroSock` distinction.
erickcestari (Migrated from github.com) reviewed 2026-11-19 17:42:51 +00:00
erickcestari (Migrated from github.com) commented 2026-11-19 17:42:51 +00:00

Nice! I've added the oracle to verify if the bitcoin node is sending the correct server hash, along others such as: each SAFECOOKIE client nonce is 32 bytes and never repeats. I've also added an assert that tor receives -torpassword exactly as configured, which catch the same issue being fixed by #36637.

I'll let the -torpassword oracle as a follow-up after this PR and that one get merged.

Nice! I've added the oracle to verify if the bitcoin node is sending the correct server hash, along others such as: each `SAFECOOKIE` client nonce is 32 bytes and never repeats. I've also added an assert that tor receives `-torpassword` exactly as configured, which catch the same issue being fixed by #36637. I'll let the `-torpassword` oracle as a follow-up after this PR and that one get merged.
winterrdog (Migrated from github.com) reviewed 2026-11-25 13:43:13 +00:00
winterrdog (Migrated from github.com) commented 2026-11-20 14:48:01 +00:00

non-blocking style nit: just wondering why a struct was chosen over a class here

generally, most readers will see a struct and expect a plain bundle of data, where each member can be touched on its own. this one has more going on: Write() keeps pending and written_tail consistent, and NewConnection() has to reset everything except client_nonce.

for this use case a class kind of looks like the more readable option. what do you think ?

_non-blocking_ style nit: just wondering why a `struct` was chosen over a `class` here generally, most readers will see a `struct` and expect a plain bundle of data, where each member can be touched on its own. this one has more going on: `Write()` keeps `pending` and `written_tail` consistent, and `NewConnection()` has to reset everything except `client_nonce`. for this use case a `class` kind of looks like the more readable option. what do you think ?
winterrdog (Migrated from github.com) commented 2026-11-25 00:30:58 +00:00

nit: arg is used in the if (password.empty()), it can be moved into that scope since that's where its only usage is

**nit**: `arg` is used in the `if (password.empty())`, it can be moved into that scope since that's where its only usage is
winterrdog (Migrated from github.com) commented 2026-11-25 00:21:16 +00:00

i think it is safe to leave out the COOKIE authentication method. the controller never uses it (it only acts on NULL, SAFECOOKIE and HASHEDPASSWORD) so offering it does not reach any new code, and the Tor control spec discourages it anyway

i think it is safe to leave out the `COOKIE` authentication method. the controller never uses it (it only acts on `NULL`, `SAFECOOKIE` and `HASHEDPASSWORD`) so offering it does not reach any new code, and the Tor control spec [discourages](https://spec.torproject.org/control-spec/implementation-notes.html?highlight=__#:~:text=using%20the%20%22COOKIE,version%20of%20Tor.) it anyway
winterrdog (Migrated from github.com) commented 2026-11-19 12:01:17 +00:00

CreateSock is restored by hand at the end of the target. if anything exits early (an exception, for instance), the restoration is skipped and CreateSock is left using tor after tor is gone

it can be restored with a minimal RAII guard instead, so it is put back on every exit path

diff
diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp
index d4db80b349..64ab04c5b7 100644
--- a/src/test/fuzz/torcontrol.cpp
+++ b/src/test/fuzz/torcontrol.cpp
@@ -274,7 +274,12 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol)
     gArgs.ForceSetArg("-torpassword", torpassword);

     FakeTor tor;
-    auto create_sock_orig{CreateSock};
+
+    struct RestoreCreateSock {
+        ~RestoreCreateSock() { CreateSock = original; }
+    private:
+        decltype(CreateSock) original{CreateSock};
+    } restore_create_sock;
     CreateSock = [&tor](int, int, int) { return std::make_unique<DynSock>(tor.pipes); };

     TorController tor_controller;
@@ -329,6 +334,4 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol)
             });
         tor.ProcessCommands();
     }
-
-    CreateSock = create_sock_orig;
 }
`CreateSock` is restored by hand at the [end](https://github.com/erickcestari/bitcoin/blob/a0a7c77289dc260a8de7ddc7ff1ae54fa3436cab/src/test/fuzz/torcontrol.cpp#L467) of the target. if anything exits early (an exception, for instance), the restoration is skipped and `CreateSock` is left using `tor` after `tor` is gone it can be restored with a minimal RAII guard instead, so it is put back on every exit path <details><summary>diff</summary> ```diff diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp index d4db80b349..64ab04c5b7 100644 --- a/src/test/fuzz/torcontrol.cpp +++ b/src/test/fuzz/torcontrol.cpp @@ -274,7 +274,12 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol) gArgs.ForceSetArg("-torpassword", torpassword); FakeTor tor; - auto create_sock_orig{CreateSock}; + + struct RestoreCreateSock { + ~RestoreCreateSock() { CreateSock = original; } + private: + decltype(CreateSock) original{CreateSock}; + } restore_create_sock; CreateSock = [&tor](int, int, int) { return std::make_unique<DynSock>(tor.pipes); }; TorController tor_controller; @@ -329,6 +334,4 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol) }); tor.ProcessCommands(); } - - CreateSock = create_sock_orig; } ``` </details>
winterrdog (Migrated from github.com) reviewed 2026-11-25 13:43:20 +00:00
winterrdog (Migrated from github.com) commented 2026-11-25 13:43:20 +00:00

now that #36637 is merged, the only thing the -torpassword oracle is waiting on is this PR itself, and it is a change to this same file. could it go in here after a rebase ?

i do not see any harm in adding it here; it avoids a follow-up PR. but, if there is a reason to keep it separate (e.g. not wanting to restart review or keeping the diff smaller), that is fine, just curious what it is

now that #36637 is merged, the only thing the `-torpassword` oracle is waiting on is this PR itself, and it is a change to this same file. could it go in here after a rebase ? i do not see any harm in adding it here; it avoids a follow-up PR. but, if there is a reason to keep it separate (e.g. not wanting to restart review or keeping the diff smaller), that is fine, just curious what it is
erickcestari (Migrated from github.com) reviewed 2026-11-25 17:18:31 +00:00
erickcestari (Migrated from github.com) commented 2026-11-25 17:18:31 +00:00

Updated!

Updated!
erickcestari (Migrated from github.com) reviewed 2026-11-25 17:18:35 +00:00
erickcestari (Migrated from github.com) commented 2026-11-25 17:18:35 +00:00

Updated!

Updated!
erickcestari (Migrated from github.com) reviewed 2026-11-25 17:18:42 +00:00
erickcestari (Migrated from github.com) commented 2026-11-25 17:18:42 +00:00

I think is worth as a regression test. Let's say if a day bitcoin core makes a change and for some reason start parsing COOKIE messages. It's also a one line change that shouldn't decrease much the efficiency of the fuzz target.

I think is worth as a regression test. Let's say if a day bitcoin core makes a change and for some reason start parsing `COOKIE` messages. It's also a one line change that shouldn't decrease much the efficiency of the fuzz target.
erickcestari (Migrated from github.com) reviewed 2026-11-25 17:18:46 +00:00
erickcestari (Migrated from github.com) commented 2026-11-25 17:18:46 +00:00

The harness drives FakeTor's state directly (pending, unanswered, pipes and others), so as a class everything would still be public. Hiding it would mean adding accessors to a test fake, which doesn't seem worth it. Stateful structs with methods are common in the fuzz tests, SimTxGraph for example, so I'll keep it as is.

The harness drives `FakeTor`'s state directly (pending, unanswered, pipes and others), so as a class everything would still be public. Hiding it would mean adding accessors to a test fake, which doesn't seem worth it. Stateful `structs` with methods are common in the fuzz tests, `SimTxGraph` for example, so I'll keep it as is.
winterrdog (Migrated from github.com) reviewed 2026-11-25 17:25:08 +00:00
winterrdog (Migrated from github.com) commented 2026-11-25 17:25:08 +00:00

👍understood! this can be resolved

👍understood! this can be resolved
winterrdog (Migrated from github.com) reviewed 2026-11-25 18:28:07 +00:00
winterrdog (Migrated from github.com) commented 2026-11-25 18:28:07 +00:00

Note

EDIT: ignore this. i was reading from an old patchset 🤦‍♂️. it's been handled therefore it's resolved

shouldn't decrease much the efficiency of the fuzz target.

fair point that it is cheap. my concern is more about the confusion it could cause: the controller does not handle COOKIE, and the spec marks it as deprecated and unsafe, so it seems very unlikely to ever be supported

offering it in the fuzzer could give the impression that there is some code handling it, and someone might go out looking for it

if you would rather keep it as a regression guard, could we add a short comment explaining that it is intentionally offered to check that it stays ignored ?

    // the COOKIE auth method is deprecated and the controller ignores it. Kept to check it stays ignored.
    static constexpr std::array<std::string_view, 4> METHODS{"NULL", "COOKIE", "SAFECOOKIE", "HASHEDPASSWORD"};
> [!NOTE] > **EDIT**: ignore this. i was reading from an old patchset 🤦‍♂️. it's been handled therefore it's resolved > shouldn't decrease much the efficiency of the fuzz target. ~~fair point that it is cheap. my concern is more about the confusion it could cause: the controller does not handle `COOKIE`, and the spec marks it as [deprecated and unsafe](https://spec.torproject.org/control-spec/implementation-notes.html?highlight=__#:~:text=using%20the%20%22COOKIE,version%20of%20Tor.), so it seems very unlikely to ever be supported~~ ~~offering it in the fuzzer could give the impression that there is some code handling it, and someone might go out looking for it~~ ~~if you would rather keep it as a regression guard, could we add a short comment explaining that it is intentionally offered to check that it stays ignored ?~~ ```suggestion // the COOKIE auth method is deprecated and the controller ignores it. Kept to check it stays ignored. static constexpr std::array<std::string_view, 4> METHODS{"NULL", "COOKIE", "SAFECOOKIE", "HASHEDPASSWORD"}; ```
erickcestari (Migrated from github.com) reviewed 2026-11-25 19:10:31 +00:00
erickcestari (Migrated from github.com) commented 2026-11-25 19:10:31 +00:00

I agree with you. Since it's already merged I've add it in this PR as you suggested.

I agree with you. Since it's already merged I've add it in this PR as you suggested.
winterrdog (Migrated from github.com) reviewed 2026-12-02 14:34:52 +00:00
winterrdog (Migrated from github.com) commented 2026-12-02 14:34:52 +00:00

i am still hitting the -torpassword assertion on cbd8dd443b with a password containing a backslash:

fuzz: test/fuzz/torcontrol.cpp:246: void (anonymous namespace)::FakeTor::ProcessCommands(): Assertion `DecodeAuthArg(arg) == password' failed.

the check makes sure Tor gets the password exactly as configured. With pa\ss, the controller sends an unescaped password, "pa\ss", and Tor drops the backslash and ends up with pass. so, authentication fails even though the user typed the right password


to reproduce, pin the password to pa\ss and answer PROTOCOLINFO with a HASHEDPASSWORD offer:

diff
diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp
index f02a30ed3a..43647b0edf 100644
--- a/src/test/fuzz/torcontrol.cpp
+++ b/src/test/fuzz/torcontrol.cpp
@@ -423,6 +423,8 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol)
         const auto size{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 32)};
         torpassword = fuzzed_data_provider.ConsumeBytesAsString(size);
     }
+    // [REPRO]: force a password containing a backslash.
+    torpassword = "pa\\ss"; // 5 bytes: p a \ s s
     gArgs.ForceSetArg("-torpassword", torpassword);

     FakeTor tor;
@@ -457,6 +459,16 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol)
     }};
     connect();

+    // [REPRO]: Tor answers PROTOCOLINFO and offers HASHEDPASSWORD, so the controller sends the password.
+    tor.ProcessCommands(); // picks up the PROTOCOLINFO command sent by connected_cb()
+    tor.pending += "250-PROTOCOLINFO 1\r\n"
+                   "250-AUTH METHODS=HASHEDPASSWORD\r\n"
+                   "250-VERSION Tor=\"0.4.8.10\"\r\n"
+                   "250 OK\r\n";
+    tor.Write(tor.pending.size());
+    receive();
+    tor.ProcessCommands(); // the AUTHENTICATE assertion fires here on a quote-only sender
+
     LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 1000) {
         CallOneOf(
             fuzzed_data_provider,

protocolinfo_cb() on this commit still only escapes quotes, so the backslash case is not covered. is #36637 in this branch? if your fix is local, could you push it ?

i am still hitting the `-torpassword` assertion on cbd8dd443b547c92dac8fe8a535a64dc7561bc40 with a password containing a backslash: ```text fuzz: test/fuzz/torcontrol.cpp:246: void (anonymous namespace)::FakeTor::ProcessCommands(): Assertion `DecodeAuthArg(arg) == password' failed. ``` the check makes sure Tor gets the password exactly as configured. With `pa\ss`, the controller sends an unescaped password, `"pa\ss"`, and Tor drops the backslash and ends up with `pass`. so, authentication fails even though the user typed the right password --- to reproduce, pin the password to `pa\ss` and answer `PROTOCOLINFO` with a `HASHEDPASSWORD` offer: <details><summary>diff</summary> ```diff diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp index f02a30ed3a..43647b0edf 100644 --- a/src/test/fuzz/torcontrol.cpp +++ b/src/test/fuzz/torcontrol.cpp @@ -423,6 +423,8 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol) const auto size{fuzzed_data_provider.ConsumeIntegralInRange<size_t>(0, 32)}; torpassword = fuzzed_data_provider.ConsumeBytesAsString(size); } + // [REPRO]: force a password containing a backslash. + torpassword = "pa\\ss"; // 5 bytes: p a \ s s gArgs.ForceSetArg("-torpassword", torpassword); FakeTor tor; @@ -457,6 +459,16 @@ FUZZ_TARGET(torcontrol, .init = initialize_torcontrol) }}; connect(); + // [REPRO]: Tor answers PROTOCOLINFO and offers HASHEDPASSWORD, so the controller sends the password. + tor.ProcessCommands(); // picks up the PROTOCOLINFO command sent by connected_cb() + tor.pending += "250-PROTOCOLINFO 1\r\n" + "250-AUTH METHODS=HASHEDPASSWORD\r\n" + "250-VERSION Tor=\"0.4.8.10\"\r\n" + "250 OK\r\n"; + tor.Write(tor.pending.size()); + receive(); + tor.ProcessCommands(); // the AUTHENTICATE assertion fires here on a quote-only sender + LIMITED_WHILE(fuzzed_data_provider.ConsumeBool(), 1000) { CallOneOf( fuzzed_data_provider, ``` </details> `protocolinfo_cb()` on this commit still [only escapes quotes](https://github.com/erickcestari/bitcoin/blob/cbd8dd443b547c92dac8fe8a535a64dc7561bc40/src/torcontrol.cpp#L695), so the backslash case is not covered. is #36637 in this branch? if your fix is local, could you push it ?
erickcestari (Migrated from github.com) reviewed 2026-12-02 17:44:14 +00:00
erickcestari (Migrated from github.com) commented 2026-12-02 17:44:14 +00:00

Indeed I forgot to rebase against master. Now it should be fine. Thanks for letting me know!

Indeed I forgot to rebase against master. Now it should be fine. Thanks for letting me know!
frankomosh (Migrated from github.com) reviewed 2026-12-02 18:36:30 +00:00
frankomosh (Migrated from github.com) commented 2026-12-02 18:36:30 +00:00

i am still hitting the -torpassword assertion on [cbd8dd4]

A rebase would work I think

> i am still hitting the `-torpassword` assertion on [cbd8dd4] A rebase would work I think
winterrdog (Migrated from github.com) reviewed 2026-12-03 18:48:21 +00:00
winterrdog (Migrated from github.com) left a comment

ACK fdc08cbc96. code reviewed and tested

successfully built and tested with clang++-20 on Debian, targeting x86_64. also, i ran the target for 29 minutes on a fresh corpus, with no assertion failures


i left one suggestion.

ACK fdc08cbc96af4aae8e5b0f943ca2066e416b432f. code reviewed and tested successfully built and tested with `clang++-20` on Debian, targeting `x86_64`. also, i ran the target for 29 minutes on a fresh corpus, with no assertion failures --- i left one suggestion.
winterrdog (Migrated from github.com) commented 2026-12-03 18:44:49 +00:00

+1 on Ralph's second suggestion: #36822

The fuzz target's framing assertions can accept an injected command beginning with an allowed verb because they run after \r\n splitting; no current production injection is established.

the command check only looks at how a command starts, so something like AUTHENTICATE-x passes as valid and then slips past every check below it

matching the verb exactly (just like in ConsumeAnswer()), and pinning down the full shape of each command, means reply data cannot alter a command's body behind a valid first word. also, any new verb without a check now fails loudly

patch
diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp
index 2299ace8cb..41a71462b8 100644
--- a/src/test/fuzz/torcontrol.cpp
+++ b/src/test/fuzz/torcontrol.cpp
@@ -231,26 +231,36 @@ struct FakeTor {
             const std::string_view cmd{std::string_view{sent}.substr(0, end)};
             // 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(' ')));
+            // do an exact match so that wrong commands like AUTHENTICATE-x do not make it through
+            const std::string_view verb{cmd.substr(0, cmd.find(' '))};
+            assert(std::ranges::find(VERBS, verb) != VERBS.end());
+            unanswered.emplace_back(verb);
             // Each authentication method may only be used once Tor offered it on this connection.
-            if (cmd == "AUTHENTICATE") {
-                assert(Offered("NULL"));
-            } else if (cmd.starts_with("AUTHENTICATE ")) {
-                const std::string_view arg{cmd.substr(std::string_view{"AUTHENTICATE "}.size())};
-                if (password.empty()) {
-                    // SAFECOOKIE: send the proof only after Tor proved it knows the cookie.
-                    assert(ProvedCookie(arg));
-                } else {
-                    assert(Offered("HASHEDPASSWORD"));
-                    assert(DecodeAuthArg(arg) == password);
-                }
-            } else if (cmd.starts_with("AUTHCHALLENGE SAFECOOKIE ")) {
+            if (verb == "PROTOCOLINFO") {
+                assert(cmd == "PROTOCOLINFO 1");
+            } else if (verb == "GETINFO") {
+                assert(cmd == "GETINFO net/listeners/socks");
+            } else if (verb == "AUTHCHALLENGE") {
+                assert(cmd.starts_with("AUTHCHALLENGE SAFECOOKIE "));
                 assert(Offered("SAFECOOKIE"));
                 client_nonce = ParseHex(cmd.substr(std::string_view{"AUTHCHALLENGE SAFECOOKIE "}.size()));
                 // A repeated nonce would let a recorded server hash prove the cookie again.
                 assert(client_nonce.size() == 32 && client_nonces.insert(client_nonce).second);
-            } else if (cmd.starts_with("ADD_ONION ")) {
+            } else if (verb == "AUTHENTICATE") {
+                if (cmd == "AUTHENTICATE") {
+                    assert(Offered("NULL"));
+                } else {
+                    const std::string_view arg{cmd.substr(std::string_view{"AUTHENTICATE "}.size())};
+                    if (password.empty()) {
+                        // SAFECOOKIE: send the proof only after Tor proved it knows the cookie.
+                        assert(ProvedCookie(arg));
+                    } else {
+                        assert(Offered("HASHEDPASSWORD"));
+                        assert(DecodeAuthArg(arg) == password);
+                    }
+                }
+            } else {
+                assert(verb == "ADD_ONION");
                 // One port mapping, always from the default virtual port, so the service doesn't
                 // reveal a node using another port.
                 std::vector<std::string> ports;
+1 on Ralph's second suggestion: https://git.fish.foo/bitcoin/bitcoin/pulls/36822#author-ralph > The fuzz target's framing assertions can accept an injected command beginning with an allowed verb because they run after `\r\n` splitting; no current production injection is established. the command check only looks at how a command starts, so something like `AUTHENTICATE-x` passes as valid and then slips past every check below it matching the verb exactly (just like in `ConsumeAnswer()`), and pinning down the full shape of each command, means reply data cannot alter a command's body behind a valid first word. also, any new verb without a check now fails loudly <details> <summary>patch </summary> ```diff diff --git a/src/test/fuzz/torcontrol.cpp b/src/test/fuzz/torcontrol.cpp index 2299ace8cb..41a71462b8 100644 --- a/src/test/fuzz/torcontrol.cpp +++ b/src/test/fuzz/torcontrol.cpp @@ -231,26 +231,36 @@ struct FakeTor { const std::string_view cmd{std::string_view{sent}.substr(0, end)}; // 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(' '))); + // do an exact match so that wrong commands like AUTHENTICATE-x do not make it through + const std::string_view verb{cmd.substr(0, cmd.find(' '))}; + assert(std::ranges::find(VERBS, verb) != VERBS.end()); + unanswered.emplace_back(verb); // Each authentication method may only be used once Tor offered it on this connection. - if (cmd == "AUTHENTICATE") { - assert(Offered("NULL")); - } else if (cmd.starts_with("AUTHENTICATE ")) { - const std::string_view arg{cmd.substr(std::string_view{"AUTHENTICATE "}.size())}; - if (password.empty()) { - // SAFECOOKIE: send the proof only after Tor proved it knows the cookie. - assert(ProvedCookie(arg)); - } else { - assert(Offered("HASHEDPASSWORD")); - assert(DecodeAuthArg(arg) == password); - } - } else if (cmd.starts_with("AUTHCHALLENGE SAFECOOKIE ")) { + if (verb == "PROTOCOLINFO") { + assert(cmd == "PROTOCOLINFO 1"); + } else if (verb == "GETINFO") { + assert(cmd == "GETINFO net/listeners/socks"); + } else if (verb == "AUTHCHALLENGE") { + assert(cmd.starts_with("AUTHCHALLENGE SAFECOOKIE ")); assert(Offered("SAFECOOKIE")); client_nonce = ParseHex(cmd.substr(std::string_view{"AUTHCHALLENGE SAFECOOKIE "}.size())); // A repeated nonce would let a recorded server hash prove the cookie again. assert(client_nonce.size() == 32 && client_nonces.insert(client_nonce).second); - } else if (cmd.starts_with("ADD_ONION ")) { + } else if (verb == "AUTHENTICATE") { + if (cmd == "AUTHENTICATE") { + assert(Offered("NULL")); + } else { + const std::string_view arg{cmd.substr(std::string_view{"AUTHENTICATE "}.size())}; + if (password.empty()) { + // SAFECOOKIE: send the proof only after Tor proved it knows the cookie. + assert(ProvedCookie(arg)); + } else { + assert(Offered("HASHEDPASSWORD")); + assert(DecodeAuthArg(arg) == password); + } + } + } else { + assert(verb == "ADD_ONION"); // One port mapping, always from the default virtual port, so the service doesn't // reveal a node using another port. std::vector<std::string> ports; ``` </details>
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!36822
No description provided.