Merge bitcoin/bitcoin#36142: net: validate Tor onion service replies and cached keys
What changed, and why it matters
This update fixes a weakness in how Bitcoin Core talks to the Tor control port when setting up a hidden onion service. A fake or compromised Tor control endpoint could trick the node into storing a malicious private key. On a later reconnect, that bad key could be inserted into an 'ADD_ONION' command in a way that adds extra commands or arguments for Tor to run. The fix checks that any returned or cached private key has the expected format and that the returned onion address is a valid Tor v3 service ID before using or saving it.
Apply the merge commit. Nodes that expose a Tor onion service should upgrade, because an unprivileged local process or a compromised Tor control endpoint could otherwise inject commands into the Tor control session. Operators using -torcontrol with non-default endpoints should also verify endpoint integrity.
Security signals we found
Tor control protocol command/argument injection via unescaped quoted reply values
Insufficient validation of attacker-influenced private key before caching and reuse
Insufficient validation of returned onion service ID before adoption and advertisement
Local privilege escalation/persistence by impersonating the Tor control endpoint on loopback
Cross-session cache poisoning of onion private key file
Evidence from the diff
The patch hardens src/torcontrol.cpp’s ADD_ONION reply handling. It introduces IsWellFormedPrivateKey(), which only accepts ‘NEW:ED25519-V3’ or ‘ED25519-V3:<64-byte base64>’. Reply parsing now keeps ServiceID and PrivateKey in local variables until validated. The service ID is validated as a Tor v3 onion address via CService::IsTor() before logging, caching, or advertising. Cached keys are also validated before reuse. If validation fails, the code returns early and does not write the key to disk or send it in a later ADD_ONION command, preventing command/argument injection via unescaped CRLF or spaces.
Changed components
src/torcontrol.cppsrc/torcontrol.htest/functional/feature_torcontrol.pyTor hidden service creation and reconnect logicOnion private key cache fileInspect captured patch +141 / −24
### src/torcontrol.cpp
@@ -70,6 +70,17 @@ constexpr int MAX_LINE_LENGTH = 100000;
constexpr int MAX_LINE_COUNT = 1000;
/** Timeout for socket operations */
constexpr auto SOCKET_SEND_TIMEOUT = 10s;
+constexpr std::string_view PRIVATE_KEY_NEW{"NEW:ED25519-V3"};
+constexpr std::string_view PRIVATE_KEY_PREFIX{"ED25519-V3:"};
+
+/** Whether the value requests a new Ed25519 v3 key or has the expected key format */
+static bool IsWellFormedPrivateKey(std::string_view key)
+{
+ if (key == PRIVATE_KEY_NEW) return true;
+ if (!key.starts_with(PRIVATE_KEY_PREFIX)) return false;
+ const auto decoded{DecodeBase64(key.substr(PRIVATE_KEY_PREFIX.size()))};
+ return decoded && decoded->size() == 64; // A 32-byte secret scalar followed by a 32-byte PRF secret
+}
/****** Low-level TorControlConnection ********/
@@ -495,23 +506,36 @@ void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlRe
{
if (reply.code == TOR_REPLY_OK) {
LogDebug(BCLog::TOR, "ADD_ONION successful (PoW defenses %s)", pow_was_enabled ? "enabled" : "disabled");
+ std::string service_id;
+ std::string private_key;
for (const std::string &s : reply.lines) {
std::map<std::string,std::string> m = ParseTorReplyMapping(s);
std::map<std::string,std::string>::iterator i;
if ((i = m.find("ServiceID")) != m.end())
- m_service_id = i->second;
- if ((i = m.find("PrivateKey")) != m.end())
- m_private_key = i->second;
+ service_id = i->second;
+ if ((i = m.find("PrivateKey")) != m.end()) {
+ if (!IsWellFormedPrivateKey(i->second)) { // Never adopt or cache such a key
+ LogWarning("tor: ADD_ONION returned a malformed private key");
+ return;
+ }
+ private_key = i->second;
+ }
}
- if (m_service_id.empty()) {
+ if (service_id.empty()) {
LogWarning("tor: Error parsing ADD_ONION parameters:");
for (const std::string &s : reply.lines) {
LogWarning(" %s", SanitizeString(s));
}
return;
}
- m_service = LookupNumeric(std::string(m_service_id+".onion"), Params().GetDefaultPort());
- LogInfo("Got tor service ID %s, advertising service %s", m_service_id, m_service.ToStringAddrPort());
+ const auto service{LookupNumeric(service_id + ".onion", Params().GetDefaultPort())};
+ if (!service.IsTor()) {
+ LogWarning("tor: ADD_ONION returned an invalid service ID");
+ return;
+ }
+ if (!private_key.empty()) m_private_key = std::move(private_key);
+ m_service = service;
+ LogInfo("Got tor service ID %s, advertising service %s", service_id, m_service.ToStringAddrPort());
if (WriteBinaryFile(GetPrivateKeyFile(), m_private_key)) {
LogDebug(BCLog::TOR, "Cached service private key to %s", fs::PathToString(GetPrivateKeyFile()));
} else {
@@ -545,7 +569,11 @@ void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply&
// Finally - now create the service
if (m_private_key.empty()) { // No private key, generate one
- m_private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
+ m_private_key = PRIVATE_KEY_NEW; // Explicitly request key type - see issue #9214
+ } else if (!IsWellFormedPrivateKey(m_private_key)) {
+ // add_onion_cb() never adopts such a key, so it can only come from the cache file
+ LogWarning("tor: Refusing to use cached private key %s because it is malformed; remove the file to generate a new key", fs::PathToString(GetPrivateKeyFile()));
+ return;
}
// Request onion service, redirect port.
_conn.Command(MakeAddOnionCmd(m_private_key, m_target.ToStringAddrPort(), /*enable_pow=*/true),
### src/torcontrol.h
@@ -142,7 +142,6 @@ class TorController
const std::string m_tor_control_center;
TorControlConnection m_conn;
std::string m_private_key;
- std::string m_service_id;
std::atomic<bool> m_reconnect;
std::chrono::duration<double> m_reconnect_timeout;
CService m_service;
### test/functional/feature_torcontrol.py
@@ -13,16 +13,21 @@
p2p_port,
)
+SERVICE_ID = "pg6mmjiyjmcrsslvykfwnntlaru7p5svn6y2ymmju6nubxndf4pscryd"
+VALID_PRIVATE_KEY = "ED25519-V3:wMHCw8TFxsfIycrLzM3Oz9DR0tPU1dbX2Nna29zd3t/g4eLj5OXm5+jp6uvs7e7v8PHy8/T19vf4+fr7/P3+/w==" # 64 arbitrary bytes encoded as Base64
+
class MockTorControlServer:
- def __init__(self, port, manual_mode=False):
+ def __init__(self, port, manual_mode=False, private_key=None, service_id=SERVICE_ID):
self.port = port
self.sock = None
self.conn = None
self.running = False
self.thread = None
self.received_commands = []
self.manual_mode = manual_mode
+ self.private_key = private_key
+ self.service_id = service_id
self.conn_ready = threading.Event()
def start(self):
@@ -83,6 +88,9 @@ def send_raw(self, data):
if self.conn:
self.conn.sendall(data.encode('utf-8'))
+ def add_onion_keys(self):
+ return [command.split()[1] for command in self.received_commands if command.startswith("ADD_ONION ")]
+
def _get_response(self, command):
if command == "PROTOCOLINFO 1":
return (
@@ -94,10 +102,10 @@ def _get_response(self, command):
elif command == "AUTHENTICATE":
return "250 OK\r\n"
elif command.startswith("ADD_ONION"):
- return (
- "250-ServiceID=testserviceid1234567890123456789012345678901234567890123456\r\n"
- "250 OK\r\n"
- )
+ reply = "" if self.service_id is None else f"250-ServiceID={self.service_id}\r\n"
+ if self.private_key:
+ reply += f"250-PrivateKey={self.private_key}\r\n"
+ return reply + "250 OK\r\n"
elif command.startswith("GETINFO"):
return "250-net/listeners/socks=\"127.0.0.1:9050\"\r\n250 OK\r\n"
else:
@@ -112,9 +120,19 @@ def next_port(self):
self._port_counter = getattr(self, '_port_counter', 0) + 1
return p2p_port(self.num_nodes + self._port_counter)
- def restart_with_mock(self, mock_tor):
+ 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):
+ self.stop_node(0)
+ key_path = self.private_key_path()
+ if cached_private_key is None:
+ key_path.unlink(missing_ok=True)
+ assert not key_path.exists()
+ else:
+ key_path.write_bytes(cached_private_key.encode())
mock_tor.start()
- self.restart_node(0, extra_args=[
+ self.start_node(0, extra_args=[
f"-torcontrol=127.0.0.1:{mock_tor.port}",
"-listenonion=1",
"-debug=tor",
@@ -145,7 +163,8 @@ def test_basic(self):
self.log.info("Test Tor control basic functionality")
mock_tor = MockTorControlServer(self.next_port())
- self.restart_with_mock(mock_tor)
+ with self.nodes[0].assert_debug_log([f"Got tor service ID {SERVICE_ID}"], timeout=10):
+ self.restart_with_mock(mock_tor)
# Waiting for Tor control commands
self.wait_until(lambda: len(mock_tor.received_commands) >= 4, timeout=10)
@@ -157,6 +176,16 @@ def test_basic(self):
assert mock_tor.received_commands[3].startswith("ADD_ONION ")
assert "PoWDefensesEnabled=1" in mock_tor.received_commands[3]
+ self.log.info("Test a later ADD_ONION reply without a service ID")
+ mock_tor.service_id = None
+ mock_tor.private_key = VALID_PRIVATE_KEY
+ with self.nodes[0].assert_debug_log(["Error parsing ADD_ONION parameters:"], timeout=10):
+ mock_tor.conn.shutdown(socket.SHUT_WR)
+ self.wait_until(lambda: len(mock_tor.add_onion_keys()) >= 2, timeout=10)
+ mock_tor.conn.shutdown(socket.SHUT_WR)
+ self.wait_until(lambda: len(mock_tor.add_onion_keys()) >= 3, timeout=10)
+ assert_equal(mock_tor.add_onion_keys()[2], "NEW:ED25519-V3")
+
# Clean up
mock_tor.stop()
@@ -191,14 +220,8 @@ def test_pow_fallback(self):
class NoPowServer(MockTorControlServer):
def _get_response(self, command):
- if command.startswith("ADD_ONION"):
- if "PoWDefensesEnabled=1" in command:
- return "512 Unrecognized option\r\n"
- else:
- return (
- "250-ServiceID=testserviceid1234567890123456789012345678901234567890123456\r\n"
- "250 OK\r\n"
- )
+ if command.startswith("ADD_ONION") and "PoWDefensesEnabled=1" in command:
+ return "512 Unrecognized option\r\n"
return super()._get_response(command)
mock_tor = NoPowServer(self.next_port())
@@ -271,12 +294,79 @@ def test_reconnect_backoff(self):
mock_tor.stop()
+ def test_invalid_service_id(self):
+ invalid_service_id = "a" + SERVICE_ID[1:]
+ key_path = self.private_key_path()
+ mock_tor = MockTorControlServer(self.next_port(), private_key=VALID_PRIVATE_KEY, service_id=invalid_service_id)
+
+ self.log.info("Test an invalid service ID returned by ADD_ONION")
+ with self.nodes[0].assert_debug_log(["ADD_ONION returned an invalid service ID"], timeout=10):
+ self.restart_with_mock(mock_tor)
+ assert not key_path.exists()
+ mock_tor.conn.shutdown(socket.SHUT_WR)
+ self.wait_until(lambda: len(mock_tor.add_onion_keys()) >= 2, timeout=10)
+ assert_equal(mock_tor.add_onion_keys()[1], "NEW:ED25519-V3")
+ mock_tor.stop()
+
+ def test_private_key_tor_command_injection(self):
+ valid_private_key = VALID_PRIVATE_KEY
+ key_path = self.private_key_path()
+
+ self.log.info("Test that a valid returned private key is cached and reused")
+ tor_control_port = self.next_port()
+ mock_tor = MockTorControlServer(tor_control_port, private_key=valid_private_key)
+ with self.nodes[0].assert_debug_log(["Cached service private key"], timeout=10):
+ self.restart_with_mock(mock_tor)
+ assert_equal(key_path.read_bytes(), valid_private_key.encode())
+ mock_tor.stop()
+
+ mock_tor = MockTorControlServer(tor_control_port)
+ self.restart_with_mock(mock_tor, cached_private_key=valid_private_key)
+ self.wait_until(lambda: any(command.startswith(f"ADD_ONION {valid_private_key} ") for command in mock_tor.received_commands), timeout=10)
+ mock_tor.stop()
+
+ for private_key, injected in [
+ # A line break ends the ADD_ONION command, so Tor runs the rest of the key as a second command
+ (f"{valid_private_key}\r\nSIGNAL SHUTDOWN\r\n", "SIGNAL SHUTDOWN"),
+ # A space ends the key argument, so Tor parses the rest of the key as further ADD_ONION arguments
+ (f"{valid_private_key} Flags=Detach", "Flags=Detach"),
+ ]:
+ self.log.info(f"Test {injected!r} injected through a returned private key")
+ # A reply line ends at CRLF and an unquoted value at a space, so only a quoted value can carry either
+ escaped_private_key = private_key.replace("\r", "\\r").replace("\n", "\\n")
+ quoted_private_key = f'"{escaped_private_key}"'
+ mock_tor = MockTorControlServer(tor_control_port, private_key=quoted_private_key)
+ with self.nodes[0].assert_debug_log(["ADD_ONION returned a malformed private key"], timeout=10):
+ self.restart_with_mock(mock_tor)
+ assert not key_path.exists()
+ mock_tor.stop()
+
+ self.log.info(f"Test {injected!r} injected through a cached private key")
+ mock_tor = MockTorControlServer(tor_control_port)
+ with self.nodes[0].assert_debug_log([f"Refusing to use cached private key {key_path}"], timeout=10):
+ self.restart_with_mock(mock_tor, cached_private_key=private_key)
+ assert not any(injected in command for command in mock_tor.received_commands)
+ mock_tor.stop()
+
+ for malformed_private_key in (
+ valid_private_key.replace("ED25519-V3:", "RSA1024:", 1),
+ "ED25519-V3:$" + valid_private_key.partition(":")[2][1:],
+ "ED25519-V3:AA==",
+ ):
+ mock_tor = MockTorControlServer(tor_control_port, private_key=malformed_private_key)
+ with self.nodes[0].assert_debug_log(["ADD_ONION returned a malformed private key"], timeout=10):
+ self.restart_with_mock(mock_tor)
+ assert not key_path.exists()
+ mock_tor.stop()
+
def run_test(self):
self.test_basic()
self.test_partial_data()
self.test_pow_fallback()
self.test_oversized_line()
self.test_overmany_lines()
+ self.test_invalid_service_id()
+ self.test_private_key_tor_command_injection()
self.test_reconnect_backoff()
Why this scored 70/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.