mirror of
https://github.com/bitcoin/bitcoin
synced 2026-12-04 10:47:36 +00:00
net: validate Tor onion service replies and cached keys #36142
Labels
No labels
Android
Backport
Block storage
Brainstorming
Bug
Build system
CI failed
Consensus
Data corruption
Descriptors
Docs
DrahtBot Guix build requested
Feature
Fuzzing
GUI
Good First Review
IPC
Insufficient Review
Kernel
Linux/Unix
Mempool
Mining
Needs Backport (31.x)
Needs Backport (32.x)
Needs Benchmark
Needs Conceptual Review
Needs backport (30.x)
Needs rebase
Needs release note
Net
P2P
PSBT
Privacy
Private Broadcast
Questions and Help
RPC/REST/ZMQ
Refactoring
Resource usage
Review club
Scripts and tools
Settings
TX fees and policy
Tests
Tracking Issue
UTXO Db and Indexes
Up for grabs
Upstream
Utils/log/libs
Validation
Waiting for author
Wallet
Windows
good first issue
interfaces
macOS
No milestone
No project
No assignees
2 participants
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
bitcoin/bitcoin!36142
Loading…
Reference in a new issue
No description provided.
Delete branch "l0rinc/tor-control-command-framing"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem: A node creates its onion service through Tor's control protocol and caches the returned
PrivateKeyvalue 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_ONIONcommand.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-V3or anED25519-V3key 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.
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.
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:
SAFECOOKIEauthentication by winterrdog)HASHEDPASSWORDauthentication 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.
concept ACK
Concept ACK
The CRLF side looks well covered. The space still gets through. The key goes into
ADD_ONIONunquoted, 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 thePort=forFlags=Detachand the service stays up after bitcoind exits.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 theADD_ONIONis 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.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.
I applied this locally and the torcontrol unit and functional tests still pass, with no assertion changed.
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_ONIONcommand:https://spec.torproject.org/control-spec/commands.html#add_onion
That is - better to treat anything that is not a valid base64 character as a malformed reply for
KeyBlob.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_ONIONcommand is passed toLookupNumeric()andLogInfo()(seeTorController::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.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.
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
.onionidentity, it seems worth doing the same here. just wanted to flag it while we are touching an area adjacent to private key handlingany thoughts? or the current approach is just fine ?
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 ; doneis a trivial way to exploit the first-write-then-set-permissions approach.There is
SetupEnvironment()which callsumask(0077)which should make the above safe, but still it would be better to callfs::permissions()first and thenfile << COOKIEAUTH_USER << ":" << rand_pwd_hex;in the above snippet. I am not sure whyfs::permissions()is needed if this relies on the global umask.ah, yes! case closed.
yes, not necessary
correct! i will find out why that is so
🐙 This pull request conflicts with the target branch and needs rebase.
Rebased, added coverage for service IDs with invalid checksums and returned private keys with unsupported types, invalid Base64, or the wrong length.
ACK
6b3e23fe68Some minor things below, feel free to ignore.
Show Signature
vasild's public key is on openpgp.org
The name
private_keygives the impression that it is... hmm... the private key, but actually it is<key type>:<private_key>.This text uses "invalid" and "malformed" interchangeably, but they are not quite the same:
aa:bb_c"dis malformed service id (contains invalid characters and is not 56 chars long)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/.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_keybefore this snippet runs. Otherwise theassert_equal()may pass due to a stale file being present upfront even ifbitcoinddoes not write to the file.Maybe easiest to add
key_path.unlink(missing_ok=True)beforeMockTorControlServer().Updated the invalid-vs-malformed wording, added extra assertion, simplified the injection cases and commit messages.
I tried a few names here and ended up keeping
private_key.Tor calls the full
KeyType:KeyBlobreply valuePrivateKey, and we store it inm_private_key, so the mock follows the same convention.Adjusted it everywhere, test name, log message, and commit text to use the nomenclature consistently.
The unlink seems to be present in
restart_with_mock()already - addedassert not key_path.exists()immediately after it to make the precondition explicit.tACK
a3537ed6a3successfully built and tested on this toolchain: FreeBSD
15.0/clang++-19/x86_64.the changes LGTM (look good to merge)
ACK
a3537ed6a3Not a blocker below. Just something worth mentioning.
Show Signature
vasild's public key is on openpgp.org
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 callsAddLocal().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_idandm_servicebefore 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 ofTorController::add_onion_cb().m_service_id- why is this even a member variable? It is used only insideTorController::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 fromLookupNumeric()and then checked whether is valid. If not, it will remain with its invalid value. Better do:Pushed, the onion response is now validated before adoption, and reconnect tests cover missing and invalid service IDs—thanks @vasild!
Thanks, hope this will make you sleep better!
ACK
0a53d12589Thanks!
Show Signature
vasild's public key is on openpgp.org
reACK
a3537ed6a3again, successfully built and tested with
clang++-19on FreeBSD15.0, targetingx86_64small 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 privatekey ?
if TOR ever returns a
ServiceIDwithout aPrivateKey, we would currentlysave
NEW:ED25519-V3toonion_v3_private_key. a properly functional TORshould not do sth like this since we never send
DiscardPK, but a broken ormalicious endpoint could
skipping the write should not change the behaviour.
auth_cb()alreadyrecreates the
NEWrequest whenm_private_keyis empty. it would just avoidleaving a file that looks like a cached key but isn't one, including
a potentially truncated
NEW:ED2...file after a crash (pragmatically lesslikely)
the normal path, where TOR returns a real key, stays unchanged. we could skip
the write while
m_private_keyis stillPRIVATE_KEY_NEWand log a shortfactual warning that Tor returned no key
(this is just for open discussion)
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 inADD_ONION. If the reply includes a validServiceIDand aPrivateKeythat passesIsWellFormedPrivateKey(), 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 returnedPrivateKeyas the newly generated key, whichDiscardPKsuppresses. Adopt a returned key only whenm_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
TorControllerconstructor, whichinit.cppcalls once at startup. Whenauth_cb()finds a malformed key, it returns without clearing or reloadingm_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 nextADD_ONION. If a change assigned the reply key tom_private_keybefore returning fromIsWellFormedPrivateKey(), 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 withVALID_PRIVATE_KEY, have the mock return a malformedPrivateKey, then reconnect and assert that the nextADD_ONIONusesVALID_PRIVATE_KEYand that the cache file is unchanged.Location:
test/functional/feature_torcontrol.py:341(head).First reported at
0a53d12589c3116495a50a694006ce5ee220fb2d. Last checked at0a53d12589c3116495a50a694006ce5ee220fb2d. 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
-listenonionunavailable 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 at0a53d12589c3116495a50a694006ce5ee220fb2d. Author reply 2026-09-04T20:09:14ZReview coverage was incomplete.
Review limitations
Base:
0f27bed5b292· Head:0a53d12589c3· Full review reportI 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.
Please check the latest version, tell me if you think it resolves your concerns
@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.
all right
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
ACK
0a53d12589ACK
0a53d12589Just wanted to note here that the issue fixed in this PR was also reported by @OSINTv96, earlier in the year.