Merge bitcoin/bitcoin#36637: torcontrol: send -torpassword hex-encoded to avoid escaping bugs
What changed, and why it matters
This change fixes how Bitcoin Core sends your Tor control password to the Tor daemon. Previously, the password was wrapped in quotes and only double-quote characters were escaped. If a password contained a backslash, Tor would misinterpret it, which could corrupt the password, fail authentication, or in theory allow command-injection-style tricks in the Tor control protocol. The fix sends the password as plain hexadecimal characters instead, which avoids escaping entirely. A new test verifies that passwords containing backslashes and quotes now work correctly.
Users who set -torpassword with special characters (especially backslashes or quotes) should upgrade. Reviewers should confirm the hex encoding matches Tor's control-spec grammar and that no other QuotedString fields remain under-escaped.
Security signals we found
Improper escaping of protocol string (QuotedString)
Potential Tor control command boundary confusion
Authentication bypass/failure risk for Tor control
Functional test added for backslash and quote characters
Evidence from the diff
In src/torcontrol.cpp, TorController::protocolinfo_cb previously sent AUTHENTICATE "
Changed components
src/torcontrol.cpptest/functional/feature_torcontrol.pyInspect captured patch +42 / −6
### src/torcontrol.cpp
@@ -38,7 +38,6 @@
#include <utility>
#include <vector>
-using util::ReplaceAll;
using util::SplitString;
using util::ToString;
@@ -686,14 +685,14 @@ void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorContro
// Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
/* Authentication:
* cookie: hex-encoded ~/.tor/control_auth_cookie
- * password: "password"
+ * password: hex-encoded password
*/
std::string torpassword = gArgs.GetArg("-torpassword", "");
if (!torpassword.empty()) {
if (methods.contains("HASHEDPASSWORD")) {
LogDebug(BCLog::TOR, "Using HASHEDPASSWORD authentication");
- ReplaceAll(torpassword, "\"", "\\\"");
- _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind_front(&TorController::auth_cb, this));
+ // Send the password hex-encoded rather than as a QuotedString, so it never needs escaping.
+ _conn.Command("AUTHENTICATE " + HexStr(torpassword), std::bind_front(&TorController::auth_cb, this));
} else {
LogWarning("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available");
}
### test/functional/feature_torcontrol.py
@@ -123,7 +123,7 @@ def next_port(self):
def private_key_path(self):
return self.nodes[0].chain_path / "onion_v3_private_key"
- def restart_with_mock(self, mock_tor, cached_private_key=None):
+ def restart_with_mock(self, mock_tor, cached_private_key=None, extra_args=None):
self.stop_node(0)
key_path = self.private_key_path()
if cached_private_key is None:
@@ -136,7 +136,7 @@ def restart_with_mock(self, mock_tor, cached_private_key=None):
f"-torcontrol=127.0.0.1:{mock_tor.port}",
"-listenonion=1",
"-debug=tor",
- ])
+ ] + (extra_args or []))
# Wait for connection and PROTOCOLINFO command
mock_tor.conn_ready.wait(timeout=10)
@@ -215,6 +215,42 @@ def test_partial_data(self):
# Clean up
mock_tor.stop()
+ def test_password_auth(self):
+ self.log.info("Test that -torpassword is sent hex-encoded, so special characters survive")
+
+ class HashedPasswordServer(MockTorControlServer):
+ def __init__(self, port, expected_password):
+ self.expected_hex = expected_password.encode().hex()
+ super().__init__(port)
+
+ def _get_response(self, command):
+ if command == "PROTOCOLINFO 1":
+ return (
+ "250-PROTOCOLINFO 1\r\n"
+ "250-AUTH METHODS=HASHEDPASSWORD\r\n"
+ "250-VERSION Tor=\"0.1.2.3\"\r\n"
+ "250 OK\r\n"
+ )
+ elif command.startswith("AUTHENTICATE "):
+ sent_hex = command.removeprefix("AUTHENTICATE ")
+ if sent_hex != self.expected_hex:
+ return "515 Bad authentication\r\n"
+ return "250 OK\r\n"
+ return super()._get_response(command)
+
+ password = 'pa\\ss"word\\'
+ mock_tor = HashedPasswordServer(self.next_port(), password)
+ self.restart_with_mock(mock_tor, extra_args=[f"-torpassword={password}"])
+
+ self.wait_until(lambda: len(mock_tor.received_commands) >= 2, timeout=10)
+ assert_equal(mock_tor.received_commands[1], f"AUTHENTICATE {password.encode().hex()}")
+
+ # Authentication succeeded, so the node goes on to create the onion service
+ self.wait_until(lambda: any(c.startswith("ADD_ONION ") for c in mock_tor.received_commands), timeout=10)
+
+ # Clean up
+ mock_tor.stop()
+
def test_pow_fallback(self):
self.log.info("Test that ADD_ONION retries without PoW on 512 error")
@@ -362,6 +398,7 @@ def test_private_key_tor_command_injection(self):
def run_test(self):
self.test_basic()
self.test_partial_data()
+ self.test_password_auth()
self.test_pow_fallback()
self.test_oversized_line()
self.test_overmany_lines()Why this scored 49/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.