net: validate Tor onion service replies and cached keys #36142

Manually merged
l0rinc merged 5 commits from l0rinc/tor-control-command-framing into master 2026-11-05 10:45:18 +00:00 AGit
l0rinc commented 2026-09-01 20:09:10 +00:00 (Migrated from github.com)

Problem: A node creates its onion service through Tor's control protocol and caches the returned PrivateKey value for reconnects.
Tor reply parsing unescapes quoted values, so a control endpoint can return a value containing a line break or space.
On reconnect, the node inserts that value unquoted into an ADD_ONION command.
CRLF frames the remainder as a separate command, while a space adds further arguments.
An unprivileged local process can exploit this by impersonating the default loopback endpoint while Tor is unavailable, seeding the cache, and releasing the port before Tor is available again.
A compromised operator-configured endpoint can return the same malicious value.
The reply handler also continues after receiving an invalid service ID, logging it and caching the key before attempting to advertise the invalid address.
A later reply without a service ID can reuse an ID left by an earlier reply.

Fix: This PR validates the returned service ID as a Tor v3 onion address before logging it, caching the key, or advertising the service.
Each reply must provide its own service ID, and reply fields stay local until validation succeeds.
Key validation accepts NEW:ED25519-V3 or an ED25519-V3 key whose Base64 payload decodes to 64 bytes.
Returned keys are validated before adoption or caching, and cached keys are validated before reuse.
A malformed cached key leaves the onion service unavailable until the operator removes the file and restarts the node. It cannot inject another command or argument.

**Problem:** A node creates its onion service through Tor's control protocol and caches the returned `PrivateKey` value for reconnects. Tor reply parsing unescapes quoted values, so a control endpoint can return a value containing a line break or space. On reconnect, the node inserts that value unquoted into an `ADD_ONION` command. CRLF frames the remainder as a separate command, while a space adds further arguments. An unprivileged local process can exploit this by impersonating the default loopback endpoint while Tor is unavailable, seeding the cache, and releasing the port before Tor is available again. A compromised operator-configured endpoint can return the same malicious value. The reply handler also continues after receiving an invalid service ID, logging it and caching the key before attempting to advertise the invalid address. A later reply without a service ID can reuse an ID left by an earlier reply. **Fix:** This PR validates the returned service ID as a Tor v3 onion address before logging it, caching the key, or advertising the service. Each reply must provide its own service ID, and reply fields stay local until validation succeeds. Key validation accepts `NEW:ED25519-V3` or an `ED25519-V3` key whose Base64 payload decodes to 64 bytes. Returned keys are validated before adoption or caching, and cached keys are validated before reuse. A malformed cached key leaves the onion service unavailable until the operator removes the file and restarts the node. It cannot inject another command or argument.
DrahtBot commented 2026-09-01 20:09:18 +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 vasild, winterrdog, jpk68, sedited
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

Reviewers, this pull request conflicts with the following ones:

  • #36637 (torcontrol: send -torpassword hex-encoded to avoid escaping bugs by jpk68)
  • #36497 (test: Add coverage for TorControl SAFECOOKIE authentication by winterrdog)
  • #36374 (torcontrol: escape backslashes in -torpassword by 0xShadowX)
  • #35292 (test: Add coverage for Tor control HASHEDPASSWORD authentication by winterrdog)

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

<!--e57a25ab6845829454e8d69fc972939a--> The following sections might be updated with supplementary metadata relevant to reviewers and maintainers. <!--006a51241073e994b41acfe9ec718e94--> ### External sites * Code coverage & benchmarks: https://corecheck.dev/bitcoin/bitcoin/pulls/36142 * Ralph review <img src=https://review.fish.foo/assets/bitcoin/bitcoin/36142.png alt="Ralph review status"> https://git.fish.foo/bitcoin/bitcoin/pulls/36142#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 | [vasild](https://github.com/bitcoin/bitcoin/pull/36142#pullrequestreview-5337118238), [winterrdog](https://github.com/bitcoin/bitcoin/pull/36142#pullrequestreview-5337766659), [jpk68](https://github.com/bitcoin/bitcoin/pull/36142#issuecomment-6321068247), [sedited](https://github.com/bitcoin/bitcoin/pull/36142#pullrequestreview-5783490936) | | Concept ACK | [jeanpablojp](https://github.com/bitcoin/bitcoin/pull/36142#pullrequestreview-5097038039) | 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: * [#36637](https://github.com/bitcoin/bitcoin/pull/36637) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36637.svg"></sub> (torcontrol: send -torpassword hex-encoded to avoid escaping bugs by jpk68) * [#36497](https://github.com/bitcoin/bitcoin/pull/36497) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36497.svg"></sub> (test: Add coverage for TorControl `SAFECOOKIE` authentication by winterrdog) * [#36374](https://github.com/bitcoin/bitcoin/pull/36374) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/36374.svg"></sub> (torcontrol: escape backslashes in -torpassword by 0xShadowX) * [#35292](https://github.com/bitcoin/bitcoin/pull/35292) <sub><img src="https://drahtbot.space/ack_count/bitcoin/bitcoin/35292.svg"></sub> (test: Add coverage for Tor control `HASHEDPASSWORD` authentication by winterrdog) 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-->
winterrdog (Migrated from github.com) reviewed 2026-09-02 09:35:58 +00:00
winterrdog (Migrated from github.com) left a comment

concept ACK

concept ACK
jeanpablojp (Migrated from github.com) reviewed 2026-09-03 02:06:26 +00:00
jeanpablojp (Migrated from github.com) left a comment

Concept ACK

The CRLF side looks well covered. The space still gets through. The key goes into ADD_ONION unquoted, and in the control protocol a space is what separates arguments. A returned key carrying one still passes the check, gets cached, and goes back out on the next startup, this time to the real Tor.

If the injected token is a Port= on the same virtual port the node publishes, Tor ends up with two targets for it and connections go to either one. Pointed at a real Tor instead of the mock, fifteen of thirty connections to the node's onion address landed on the injected target, with no warning about it in the log. Swap the Port= for Flags=Detach and the service stays up after bitcoind exits.

Concept ACK The CRLF side looks well covered. The space still gets through. The key goes into `ADD_ONION` unquoted, and in the control protocol a space is what separates arguments. A returned key carrying one still passes the check, gets cached, and goes back out on the next startup, this time to the real Tor. If the injected token is a `Port=` on the same virtual port the node publishes, Tor ends up with two targets for it and connections go to either one. Pointed at a real Tor instead of the mock, fifteen of thirty connections to the node's onion address landed on the injected target, with no warning about it in the log. Swap the `Port=` for ` Flags=Detach` and the service stays up after bitcoind exits.
jeanpablojp (Migrated from github.com) commented 2026-09-03 02:06:26 +00:00

This guard covers a cache that already has CR or LF, but it can't be extended to the space, since control commands legitimately contain spaces. Would it make sense to check the cached key in auth_cb, before the ADD_ONION is built? The warning could name the file there. That is what the operator has to delete, and it doesn't appear in the default log today.

This guard covers a cache that already has CR or LF, but it can't be extended to the space, since control commands legitimately contain spaces. Would it make sense to check the cached key in `auth_cb`, before the `ADD_ONION` is built? The warning could name the file there. That is what the operator has to delete, and it doesn't appear in the default log today.
Lines 550-554
jeanpablojp (Migrated from github.com) commented 2026-09-03 02:06:26 +00:00

Would it make sense to reject the space here alongside CR and LF? It is the only other byte that works as a separator there, and none of the twenty keys I asked Tor for had any of the three.

            // A line break frames a second command and a space smuggles further
            // ADD_ONION arguments, so never adopt or cache such a key.
            if (private_key->find_first_of(" \r\n") != std::string::npos) {
                LogWarning("tor: ADD_ONION returned a private key containing a line break or a space");
                return;
            }

I applied this locally and the torcontrol unit and functional tests still pass, with no assertion changed.

Would it make sense to reject the space here alongside CR and LF? It is the only other byte that works as a separator there, and none of the twenty keys I asked Tor for had any of the three. ```suggestion // A line break frames a second command and a space smuggles further // ADD_ONION arguments, so never adopt or cache such a key. if (private_key->find_first_of(" \r\n") != std::string::npos) { LogWarning("tor: ADD_ONION returned a private key containing a line break or a space"); return; } ``` I applied this locally and the torcontrol unit and functional tests still pass, with no assertion changed.
vasild commented 2026-09-03 13:06:37 +00:00 (Migrated from github.com)

Concept ACK

Instead of chasing bad characters from the Tor router reponses, it would be more robust to only allow legit characters and frown upon anything else. For example, for the ADD_ONION command:

https://spec.torproject.org/control-spec/commands.html#add_onion

The server reply format is:

    "250-ServiceID=" ServiceID CRLF
    ["250-PrivateKey=" KeyType ":" KeyBlob CRLF]
    *("250-ClientAuth=" ClientName ":" ClientBlob CRLF)
    "250 OK" CRLF

The KeyBlob format is left intentionally opaque, however ... For a “ED25519-V3” key is the Base64 encoding of ...

That is - better to treat anything that is not a valid base64 character as a malformed reply for KeyBlob.

Concept ACK Instead of chasing bad characters from the Tor router reponses, it would be more robust to only allow legit characters and frown upon anything else. For example, for the `ADD_ONION` command: https://spec.torproject.org/control-spec/commands.html#add_onion > The server reply format is: ``` "250-ServiceID=" ServiceID CRLF ["250-PrivateKey=" KeyType ":" KeyBlob CRLF] *("250-ClientAuth=" ClientName ":" ClientBlob CRLF) "250 OK" CRLF ``` > The KeyBlob format is left intentionally opaque, however ... For a “ED25519-V3” key is the Base64 encoding of ... That is - better to treat anything that is not a valid base64 character as a malformed reply for `KeyBlob`.
vasild commented 2026-09-04 16:49:01 +00:00 (Migrated from github.com)

In general, we can be more strict when receiving replies from the Tor daemon, not just the private key blob. For example, the ServiceID received as a reply to our ADD_ONION command is passed to LookupNumeric() and LogInfo() (see TorController::add_onion_cb()) without much checking. But it must be exactly 56 base32 characters. If it is not, then it is safer to assume malformed reply from Tor, stop the processing right there, and not pass the malformed stuff to other functions.

In general, we can be more strict when receiving replies from the Tor daemon, not just the private key blob. For example, the ServiceID received as a reply to our `ADD_ONION` command is passed to `LookupNumeric()` and `LogInfo()` (see `TorController::add_onion_cb()`) without much checking. But it must be exactly 56 base32 characters. If it is not, then it is safer to assume malformed reply from Tor, stop the processing right there, and not pass the malformed stuff to other functions.
l0rinc commented 2026-09-04 20:09:14 +00:00 (Migrated from github.com)

Rebased and pushed, addressed all comments, thank you!
Private-key format is now checked when received and before cached reuse, blocking both CRLF and space injection. Service IDs are validated before caching the key or advertising the service, and malformed-cache warnings name the file to remove.

Thanks @jeanpablojp for identifying the space-injection gap and suggesting cached-key checks, and @vasild for suggesting strict key-format and service-ID validation.

Rebased and pushed, addressed all comments, thank you! Private-key format is now checked when received and before cached reuse, blocking both CRLF and space injection. Service IDs are validated before caching the key or advertising the service, and malformed-cache warnings name the file to remove. Thanks @jeanpablojp for identifying the space-injection gap and suggesting cached-key checks, and @vasild for suggesting strict key-format and service-ID validation.
winterrdog (Migrated from github.com) reviewed 2026-09-04 22:12:37 +00:00
winterrdog (Migrated from github.com) commented 2026-09-04 22:04:59 +00:00

just a suggestion we can consider separately: should we explicitly enforce owner-only permissions when writing the cached onion private key ?

this feels kind of similar to how we handle other sensitive files, e.g. GenerateAuthCookie() explicitly (if provided) sets restrictive permissions on the RPC cookie (fs::perms, -rpccookieperms):
github.com/bitcoin/bitcoin@4519933391/src/rpc/request.cpp (L100-L146)

since this file contains the private key controlling the .onion identity, it seems worth doing the same here. just wanted to flag it while we are touching an area adjacent to private key handling

any thoughts? or the current approach is just fine ?

just a suggestion we can consider separately: should we explicitly enforce _owner-only_ permissions when writing the cached onion private key ? this feels kind of similar to how we handle other sensitive files, e.g. `GenerateAuthCookie()` explicitly (if provided) sets restrictive permissions on the RPC cookie (`fs::perms`, `-rpccookieperms`): https://github.com/bitcoin/bitcoin/blob/4519933391dd23dbf1a4eceec6dd53d2e9e71cc3/src/rpc/request.cpp#L100-L146 since this file contains the private key controlling the `.onion` identity, it seems worth doing the same here. just wanted to flag it while we are touching an area adjacent to private key handling any thoughts? or the current approach is just fine ?
vasild (Migrated from github.com) reviewed 2026-09-08 12:57:18 +00:00
vasild (Migrated from github.com) commented 2026-09-08 12:57:18 +00:00

Yes, makes sense. But the correct way is to set the filesystem permissions first and after that write the sensitive data to it, or create it right away with the desired permissions using umask. The above snippet first writes the data and then sets the permissions :( while : ; do cat /path/to/sensitive_file ; done is a trivial way to exploit the first-write-then-set-permissions approach.

There is SetupEnvironment() which calls umask(0077) which should make the above safe, but still it would be better to call fs::permissions() first and then file << COOKIEAUTH_USER << ":" << rand_pwd_hex; in the above snippet. I am not sure why fs::permissions() is needed if this relies on the global umask.

Yes, makes sense. But the correct way is to set the filesystem permissions first and after that write the sensitive data to it, or create it right away with the desired permissions using umask. The above snippet first writes the data and then sets the permissions :( `while : ; do cat /path/to/sensitive_file ; done` is a trivial way to exploit the first-write-then-set-permissions approach. There is `SetupEnvironment()` which calls `umask(0077)` which should make the above safe, but still it would be better to call `fs::permissions()` first and then `file << COOKIEAUTH_USER << ":" << rand_pwd_hex;` in the above snippet. I am not sure why `fs::permissions()` is needed if this relies on the global umask.
winterrdog (Migrated from github.com) reviewed 2026-09-08 14:02:39 +00:00
winterrdog (Migrated from github.com) commented 2026-09-08 14:02:39 +00:00

There is SetupEnvironment() which calls umask(0077) which should make the above safe

ah, yes! case closed.

I am not sure why fs::permissions() is needed if this relies on the global umask.

yes, not necessary

but still it would be better to call fs::permissions() first and then file << COOKIEAUTH_USER << ":" << rand_pwd_hex; in the above snippet.

correct! i will find out why that is so

> There is `SetupEnvironment()` which calls `umask(0077)` which should make the above safe ah, yes! case closed. > I am not sure why `fs::permissions()` is needed if this relies on the global umask. yes, not necessary > but still it would be better to call `fs::permissions()` first and then `file << COOKIEAUTH_USER << ":" << rand_pwd_hex;` in the above snippet. correct! i will find out why that is so
DrahtBot commented 2026-09-16 11:23:44 +00:00 (Migrated from github.com)

🐙 This pull request conflicts with the target branch and needs rebase.

<!--cf906140f33d8803c4a75a2196329ecb--> 🐙 This pull request conflicts with the target branch and [needs rebase](https://github.com/bitcoin/bitcoin/blob/master/CONTRIBUTING.md#rebasing-changes).
l0rinc commented 2026-09-25 03:46:56 +00:00 (Migrated from github.com)

Rebased, added coverage for service IDs with invalid checksums and returned private keys with unsupported types, invalid Base64, or the wrong length.

Rebased, added coverage for service IDs with invalid checksums and returned private keys with unsupported types, invalid Base64, or the wrong length.
vasild (Migrated from github.com) approved these changes 2026-09-25 16:18:26 +00:00
vasild (Migrated from github.com) left a comment

ACK 6b3e23fe68

Some minor things below, feel free to ignore.

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 6b3e23fe6883569e07f4d8c9413b1dedcc510778

Some minor things below, feel free to ignore.
-----BEGIN PGP SIGNATURE-----

iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmq2nqQbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/EYQf/A+7jw6WENj50dvG476P
PXYyb95b1oW6w5Ht7JIauA9HwFiBiiKn1k8m5PA+pt7c/IzY6BxWc1WZBaYnuEOz
jSoNKM1byO21NupAT0sA6uMsawgxhF/XJfgCQeLo7PQjSyDsm2a3WU1Gnjo5cSPU
MlVi/ps8+2PGy+pxT/nbUS+fATtxYre8vLwY5FvCTaeoNEdPRrPYrLqDI7n9vGmB
H1q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1JDPz+2aqF6+fO5Sfdy
1C+GPNNVl44/m2opycMurdMSSTvnApfMw2Rtmyued6flgWxiZFHjPZrxEUpwYFhv
NsY=
=GaWT
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

ACK 6b3e23fe6883569e07f4d8c9413b1dedcc510778 Some minor things below, feel free to ignore. <details> <summary>Show Signature</summary> ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ACK 6b3e23fe6883569e07f4d8c9413b1dedcc510778 Some minor things below, feel free to ignore. -----BEGIN PGP SIGNATURE----- iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmq2nqQbFIAAAAAABAAO bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/EYQf/A+7jw6WENj50dvG476P PXYyb95b1oW6w5Ht7JIauA9HwFiBiiKn1k8m5PA+pt7c/IzY6BxWc1WZBaYnuEOz jSoNKM1byO21NupAT0sA6uMsawgxhF/XJfgCQeLo7PQjSyDsm2a3WU1Gnjo5cSPU MlVi/ps8+2PGy+pxT/nbUS+fATtxYre8vLwY5FvCTaeoNEdPRrPYrLqDI7n9vGmB H1qi5n/n7czcuhUfLMK45CmTiAEQYDonHER1iThSHzHLT5kLdi+OCJKNaFuol+ka jTIjMe1wQTB/caTkIfhJ0PtHo587u4Z0RafeaKK8Yalls88y0QFIMQyt3Sxq29fU c1UOfM8kV2lU7k+NE0CWltZB6/HUlB6AWAIRAOVauPvq3arHeRkRhhx1I/zbJQp+ IhkSsF0WrYsEcicBG1adOajIG0zUYsDjSzaRYbmuZIriayEY9FE5Kw8WVVTE3JU3 +eZdOLio8vNNd/s15vVxcsl69MwOVFp4A9FhWxYtA8cSY7TAW44P2hCQgUbYNizN pQRwnvZXWTevDLJP2ujBrn0YS4Bq9Jj3k91j+8XArrP9FeMOKfgSzFp/VIXfeGYy XXWc7Wa57uC4EWR4aEq+LAQkojMpXNKky1BizBL5ak4xcpbw8jYTlMK7zvLvO/Cn OPN1f0WkDw3ztKRgsE1mSl8xc6EmRoLLq95fHfP0T0RaRghbEqL02JASpsafD2oY EsY4pRcMrTYcY4f7ojPPRTidduNt6y59+cQvBCupBr9fAQgTmWKCj0trsm/wOMBU /U+YnmDAGltGCmFABK7ZjKQ0O1+P8fyYmOTMP+cclPXDmiJzeGHdkoqRWb0yc6eA yDZ9BrGGBVo83gi53Vd2z8uJOogUrP4D030spL4ajM0GPg5bqVX/Jx5vt7qhEnQH MHQzboFJWeNHWLo6kX/pWtbS2juuHLEjN/qKFkcSaSSnmA7Zh7C6+xezN4wySNhb F+nsy1DYaNR/PEvx9Ajc3vTHrkm9ADxVJCXETMtw5t0KfQ7H3ECW/sKP7b244KXt pKo/BneW4MQfnrZ67OF2vdG44cgYacfg+NonJOVxIzH9APEkw5y799JdAjqlbAXo 4mqkR53LzTbY2ho6xRJgDd6MBfsk6YK/mHAhivHVc+rwWo8ThxYBLNQxbng05RR1 pnNCnqs3m1cbKFYXnUPA1Gtp4gEMbffIaDNWF+2nH97O3HkH5BpTtf47FEmdlYyz wf4btfb7ix/6ecMxX8sKnEseXg+xEi4hprcx7Sdepd7Ce1JDPz+2aqF6+fO5Sfdy 1C+GPNNVl44/m2opycMurdMSSTvnApfMw2Rtmyued6flgWxiZFHjPZrxEUpwYFhv NsY= =GaWT -----END PGP SIGNATURE----- ``` vasild's public key is [on openpgp.org](https://keys.openpgp.org/vks/v1/by-fingerprint/850E138BA9C0923881DFD55FCE712013582E2230) </details>
vasild (Migrated from github.com) commented 2026-09-25 15:45:56 +00:00

The name private_key gives the impression that it is... hmm... the private key, but actually it is <key type>:<private_key>.

The name `private_key` gives the impression that it is... hmm... the private key, but actually it is `<key type>:<private_key>`.
vasild (Migrated from github.com) commented 2026-09-25 15:55:15 +00:00

This text uses "invalid" and "malformed" interchangeably, but they are not quite the same:

  • malformed would be e.g. longer or shorter or that contains not-allowed character, e.g. aa:bb_c"d is malformed service id (contains invalid characters and is not 56 chars long)
  • invalid would be ag6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd - it is not malformed, but has a mismatching checksum.

Even if the above is somewhat subjective, better use just one term in the test, e.g. s/malformed/invalid/.

This text uses "invalid" and "malformed" interchangeably, but they are not quite the same: * malformed would be e.g. longer or shorter or that contains not-allowed character, e.g. `aa:bb_c"d` is malformed service id (contains invalid characters and is not 56 chars long) * invalid would be `ag6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd` - it is not malformed, but has a mismatching checksum. Even if the above is somewhat subjective, better use just one term in the test, e.g. `s/malformed/invalid/`.
vasild (Migrated from github.com) commented 2026-09-25 16:00:27 +00:00

Would be good here to ensure that the key did not exist or if it existed did not contain exactly the value of valid_private_key before this snippet runs. Otherwise the assert_equal() may pass due to a stale file being present upfront even if bitcoind does not write to the file.

Maybe easiest to add key_path.unlink(missing_ok=True) before MockTorControlServer().

Would be good here to ensure that the key did not exist or if it existed did not contain exactly the value of `valid_private_key` before this snippet runs. Otherwise the `assert_equal()` may pass due to a stale file being present upfront even if `bitcoind` does not write to the file. Maybe easiest to add `key_path.unlink(missing_ok=True)` before `MockTorControlServer()`.
l0rinc (Migrated from github.com) reviewed 2026-09-25 19:32:31 +00:00
l0rinc (Migrated from github.com) left a comment

Updated the invalid-vs-malformed wording, added extra assertion, simplified the injection cases and commit messages.

Updated the invalid-vs-malformed wording, added extra assertion, simplified the injection cases and commit messages.
l0rinc (Migrated from github.com) commented 2026-09-25 19:24:15 +00:00

I tried a few names here and ended up keeping private_key.
Tor calls the full KeyType:KeyBlob reply value PrivateKey, and we store it in m_private_key, so the mock follows the same convention.

I tried a few names here and ended up keeping `private_key`. Tor calls the full `KeyType:KeyBlob` reply value `PrivateKey`, and we store it in `m_private_key`, so the mock follows the same convention.
l0rinc (Migrated from github.com) commented 2026-09-25 19:25:56 +00:00

Adjusted it everywhere, test name, log message, and commit text to use the nomenclature consistently.

Adjusted it everywhere, test name, log message, and commit text to use the nomenclature consistently.
l0rinc (Migrated from github.com) commented 2026-09-25 19:31:24 +00:00

The unlink seems to be present in restart_with_mock() already - added assert not key_path.exists() immediately after it to make the precondition explicit.

The unlink seems to be present in `restart_with_mock()` already - added `assert not key_path.exists()` immediately after it to make the precondition explicit.
winterrdog (Migrated from github.com) reviewed 2026-09-25 23:00:23 +00:00
winterrdog (Migrated from github.com) left a comment

tACK a3537ed6a3

successfully built and tested on this toolchain: FreeBSD 15.0/clang++-19/x86_64.
the changes LGTM (look good to merge)

tACK a3537ed6a344b5fdd4c9d4860985f9dc1521feb1 successfully built and tested on this toolchain: FreeBSD `15.0`/`clang++-19`/`x86_64`. the changes LGTM (look good to merge)
vasild (Migrated from github.com) approved these changes 2026-09-26 08:44:54 +00:00
vasild (Migrated from github.com) left a comment

ACK a3537ed6a3

Not a blocker below. Just something worth mentioning.

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK a3537ed6a344b5fdd4c9d4860985f9dc1521feb1

Not a blocker below. Just something worth mentioning.
-----BEGIN PGP SIGNATURE-----

iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmq3hfgbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/vuMf/3fDG66xgQIyGWz4PVXJ
2tK6TOEJstD3ngUL7/yV/zz5wyaKwJYarA4AeYL1wCnySTq2p8BP5tZnncS+PkBs
jcXtnWzMnasx0sGKZ1ib5wEmXVCn+KqOrq3Vw5MgjCelK6DOzk/LZqceyX+DI5/r
mqElvXOcUDhvKS4lxSds0L+F3ZPLhx7LzFeErH5z/1Cu+ymTiB1S5Nn7WRyVQsDM
aTMAvnHKFXuLgJ3lsnnRE5BKOOnrO5RlyM4nLftqWyu0aIeshpr1LXawxZ+k/Aau
JngQC3GS5HgFR7GyIBh9MaFulJxVacCorU5Cswl67rTIc42lPeHEWTLddzpHtZi6
+sxFnZO0MZ1jSBVrAvIqAJyezTE6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c9d4860985f9dc1521feb1 Not a blocker below. Just something worth mentioning. <details> <summary>Show Signature</summary> ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ACK a3537ed6a344b5fdd4c9d4860985f9dc1521feb1 Not a blocker below. Just something worth mentioning. -----BEGIN PGP SIGNATURE----- iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmq3hfgbFIAAAAAABAAO bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/vuMf/3fDG66xgQIyGWz4PVXJ 2tK6TOEJstD3ngUL7/yV/zz5wyaKwJYarA4AeYL1wCnySTq2p8BP5tZnncS+PkBs jcXtnWzMnasx0sGKZ1ib5wEmXVCn+KqOrq3Vw5MgjCelK6DOzk/LZqceyX+DI5/r mqElvXOcUDhvKS4lxSds0L+F3ZPLhx7LzFeErH5z/1Cu+ymTiB1S5Nn7WRyVQsDM aTMAvnHKFXuLgJ3lsnnRE5BKOOnrO5RlyM4nLftqWyu0aIeshpr1LXawxZ+k/Aau JngQC3GS5HgFR7GyIBh9MaFulJxVacCorU5Cswl67rTIc42lPeHEWTLddzpHtZi6 +sxFnZO0MZ1jSBVrAvIqAJyezTE6hrxDTbxPI6xPjii8xalNJkq/VzByJw2UzuNy x+6vgPotN5+7IQni6/vDMNV+1kkkhHkT/eqXKKhtFdRjjuJ+xqU3x03/wsLTffTO DOdZ/LRwAg3z8wDuPzXIVyXzy/bw5gbknABtAqiSDF7UKhxfkSU3v4B9iD3u2rgJ mGYQ7q9Mec0lXNzguhJp+Y81szXZvdM/IzywcCwIR2BQ7rgjskB2DdJQD4j+1f45 dEtihVyf8fnjhVOJcSHU3mr/na2XJOR6JtDSSV8tx9j0I+rLb3YHRKEywbzkZT/4 kqXw6mF2d4zvdnlHXs5xvCRTWx16rfR7cb+TtFqRgQio4AfPAd00wt+li7BvMbLB vh5brnPUVKOXjZSPuvOQpzx0cvPikcm9ZhmGImVpCEetAXPfRwTTVwiylQ3v7J9N 9U3MHGsRIfTJdFf/gRlZwfxWXMH8101g4Y74plm80vgcdUPHhS/mKDCVczd/5O2M kp/4Uu7x6GGED3r6yBS6dsoy08bAU96iJ6X6QknrU50ugXqMpF0T+C3WM4B9enzG nb8tAXxa7F0mWmCn33jemQy3/M0LCfwskf2pmcF24hM/YEd7nuaTf2YRtCZId3Xx T9a9B0VMfrGNib3L9YBrycTN1amvE7GC7W2b/4/VOcoIpy1eeTX6ZU8O1/L86ml0 tMk6sSw7SouW2FQE8FmaKG0zIEKIfBu794F9Nn6yF+qLC35UUThHKiwbxw0gzir1 kYRmBvQYwUVU4KKwLvgPKqtQtGocEWo/Y2Fy8a4XjYN3DmBLmT7Ijp13KHV+BkVH jRf/HZziEIqWwojYzSngfP7H6jPa5qPZDhtVkt2/r1mvQP4yfx4dPjH+N3pbfsmU lRAf+7BIoS7cumd2yEhlcSHroc8AgzHlNeDfvAWpJ87d4nHOF/GndSja7zbwUPQm pRK6mXCI9bHBVopBwAVG0MUq7G5FWvqxrqjhhQKwCXz4H1vWVaVGg/cUhJBBPpJt P8A= =FzqX -----END PGP SIGNATURE----- ``` vasild's public key is [on openpgp.org](https://keys.openpgp.org/vks/v1/by-fingerprint/850E138BA9C0923881DFD55FCE712013582E2230) </details>
Lines 533-553
vasild (Migrated from github.com) commented 2026-09-26 08:41:28 +00:00

The following occurred to me in the middle of the night 🛌😴 🌃:

The method TorController::add_onion_cb() reads the reply from the Tor server and if the reply is fine, then it saves it to disk and calls AddLocal().

If the reply is invalid, then it should be discarded and shouldn't go outside of this method. However this method modifies two member variables m_service_id and m_service before fully validating everything. Their values will remain after the method returns due to the error. This could have unexpected outcomes depending on where these variables are read elsewhere, outside of TorController::add_onion_cb().

  • m_service_id - why is this even a member variable? It is used only inside TorController::add_onion_cb(). I think it should be turned into a local variable inside the method. At the start of the method we do not want to have a leftover value from a previous call to the method, I guess.
  • m_service - it is assigned from LookupNumeric() and then checked whether is valid. If not, it will remain with its invalid value. Better do:
-        m_service = LookupNumeric(std::string(m_service_id+".onion"), Params().GetDefaultPort());
-        if (!m_service.IsValid()) {
+        const auto service{LookupNumeric(std::string(m_service_id+".onion"), Params().GetDefaultPort())};
+        if (!service.IsValid()) {
             LogWarning("tor: ADD_ONION returned an invalid service ID");
             return;
         }
+        m_service = service;
         LogInfo("Got tor service ID %s, advertising service %s", m_service_id, m_service.ToStringAddrPort());
The following occurred to me in the middle of the night 🛌😴 🌃: The method `TorController::add_onion_cb()` reads the reply from the Tor server and if the reply is fine, then it saves it to disk and calls `AddLocal()`. If the reply is invalid, then it should be discarded and shouldn't go outside of this method. However this method modifies two member variables `m_service_id` and `m_service` before fully validating everything. Their values will remain after the method returns due to the error. This could have unexpected outcomes depending on where these variables are read elsewhere, outside of `TorController::add_onion_cb()`. * `m_service_id` - why is this even a member variable? It is used only inside `TorController::add_onion_cb()`. I think it should be turned into a local variable inside the method. At the start of the method we do not want to have a leftover value from a previous call to the method, I guess. * `m_service` - it is assigned from `LookupNumeric()` and then checked whether is valid. If not, it will remain with its invalid value. Better do: ```diff - m_service = LookupNumeric(std::string(m_service_id+".onion"), Params().GetDefaultPort()); - if (!m_service.IsValid()) { + const auto service{LookupNumeric(std::string(m_service_id+".onion"), Params().GetDefaultPort())}; + if (!service.IsValid()) { LogWarning("tor: ADD_ONION returned an invalid service ID"); return; } + m_service = service; LogInfo("Got tor service ID %s, advertising service %s", m_service_id, m_service.ToStringAddrPort()); ```
l0rinc commented 2026-09-28 03:19:42 +00:00 (Migrated from github.com)

Pushed, the onion response is now validated before adoption, and reconnect tests cover missing and invalid service IDs—thanks @vasild!

Pushed, the onion response is now validated before adoption, and reconnect tests cover missing and invalid service IDs—thanks @vasild!
l0rinc (Migrated from github.com) reviewed 2026-09-28 03:20:12 +00:00
Lines 533-553
l0rinc (Migrated from github.com) commented 2026-09-28 03:20:12 +00:00

Thanks, hope this will make you sleep better!

Thanks, hope this will make you sleep better!
vasild (Migrated from github.com) approved these changes 2026-09-28 10:15:13 +00:00
vasild (Migrated from github.com) left a comment

ACK 0a53d12589

Thanks!

Show Signature
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA256

ACK 0a53d12589c3116495a50a694006ce5ee220fb2d

Thanks!
-----BEGIN PGP SIGNATURE-----

iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmq6PiAbFIAAAAAABAAO
bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/PgEf/Rw/kX9jY7nOlP0gAQrG
4UYTzMrUzBrez1DUkOge20qwk2OoRPlLzUqMvzmFFOK+MEqukrC7JuSS+WtEQAsh
jBk9oiTx2a56xj8+beIYebBpfYzvWlOjl1mfWgQocP13+b1sxXc0aVRS0N9T5+/5
iULjg/0xKG1l9QK0rXpKDhL7QCF1fMr+jbdLaUzmCLlCa/FofooYjfTepl5S+OnC
029URxW9pgRZlNRHWOM4W+s0u03B4ET0sOvUMDu6lvAQ1jixzUzfqJpyh7aFYwEf
Tnu8nwbukfpi5JwL8g9Kb2ik2RKW632YaSdNPw4NkcKn1CmSQc6h6k23cXZ1oTEc
3B8dvbMPDC80IBbtBkUE8+I6OWemmADhhtOxrJH0UysB5Vmg8Y8jSJQNw5+r0M58
Mc9cSWzNQteDAQwR52sRlgEfR0ZNzFiy4nLYQvbuIYBFeN4qdJ0MugJsNRhD3XSh
jl7DYHrRVXqoSUUR0wFvv6WOnzF4uJ42w8dvkr52kjkFoeDNJ+VlGP21Y9Ls0iBo
nhGYTHo9rdIeStvHZ6HLnoUGGhdrOC/EH+VMx04KYSQM4NWqHuE8tmN1jDGgkihm
e/RqaSr54xzIAFjei/zlBYoQ8hIiC+tHpwsLPtP7xu00Tl+WmlolgOxkuS3Mxyr/
rFm6yed9RkecQQcrexCMhmWvcBJvchvv1lkilA3a72JZz6SNsRR6h8Jz71PEtVP1
WWA215yYrG/lp93YprSr6j4COlGWH4y5xTkaZyUvKMfq+KCs82IBeE07k4nSOP9b
21TaN9kao2JN6NrIIFVicX31gSyQrZ1SN4UQ/if414gKFleHR7XKdoVRjJnAA3oV
+4mzEBVYLyob0poOMJVQwvDeD+J340pqjYiHAH8XSa5btkEdKdUWHhs8kmjcMvFD
I2tW719qzy1m/hKyXkGk60f8gtPhfohcE4+PEB8Vs8VSVIl6DNcg/RWnG5P6hcg7
TZQPsqauQ3yx1S8okkfj+e8H82TZYXH0wh7tndWj7WiGpUPtIbXlzHa3sws6ay2C
IM0A+8Z4SvPj7F7FWgauglT8dtcqVVhANAFQqUbLY5ObYrxZwyO7aG2fgjVPxN8z
x1RSseIH1zbMmojH7qcwOZ6k3Kv3o4TpLs9sYso5y7C3vmGbHrcfnYUYSq5kXqZk
dM0qowKVuBAYfXfcLrq9spipdevd7p5ZiUh+0or7xqHm+QTO3Sr7qY9Uazl/znzk
GK+ByxZpRonpIoPQ3fHji7rn1q3aziPooWbQ2Ze78LhDTUO3Kw/jZvFUyN4Tqjfq
XK4lrrjx+VphNKbqEMI9+UvI17jkwqse15EAxsk8Urd6zXZjhjo8G6vkN7oyAm0n
PqM=
=AEcH
-----END PGP SIGNATURE-----

vasild's public key is on openpgp.org

ACK 0a53d12589c3116495a50a694006ce5ee220fb2d Thanks! <details> <summary>Show Signature</summary> ``` -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA256 ACK 0a53d12589c3116495a50a694006ce5ee220fb2d Thanks! -----BEGIN PGP SIGNATURE----- iQRPBAEBCAA5FiEE5k2NRWFNsHVF2czBVN8G9ktVy78FAmq6PiAbFIAAAAAABAAO bWFudTIsMi41KzEuMTIsMiwzAAoJEFTfBvZLVcu/PgEf/Rw/kX9jY7nOlP0gAQrG 4UYTzMrUzBrez1DUkOge20qwk2OoRPlLzUqMvzmFFOK+MEqukrC7JuSS+WtEQAsh jBk9oiTx2a56xj8+beIYebBpfYzvWlOjl1mfWgQocP13+b1sxXc0aVRS0N9T5+/5 iULjg/0xKG1l9QK0rXpKDhL7QCF1fMr+jbdLaUzmCLlCa/Fofoo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ooWbQ2Ze78LhDTUO3Kw/jZvFUyN4Tqjfq XK4lrrjx+VphNKbqEMI9+UvI17jkwqse15EAxsk8Urd6zXZjhjo8G6vkN7oyAm0n PqM= =AEcH -----END PGP SIGNATURE----- ``` vasild's public key is [on openpgp.org](https://keys.openpgp.org/vks/v1/by-fingerprint/850E138BA9C0923881DFD55FCE712013582E2230) </details>
winterrdog (Migrated from github.com) reviewed 2026-09-28 11:20:07 +00:00
winterrdog (Migrated from github.com) left a comment

reACK a3537ed6a3

again, successfully built and tested with clang++-19 on FreeBSD 15.0, targeting x86_64

reACK a3537ed6a344b5fdd4c9d4860985f9dc1521feb1 again, successfully built and tested with `clang++-19` on FreeBSD `15.0`, targeting `x86_64`
winterrdog (Migrated from github.com) commented 2026-09-28 11:18:12 +00:00

small non-blocking nit, feel free to ignore: would it make sense to avoid
caching PRIVATE_KEY_NEW, since it is a request token rather than a private
key ?

if TOR ever returns a ServiceID without a PrivateKey, we would currently
save NEW:ED25519-V3 to onion_v3_private_key. a properly functional TOR
should not do sth like this since we never send DiscardPK, but a broken or
malicious endpoint could

skipping the write should not change the behaviour. auth_cb() already
recreates the NEW request when m_private_key is empty. it would just avoid
leaving a file that looks like a cached key but isn't one, including
a potentially truncated NEW:ED2... file after a crash (pragmatically less
likely)

the normal path, where TOR returns a real key, stays unchanged. we could skip
the write while m_private_key is still PRIVATE_KEY_NEW and log a short
factual warning that Tor returned no key

(this is just for open discussion)

small _non_-blocking nit, feel free to ignore: would it make sense to avoid caching `PRIVATE_KEY_NEW`, since it is a request token rather than a private key ? if TOR ever returns a `ServiceID` without a `PrivateKey`, we would currently save `NEW:ED25519-V3` to `onion_v3_private_key`. a properly functional TOR should not do sth like this since we never send `DiscardPK`, but a broken or malicious endpoint could skipping the write should not change the behaviour. `auth_cb()` already recreates the `NEW` request when `m_private_key` is empty. it would just avoid leaving a file that looks like a cached key but isn't one, including a _potentially_ truncated `NEW:ED2...` file after a crash (pragmatically less likely) the normal path, where TOR returns a real key, stays unchanged. we could skip the write while `m_private_key` is still `PRIVATE_KEY_NEW` and log a short factual warning that Tor returned no key _(this is just for open discussion)_
First-time contributor

2 suggestions · 2 previous suggestions

🔵 Suggestion

A fake Tor endpoint can replace an existing onion key with a key it controls

Location: src/torcontrol.cpp:536 (head).

The format check blocks malformed keys but does not prevent permanent replacement with a well-formed key; this gap predates the change.

Details and suggested fix

When a key is cached, auth_cb() sends it in ADD_ONION. If the reply includes a valid ServiceID and a PrivateKey that passes IsWellFormedPrivateKey(), the code adopts and caches that key without checking whether the node requested a new one. A local process answering on the loopback control port while Tor is down can therefore replace an existing key with one it knows. When the node later uses that key with real Tor, the attacker can host the same advertised onion address and receive inbound connections meant for the node. The base code also adopted returned keys, so this change neither introduces nor worsens the gap, but it leaves part of the stated threat model unaddressed. The Tor control specification describes the returned PrivateKey as the newly generated key, which DiscardPK suppresses. Adopt a returned key only when m_private_key == PRIVATE_KEY_NEW; this should not affect real Tor and keeps the cache unchanged otherwise. This does not protect a node that has no cached key yet.

🔵 Suggestion

Malformed-cache warning omits the required restart

Location: src/torcontrol.cpp:575 (head).

Removing the file while the node is running has no effect, so following the warning alone leaves the onion service unavailable.

Details and suggested fix

The cached key is read only in the TorController constructor, which init.cpp calls once at startup. When auth_cb() finds a malformed key, it returns without clearing or reloading m_private_key. Removing the file while the node runs therefore leaves the malformed key in memory, and every reconnect logs the same refusal. The PR description gives the correct recovery: remove the file and restart the node. Update the warning to say, for example, “remove the file and restart to generate a new key.”


Previous suggestions (2)
[Suggestion · still present] Malformed-key tests do not verify that a cached key survives

A regression that adopts a malformed reply key before rejecting it could pass these tests but leave the onion service unavailable after reconnects.

Each malformed-key case starts without a cached key because restart_with_mock() deletes the file. The cases check the warning and that no cache file was written, but do not reconnect to check the next ADD_ONION. If a change assigned the reply key to m_private_key before returning from IsWellFormedPrivateKey(), those checks would still pass. On reconnect, auth_cb() would refuse the malformed in-memory key, leaving the onion service unavailable until restart, even if Tor is healthy. Seed the cache with VALID_PRIVATE_KEY, have the mock return a malformed PrivateKey, then reconnect and assert that the next ADD_ONION uses VALID_PRIVATE_KEY and that the cache file is unchanged.

Location: test/functional/feature_torcontrol.py:341 (head).

First reported at 0a53d12589c3116495a50a694006ce5ee220fb2d. Last checked at 0a53d12589c3116495a50a694006ce5ee220fb2d. The author plans to address this separately. Author reply 2026-09-25T03:46:56Z Author reply 2026-09-28T03:19:42Z

[Suggestion · still present] Document malformed-cache recovery in a release note

The new check leaves -listenonion unavailable when the cached key is malformed, and recovery requires removing the cache file and restarting. The warning gives this recovery instruction at runtime, but users encountering the change after upgrading should also be told in a PR-specific release note. The Developer Notes call for release notes for significant bug fixes and visible end-user changes.

Location: src/torcontrol.cpp:575 (head).

First reported at 0a53d12589c3116495a50a694006ce5ee220fb2d. Last checked at 0a53d12589c3116495a50a694006ce5ee220fb2d. Author reply 2026-09-04T20:09:14Z

Review coverage was incomplete.

Review limitations
  • adversarial_claude: Tor's source is not in this checkout, so two points rely on recalled Tor behavior. First, Tor's ADD_ONION reply is assumed to encode an ED25519-V3 key as padded Base64 (88 characters ending in "=="); if it is unpadded, the new length check would reject every real key and every existing cached key. Second, Tor is assumed to return a PrivateKey line only when the request was NEW.
  • verifier: Tor's control-port source is not in this checkout. The assumption that real Tor returns ED25519-V3 keys as padded Base64 (86 data characters followed by "==") is supported only by external Tor documentation: base64_encode adds padding and base64_encode_nopad strips it. It is not supported by Tor's ADD_ONION code. If Tor returned unpadded keys, IsWellFormedPrivateKey would reject every real returned key and every existing cached key.
  • verifier: The claim that Tor returns a PrivateKey line only for NEW requests relies on the control spec's DiscardPK wording, which refers to the newly generated private key. Tor's handler was not inspected. This affects only whether the correction in adversarial_claude:1 is compatible with real Tor, not its factual premise.

Base: 0f27bed5b292 · Head: 0a53d12589c3 · Full review report

<!-- forgejo-review-bot:bitcoin/bitcoin --> <!-- ralph-engine:current:aadde06fc908436af97c3ae22ac03220a75b46811daf747af5f90dd2d5b368be:58df985c6f760decb26503b27f8441ea78138ad8e02f110fa19b993630f18590 --> <!-- ralph-base:0f27bed5b2924420d65caeca439e6b036d3c6cb2 --> <!-- ralph-head:0a53d12589c3116495a50a694006ce5ee220fb2d --> <!-- ralph-case:f94bb3cd3cf9869a25944091bfd354cbae1559b21b270668a6317095695aec6e --> 2 suggestions · 2 previous suggestions **🔵 Suggestion** **A fake Tor endpoint can replace an existing onion key with a key it controls** Location: [`src/torcontrol.cpp:536`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/0a53d12589c3116495a50a694006ce5ee220fb2d/src/torcontrol.cpp#L536>) (head). The format check blocks malformed keys but does not prevent permanent replacement with a well-formed key; this gap predates the change. <details> <summary>Details and suggested fix</summary> When a key is cached, `auth_cb()` sends it in `ADD_ONION`. If the reply includes a valid `ServiceID` and a `PrivateKey` that passes `IsWellFormedPrivateKey()`, the code adopts and caches that key without checking whether the node requested a new one. A local process answering on the loopback control port while Tor is down can therefore replace an existing key with one it knows. When the node later uses that key with real Tor, the attacker can host the same advertised onion address and receive inbound connections meant for the node. The base code also adopted returned keys, so this change neither introduces nor worsens the gap, but it leaves part of the stated threat model unaddressed. The Tor control specification describes the returned `PrivateKey` as the newly generated key, which `DiscardPK` suppresses. Adopt a returned key only when `m_private_key == PRIVATE_KEY_NEW`; this should not affect real Tor and keeps the cache unchanged otherwise. This does not protect a node that has no cached key yet. </details> **🔵 Suggestion** **Malformed-cache warning omits the required restart** Location: [`src/torcontrol.cpp:575`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/0a53d12589c3116495a50a694006ce5ee220fb2d/src/torcontrol.cpp#L575>) (head). Removing the file while the node is running has no effect, so following the warning alone leaves the onion service unavailable. <details> <summary>Details and suggested fix</summary> The cached key is read only in the `TorController` constructor, which `init.cpp` calls once at startup. When `auth_cb()` finds a malformed key, it returns without clearing or reloading `m_private_key`. Removing the file while the node runs therefore leaves the malformed key in memory, and every reconnect logs the same refusal. The PR description gives the correct recovery: remove the file and restart the node. Update the warning to say, for example, “remove the file and restart to generate a new key.” </details> --- <details> <summary>Previous suggestions (2)</summary> <details> <summary>[Suggestion · still present] Malformed-key tests do not verify that a cached key survives</summary> A regression that adopts a malformed reply key before rejecting it could pass these tests but leave the onion service unavailable after reconnects. Each malformed-key case starts without a cached key because `restart_with_mock()` deletes the file. The cases check the warning and that no cache file was written, but do not reconnect to check the next `ADD_ONION`. If a change assigned the reply key to `m_private_key` before returning from `IsWellFormedPrivateKey()`, those checks would still pass. On reconnect, `auth_cb()` would refuse the malformed in-memory key, leaving the onion service unavailable until restart, even if Tor is healthy. Seed the cache with `VALID_PRIVATE_KEY`, have the mock return a malformed `PrivateKey`, then reconnect and assert that the next `ADD_ONION` uses `VALID_PRIVATE_KEY` and that the cache file is unchanged. Location: [`test/functional/feature_torcontrol.py:341`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/0a53d12589c3116495a50a694006ce5ee220fb2d/test/functional/feature_torcontrol.py#L341>) (head). First reported at `0a53d12589c3116495a50a694006ce5ee220fb2d`. Last checked at `0a53d12589c3116495a50a694006ce5ee220fb2d`. The author plans to address this separately. [Author reply](https://github.com/bitcoin/bitcoin/pull/36142#issuecomment-5826341146) 2026-09-25T03:46:56Z [Author reply](https://github.com/bitcoin/bitcoin/pull/36142#issuecomment-5862689023) 2026-09-28T03:19:42Z </details> <details> <summary>[Suggestion · still present] Document malformed-cache recovery in a release note</summary> The new check leaves `-listenonion` unavailable when the cached key is malformed, and recovery requires removing the cache file and restarting. The warning gives this recovery instruction at runtime, but users encountering the change after upgrading should also be told in a PR-specific release note. The Developer Notes call for release notes for significant bug fixes and visible end-user changes. Location: [`src/torcontrol.cpp:575`](<https://git.fish.foo/bitcoin/bitcoin/src/commit/0a53d12589c3116495a50a694006ce5ee220fb2d/src/torcontrol.cpp#L575>) (head). First reported at `0a53d12589c3116495a50a694006ce5ee220fb2d`. Last checked at `0a53d12589c3116495a50a694006ce5ee220fb2d`. [Author reply](https://github.com/bitcoin/bitcoin/pull/36142#issuecomment-5545894123) 2026-09-04T20:09:14Z </details> </details> Review coverage was incomplete. ##### Review limitations - adversarial_claude: Tor's source is not in this checkout, so two points rely on recalled Tor behavior. First, Tor's ADD_ONION reply is assumed to encode an ED25519-V3 key as padded Base64 (88 characters ending in "=="); if it is unpadded, the new length check would reject every real key and every existing cached key. Second, Tor is assumed to return a PrivateKey line only when the request was NEW. - verifier: Tor's control-port source is not in this checkout. The assumption that real Tor returns ED25519-V3 keys as padded Base64 (86 data characters followed by "==") is supported only by external Tor documentation: base64_encode adds padding and base64_encode_nopad strips it. It is not supported by Tor's ADD_ONION code. If Tor returned unpadded keys, IsWellFormedPrivateKey would reject every real returned key and every existing cached key. - verifier: The claim that Tor returns a PrivateKey line only for NEW requests relies on the control spec's DiscardPK wording, which refers to the newly generated private key. Tor's handler was not inspected. This affects only whether the correction in adversarial_claude:1 is compatible with real Tor, not its factual premise. <!-- Review tier: sensitive --> --- Base: [`0f27bed5b292`](<https://git.fish.foo/bitcoin/bitcoin/commit/0f27bed5b2924420d65caeca439e6b036d3c6cb2>) · Head: [`0a53d12589c3`](<https://git.fish.foo/bitcoin/bitcoin/commit/0a53d12589c3116495a50a694006ce5ee220fb2d>) · [Full review report](<https://review.fish.foo/traces/36142-0a53d12589c3116495a50a694006ce5ee220fb2d-1608-3.html>)
l0rinc (Migrated from github.com) reviewed 2026-09-28 16:45:35 +00:00
l0rinc (Migrated from github.com) commented 2026-09-28 16:45:35 +00:00

I don't have strong opinions, tried renaming (see https://github.com/bitcoin/bitcoin/pull/36142#discussion_r4107908953), other places already use these names, we can unify in a followup.

I don't have strong opinions, tried renaming (see https://github.com/bitcoin/bitcoin/pull/36142#discussion_r4107908953), other places already use these names, we can unify in a followup.
l0rinc (Migrated from github.com) reviewed 2026-09-28 16:47:58 +00:00
Lines 550-554
l0rinc (Migrated from github.com) commented 2026-09-28 16:47:58 +00:00

Please check the latest version, tell me if you think it resolves your concerns

Please check the latest version, tell me if you think it resolves your concerns
l0rinc commented 2026-09-28 16:49:02 +00:00 (Migrated from github.com)

@winterrdog, if you agree with the latest version, please update your ACK hash. If you don't please explain what you think should be changed.

@winterrdog, if you agree with the latest version, please update your ACK hash. If you don't please explain what you think should be changed.
winterrdog (Migrated from github.com) reviewed 2026-09-29 09:31:03 +00:00
winterrdog (Migrated from github.com) commented 2026-09-29 09:31:03 +00:00

other places already use these names, we can unify in a followup.

all right

> other places already use these names, we can unify in a followup. all right
winterrdog commented 2026-09-29 09:31:09 +00:00 (Migrated from github.com)

if you agree with the latest version, please update your ACK hash.

i fully agree with everything. i have updated the ACK hash too because i did not intend to use an older hash

thank you for pointing that out

> if you agree with the latest version, please update your ACK hash. i fully agree with everything. i have updated the ACK hash too because i did not intend to use an older hash thank you for pointing that out
jpk68 commented 2026-10-21 16:30:37 +00:00 (Migrated from github.com)
ACK 0a53d12589c3116495a50a694006ce5ee220fb2d
sedited (Migrated from github.com) approved these changes 2026-11-05 10:34:10 +00:00
sedited (Migrated from github.com) left a comment
ACK 0a53d12589c3116495a50a694006ce5ee220fb2d
fanquake commented 2026-11-16 17:43:36 +00:00 (Migrated from github.com)

Just wanted to note here that the issue fixed in this PR was also reported by @OSINTv96, earlier in the year.

Just wanted to note here that the issue fixed in this PR was also reported by @OSINTv96, earlier in the year.
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!36142
No description provided.