Bitcoin Core 32.99.0
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1// Copyright (c) 2015-present The Bitcoin Core developers
2// Copyright (c) 2017 The Zcash developers
3// Distributed under the MIT software license, see the accompanying
4// file COPYING or http://www.opensource.org/licenses/mit-license.php.
5
6#include <torcontrol.h>
7
8#include <chainparams.h>
9#include <chainparamsbase.h>
10#include <common/args.h>
11#include <compat/compat.h>
12#include <crypto/hmac_sha256.h>
13#include <net.h>
14#include <netaddress.h>
15#include <netbase.h>
16#include <random.h>
17#include <tinyformat.h>
18#include <util/check.h>
19#include <util/fs.h>
20#include <util/log.h>
21#include <util/readwritefile.h>
22#include <util/strencodings.h>
23#include <util/string.h>
24#include <util/thread.h>
25#include <util/time.h>
26
27#include <algorithm>
28#include <cassert>
29#include <chrono>
30#include <cstdint>
31#include <cstdlib>
32#include <deque>
33#include <functional>
34#include <map>
35#include <optional>
36#include <set>
37#include <thread>
38#include <utility>
39#include <vector>
40
43using util::ToString;
44
46const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:" + ToString(DEFAULT_TOR_CONTROL_PORT);
48constexpr int TOR_COOKIE_SIZE = 32;
50constexpr int TOR_NONCE_SIZE = 32;
52static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
54static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
56constexpr std::chrono::duration<double> RECONNECT_TIMEOUT_START{1.0};
58constexpr double RECONNECT_TIMEOUT_EXP = 1.5;
60constexpr std::chrono::duration<double> RECONNECT_TIMEOUT_MAX{600.0};
65constexpr int MAX_LINE_LENGTH = 100000;
70constexpr int MAX_LINE_COUNT = 1000;
72constexpr auto SOCKET_SEND_TIMEOUT = 10s;
73
74/****** Low-level TorControlConnection ********/
75
77 : m_interrupt(interrupt)
78{
79}
80
82{
83 Disconnect();
84}
85
86bool TorControlConnection::Connect(const std::string& tor_control_center)
87{
88 if (m_sock) {
89 Disconnect();
90 }
91
92 std::optional<CService> control_service = Lookup(tor_control_center, DEFAULT_TOR_CONTROL_PORT, fNameLookup);
93 if (!control_service.has_value()) {
94 LogWarning("tor: Failed to look up control center %s", tor_control_center);
95 return false;
96 }
97
98 m_sock = ConnectDirectly(control_service.value(), /*manual_connection=*/true);
99 if (!m_sock) {
100 LogWarning("tor: Error connecting to address %s", tor_control_center);
101 return false;
102 }
103
104 m_recv_buffer.clear();
106 m_reply_handlers.clear();
107
108 LogDebug(BCLog::TOR, "Successfully connected to Tor control port");
109 return true;
110}
111
113{
114 m_sock.reset();
115 m_recv_buffer.clear();
117 m_reply_handlers.clear();
118}
119
121{
122 if (!m_sock) return false;
123 std::string errmsg;
124 const bool connected{m_sock->IsConnected(errmsg)};
125 if (!connected && !errmsg.empty()) {
126 LogDebug(BCLog::TOR, "Connection check failed: %s", errmsg);
127 }
128 return connected;
129}
130
131bool TorControlConnection::WaitForData(std::chrono::milliseconds timeout)
132{
133 if (!m_sock) return false;
134
135 Sock::Event event{0};
136 if (!m_sock->Wait(timeout, Sock::RecvEvent, &event)) {
137 return false;
138 }
139 if (event & Sock::ErrorEvent) {
140 LogDebug(BCLog::TOR, "Socket error detected");
141 Disconnect();
142 return false;
143 }
144
145 return (event & Sock::RecvEvent);
146}
147
149{
150 if (!m_sock) return false;
151
152 char buf[4096];
153 ssize_t nread = m_sock->Recv(buf, sizeof(buf), MSG_DONTWAIT);
154
155 if (nread < 0) {
156 int err = WSAGetLastError();
157 if (err == WSAEWOULDBLOCK || err == WSAEINTR || err == WSAEINPROGRESS) {
158 // No data available currently
159 return true;
160 }
161 LogWarning("tor: Error reading from socket: %s", NetworkErrorString(err));
162 return false;
163 }
164
165 if (nread == 0) {
166 LogDebug(BCLog::TOR, "End of stream");
167 return false;
168 }
169
170 m_recv_buffer.insert(m_recv_buffer.end(), buf, buf + nread);
171 try {
172 return ProcessBuffer();
173 } catch (const std::runtime_error& e) {
174 LogWarning("tor: Error processing receive buffer: %s", e.what());
175 return false;
176 }
177}
178
180{
182
183 while (auto line = reader.ReadLine()) {
184 if (m_message.lines.size() == MAX_LINE_COUNT) {
185 throw std::runtime_error(strprintf("Control port reply exceeded %d lines, disconnecting", MAX_LINE_COUNT));
186 }
187 // Skip short lines
188 if (line->size() < 4) continue;
189
190 // Parse: <code><separator><data>
191 // <status>(-|+| )<data>
192 m_message.code = ToIntegral<int>(line->substr(0, 3)).value_or(0);
193 m_message.lines.emplace_back(line->substr(4));
194 char separator = (*line)[3]; // '-', '+', or ' '
195
196 if (separator == ' ') {
197 if (m_message.code >= 600) {
198 // Async notifications are currently unused
199 // Synchronous and asynchronous messages are never interleaved
200 LogDebug(BCLog::TOR, "Received async notification %i", m_message.code);
201 } else if (!m_reply_handlers.empty()) {
202 // Invoke reply handler with message
203 m_reply_handlers.front()(*this, m_message);
204 m_reply_handlers.pop_front();
205 } else {
206 LogDebug(BCLog::TOR, "Received unexpected sync reply %i", m_message.code);
207 }
209 }
210 }
211
212 m_recv_buffer.erase(m_recv_buffer.begin(), m_recv_buffer.begin() + reader.Consumed());
213 return true;
214}
215
216bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
217{
218 if (!m_sock) return false;
219
220 std::string command = cmd + "\r\n";
221 try {
222 m_sock->SendComplete(std::span<const char>{command}, SOCKET_SEND_TIMEOUT, m_interrupt);
223 } catch (const std::runtime_error& e) {
224 LogWarning("tor: Error sending command: %s", e.what());
225 return false;
226 }
227
228 m_reply_handlers.push_back(reply_handler);
229 return true;
230}
231
232/****** General parsing utilities ********/
233
234/* Split reply line in the form 'AUTH METHODS=...' into a type
235 * 'AUTH' and arguments 'METHODS=...'.
236 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
237 * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
238 */
239std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
240{
241 size_t ptr=0;
242 std::string type;
243 while (ptr < s.size() && s[ptr] != ' ') {
244 type.push_back(s[ptr]);
245 ++ptr;
246 }
247 if (ptr < s.size())
248 ++ptr; // skip ' '
249 return make_pair(type, s.substr(ptr));
250}
251
258std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
259{
260 std::map<std::string,std::string> mapping;
261 size_t ptr=0;
262 while (ptr < s.size()) {
263 std::string key, value;
264 while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
265 key.push_back(s[ptr]);
266 ++ptr;
267 }
268 if (ptr == s.size()) // unexpected end of line
269 return std::map<std::string,std::string>();
270 if (s[ptr] == ' ') // The remaining string is an OptArguments
271 break;
272 ++ptr; // skip '='
273 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
274 ++ptr; // skip opening '"'
275 bool escape_next = false;
276 while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
277 // Repeated backslashes must be interpreted as pairs
278 escape_next = (s[ptr] == '\\' && !escape_next);
279 value.push_back(s[ptr]);
280 ++ptr;
281 }
282 if (ptr == s.size()) // unexpected end of line
283 return std::map<std::string,std::string>();
284 ++ptr; // skip closing '"'
295 std::string escaped_value;
296 for (size_t i = 0; i < value.size(); ++i) {
297 if (value[i] == '\\') {
298 // This will always be valid, because if the QuotedString
299 // ended in an odd number of backslashes, then the parser
300 // would already have returned above, due to a missing
301 // terminating double-quote.
302 ++i;
303 if (value[i] == 'n') {
304 escaped_value.push_back('\n');
305 } else if (value[i] == 't') {
306 escaped_value.push_back('\t');
307 } else if (value[i] == 'r') {
308 escaped_value.push_back('\r');
309 } else if ('0' <= value[i] && value[i] <= '7') {
310 size_t j;
311 // Octal escape sequences have a limit of three octal digits,
312 // but terminate at the first character that is not a valid
313 // octal digit if encountered sooner.
314 for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
315 // Tor restricts first digit to 0-3 for three-digit octals.
316 // A leading digit of 4-7 would therefore be interpreted as
317 // a two-digit octal.
318 if (j == 3 && value[i] > '3') {
319 j--;
320 }
321 const auto end{i + j};
322 uint8_t val{0};
323 while (i < end) {
324 val *= 8;
325 val += value[i++] - '0';
326 }
327 escaped_value.push_back(char(val));
328 // Account for automatic incrementing at loop end
329 --i;
330 } else {
331 escaped_value.push_back(value[i]);
332 }
333 } else {
334 escaped_value.push_back(value[i]);
335 }
336 }
337 value = escaped_value;
338 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
339 while (ptr < s.size() && s[ptr] != ' ') {
340 value.push_back(s[ptr]);
341 ++ptr;
342 }
343 }
344 if (ptr < s.size() && s[ptr] == ' ')
345 ++ptr; // skip ' ' after key=value
346 mapping[key] = value;
347 }
348 return mapping;
349}
350
351TorController::TorController(const std::string& tor_control_center, const CService& target)
352 : m_tor_control_center(tor_control_center),
353 m_conn(m_interrupt),
354 m_reconnect(true),
355 m_reconnect_timeout(RECONNECT_TIMEOUT_START),
356 m_target(target)
357{
358 // Read service private key if cached
359 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
360 if (pkf.first) {
361 LogDebug(BCLog::TOR, "Reading cached private key from %s", fs::PathToString(GetPrivateKeyFile()));
362 m_private_key = pkf.second;
363 }
364 m_thread = std::thread(&util::TraceThread, "torcontrol", [this] { ThreadControl(); });
365}
366
368{
369 Interrupt();
370 Join();
371 if (m_service.IsValid()) {
373 }
374}
375
377{
378 m_reconnect = false;
379 m_interrupt();
380}
381
383{
384 if (m_thread.joinable()) {
385 m_thread.join();
386 }
387}
388
390{
391 LogDebug(BCLog::TOR, "Entering Tor control thread");
392
393 while (!m_interrupt) {
394 LogDebug(BCLog::TOR, "Attempting to connect to Tor control port %s", m_tor_control_center);
397 while (!m_interrupt) {
398 if (!m_conn.WaitForData(std::chrono::seconds(1))) {
399 if (m_conn.IsConnected()) continue;
400 LogDebug(BCLog::TOR, "Lost connection to Tor control port");
401 break;
402 }
403 if (!m_conn.ReceiveAndProcess()) break;
404 }
405 } else {
406 LogWarning("tor: Initiating connection to Tor control port %s failed", m_tor_control_center);
407 }
409 }
410 LogDebug(BCLog::TOR, "Exited Tor control thread");
411}
412
414{
415 // NOTE: We can only get here if -onion is unset
416 std::string socks_location;
417 if (reply.code == TOR_REPLY_OK) {
418 for (const auto& line : reply.lines) {
419 if (line.starts_with("net/listeners/socks=")) {
420 const std::string port_list_str = line.substr(20);
421 std::vector<std::string> port_list = SplitString(port_list_str, ' ');
422
423 for (auto& portstr : port_list) {
424 if (portstr.empty()) continue;
425 if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
426 portstr = portstr.substr(1, portstr.size() - 2);
427 if (portstr.empty()) continue;
428 }
429 socks_location = portstr;
430 if (portstr.starts_with("127.0.0.1:")) {
431 // Prefer localhost - ignore other ports
432 break;
433 }
434 }
435 }
436 }
437 if (!socks_location.empty()) {
438 LogDebug(BCLog::TOR, "Get SOCKS port command yielded %s", socks_location);
439 } else {
440 LogWarning("tor: Get SOCKS port command returned nothing");
441 }
442 } else if (reply.code == TOR_REPLY_UNRECOGNIZED) {
443 LogWarning("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)");
444 } else {
445 LogWarning("tor: Get SOCKS port command failed; error code %d", reply.code);
446 }
447
448 CService resolved;
449 Assume(!resolved.IsValid());
450 if (!socks_location.empty()) {
451 resolved = LookupNumeric(socks_location, DEFAULT_TOR_SOCKS_PORT);
452 }
453 if (!resolved.IsValid()) {
454 // Fallback to old behaviour
455 resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT);
456 }
457
458 Assume(resolved.IsValid());
459 LogDebug(BCLog::TOR, "Configuring onion proxy for %s", resolved.ToStringAddrPort());
460
461 // Add Tor as proxy for .onion addresses.
462 // Enable stream isolation to prevent connection correlation and enhance privacy, by forcing a different Tor circuit for every connection.
463 // For this to work, the IsolateSOCKSAuth flag must be enabled on SOCKSPort (which is the default, see the IsolateSOCKSAuth section of Tor's manual page).
464 Proxy addrOnion = Proxy(resolved, /*tor_stream_isolation=*/ true);
465 SetProxy(NET_ONION, addrOnion);
466
467 const auto onlynets = gArgs.GetArgs("-onlynet");
468
469 const bool onion_allowed_by_onlynet{
470 onlynets.empty() ||
471 std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) {
472 return ParseNetwork(n) == NET_ONION;
473 })};
474
475 if (onion_allowed_by_onlynet) {
476 // If NET_ONION is reachable, then the below is a noop.
477 //
478 // If NET_ONION is not reachable, then none of -proxy or -onion was given.
479 // Since we are here, then -torcontrol and -torpassword were given.
481 }
482}
483
484static std::string MakeAddOnionCmd(const std::string& private_key, const std::string& target, bool enable_pow)
485{
486 // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
487 return strprintf("ADD_ONION %s%s Port=%i,%s",
489 enable_pow ? " PoWDefensesEnabled=1" : "",
490 Params().GetDefaultPort(),
491 target);
492}
493
494void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply, bool pow_was_enabled)
495{
496 if (reply.code == TOR_REPLY_OK) {
497 LogDebug(BCLog::TOR, "ADD_ONION successful (PoW defenses %s)", pow_was_enabled ? "enabled" : "disabled");
498 for (const std::string &s : reply.lines) {
499 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
500 std::map<std::string,std::string>::iterator i;
501 if ((i = m.find("ServiceID")) != m.end())
502 m_service_id = i->second;
503 if ((i = m.find("PrivateKey")) != m.end())
504 m_private_key = i->second;
505 }
506 if (m_service_id.empty()) {
507 LogWarning("tor: Error parsing ADD_ONION parameters:");
508 for (const std::string &s : reply.lines) {
509 LogWarning(" %s", SanitizeString(s));
510 }
511 return;
512 }
513 m_service = LookupNumeric(std::string(m_service_id+".onion"), Params().GetDefaultPort());
514 LogInfo("Got tor service ID %s, advertising service %s", m_service_id, m_service.ToStringAddrPort());
516 LogDebug(BCLog::TOR, "Cached service private key to %s", fs::PathToString(GetPrivateKeyFile()));
517 } else {
518 LogWarning("tor: Error writing service private key to %s", fs::PathToString(GetPrivateKeyFile()));
519 }
521 // ... onion requested - keep connection open
522 } else if (reply.code == TOR_REPLY_UNRECOGNIZED) {
523 LogWarning("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)");
524 } else if (pow_was_enabled && reply.code == TOR_REPLY_SYNTAX_ERROR) {
525 LogDebug(BCLog::TOR, "ADD_ONION failed with PoW defenses, retrying without");
526 _conn.Command(MakeAddOnionCmd(m_private_key, m_target.ToStringAddrPort(), /*enable_pow=*/false),
527 [this](TorControlConnection& conn, const TorControlReply& reply) {
528 add_onion_cb(conn, reply, /*pow_was_enabled=*/false);
529 });
530 } else {
531 LogWarning("tor: Add onion failed; error code %d", reply.code);
532 }
533}
534
536{
537 if (reply.code == TOR_REPLY_OK) {
538 LogDebug(BCLog::TOR, "Authentication successful");
539
540 // Now that we know Tor is running setup the proxy for onion addresses
541 // if -onion isn't set to something else.
542 if (gArgs.GetArg("-onion", "") == "") {
543 _conn.Command("GETINFO net/listeners/socks", std::bind_front(&TorController::get_socks_cb, this));
544 }
545
546 // Finally - now create the service
547 if (m_private_key.empty()) { // No private key, generate one
548 m_private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
549 }
550 // Request onion service, redirect port.
551 _conn.Command(MakeAddOnionCmd(m_private_key, m_target.ToStringAddrPort(), /*enable_pow=*/true),
552 [this](TorControlConnection& conn, const TorControlReply& reply) {
553 add_onion_cb(conn, reply, /*pow_was_enabled=*/true);
554 });
555 } else {
556 LogWarning("tor: Authentication failed");
557 }
558}
559
576static std::vector<uint8_t> ComputeResponse(std::string_view key, std::span<const uint8_t> cookie, std::span<const uint8_t> client_nonce, std::span<const uint8_t> server_nonce)
577{
578 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
579 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
580 computeHash.Write(cookie.data(), cookie.size());
581 computeHash.Write(client_nonce.data(), client_nonce.size());
582 computeHash.Write(server_nonce.data(), server_nonce.size());
583 computeHash.Finalize(computedHash.data());
584 return computedHash;
585}
586
588{
589 if (reply.code == TOR_REPLY_OK) {
590 LogDebug(BCLog::TOR, "SAFECOOKIE authentication challenge successful");
591 if (reply.lines.empty()) {
592 LogWarning("tor: AUTHCHALLENGE reply was empty");
593 return;
594 }
595 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
596 if (l.first == "AUTHCHALLENGE") {
597 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
598 if (m.empty()) {
599 LogWarning("tor: Error parsing AUTHCHALLENGE parameters: %s", SanitizeString(l.second));
600 return;
601 }
602 std::vector<uint8_t> server_hash = ParseHex(m["SERVERHASH"]);
603 std::vector<uint8_t> server_nonce = ParseHex(m["SERVERNONCE"]);
604 LogDebug(BCLog::TOR, "AUTHCHALLENGE ServerHash %s ServerNonce %s", HexStr(server_hash), HexStr(server_nonce));
605 if (server_nonce.size() != 32) {
606 LogWarning("tor: ServerNonce is not 32 bytes, as required by spec");
607 return;
608 }
609
610 std::vector<uint8_t> computed_server_hash = ComputeResponse(TOR_SAFE_SERVERKEY, m_cookie, m_client_nonce, server_nonce);
611 if (computed_server_hash != server_hash) {
612 LogWarning("tor: ServerHash %s does not match expected ServerHash %s", HexStr(server_hash), HexStr(computed_server_hash));
613 return;
614 }
615
616 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, m_cookie, m_client_nonce, server_nonce);
617 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind_front(&TorController::auth_cb, this));
618 } else {
619 LogWarning("tor: Invalid reply to AUTHCHALLENGE");
620 }
621 } else {
622 LogWarning("tor: SAFECOOKIE authentication challenge failed");
623 }
624}
625
627{
628 if (reply.code == TOR_REPLY_OK) {
629 std::set<std::string> methods;
630 std::string cookiefile;
631 /*
632 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
633 * 250-AUTH METHODS=NULL
634 * 250-AUTH METHODS=HASHEDPASSWORD
635 */
636 for (const std::string &s : reply.lines) {
637 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
638 if (l.first == "AUTH") {
639 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
640 std::map<std::string,std::string>::iterator i;
641 if ((i = m.find("METHODS")) != m.end()) {
642 std::vector<std::string> m_vec = SplitString(i->second, ',');
643 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
644 }
645 if ((i = m.find("COOKIEFILE")) != m.end())
646 cookiefile = i->second;
647 } else if (l.first == "VERSION") {
648 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
649 std::map<std::string,std::string>::iterator i;
650 if ((i = m.find("Tor")) != m.end()) {
651 LogDebug(BCLog::TOR, "Connected to Tor version %s", i->second);
652 }
653 }
654 }
655 for (const std::string &s : methods) {
656 LogDebug(BCLog::TOR, "Supported authentication method: %s", s);
657 }
658 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
659 /* Authentication:
660 * cookie: hex-encoded ~/.tor/control_auth_cookie
661 * password: "password"
662 */
663 std::string torpassword = gArgs.GetArg("-torpassword", "");
664 if (!torpassword.empty()) {
665 if (methods.contains("HASHEDPASSWORD")) {
666 LogDebug(BCLog::TOR, "Using HASHEDPASSWORD authentication");
667 ReplaceAll(torpassword, "\"", "\\\"");
668 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind_front(&TorController::auth_cb, this));
669 } else {
670 LogWarning("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available");
671 }
672 } else if (methods.contains("NULL")) {
673 LogDebug(BCLog::TOR, "Using NULL authentication");
674 _conn.Command("AUTHENTICATE", std::bind_front(&TorController::auth_cb, this));
675 } else if (methods.contains("SAFECOOKIE")) {
676 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
677 LogDebug(BCLog::TOR, "Using SAFECOOKIE authentication, reading cookie authentication from %s", cookiefile);
678 std::pair<bool,std::string> status_cookie = ReadBinaryFile(fs::PathFromString(cookiefile), TOR_COOKIE_SIZE);
679 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
680 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind_front(&TorController::auth_cb, this));
681 m_cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
682 m_client_nonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
684 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(m_client_nonce), std::bind_front(&TorController::authchallenge_cb, this));
685 } else {
686 if (status_cookie.first) {
687 LogWarning("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec", cookiefile, TOR_COOKIE_SIZE);
688 } else {
689 LogWarning("tor: Authentication cookie %s could not be opened (check permissions)", cookiefile);
690 }
691 }
692 } else if (methods.contains("HASHEDPASSWORD")) {
693 LogWarning("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword");
694 } else {
695 LogWarning("tor: No supported authentication method");
696 }
697 } else {
698 LogWarning("tor: Requesting protocol info failed");
699 }
700}
701
703{
705 // First send a PROTOCOLINFO command to figure out what authentication is expected
706 if (!_conn.Command("PROTOCOLINFO 1", std::bind_front(&TorController::protocolinfo_cb, this)))
707 LogWarning("tor: Error sending initial protocolinfo command");
708}
709
711{
712 // Stop advertising service when disconnected
713 if (m_service.IsValid())
716 if (!m_reconnect)
717 return;
718
719 LogDebug(BCLog::TOR, "Not connected to Tor control port %s, retrying in %.2f s",
721 _conn.Disconnect();
722
723 m_interrupt.sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(m_reconnect_timeout));
725}
726
728{
729 return gArgs.GetDataDirNet() / "onion_v3_private_key";
730}
731
733{
734 struct in_addr onion_service_target;
735 onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
736 return {onion_service_target, port};
737}
ArgsManager gArgs
Definition: args.cpp:38
const auto cmd
const auto command
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Definition: check.h:128
std::vector< std::string > GetArgs(const std::string &strArg) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return a vector of strings of the given argument.
Definition: args.cpp:422
std::string GetArg(const std::string &strArg, const std::string &strDefault) const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Return string argument or default value.
Definition: args.cpp:517
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition: args.cpp:328
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:23
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:34
static constexpr size_t OUTPUT_SIZE
Definition: hmac_sha256.h:20
bool IsValid() const
Definition: netaddress.cpp:430
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
std::string ToStringAddrPort() const
Definition: netaddress.cpp:909
A helper class for interruptible sleeps.
virtual bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
Sleep for the given duration.
Definition: netbase.h:61
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:106
static constexpr Event RecvEvent
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:151
uint8_t Event
Definition: sock.h:146
static constexpr Event ErrorEvent
Ignored if passed to Wait(), but could be set in the occurred events if an exceptional condition has ...
Definition: sock.h:162
Low-level handling for Tor control connection.
Definition: torcontrol.h:56
TorControlReply m_message
Message being received.
Definition: torcontrol.h:108
std::deque< ReplyHandlerCB > m_reply_handlers
Response handlers.
Definition: torcontrol.h:110
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:216
CThreadInterrupt & m_interrupt
Reference to interrupt object for clean shutdown.
Definition: torcontrol.h:104
bool WaitForData(std::chrono::milliseconds timeout)
Wait for data to be available on the socket.
Definition: torcontrol.cpp:131
std::string m_recv_buffer
Buffer for incoming data.
Definition: torcontrol.h:112
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.h:58
bool ProcessBuffer()
Process complete lines from the receive buffer.
Definition: torcontrol.cpp:179
bool ReceiveAndProcess()
Read available data from socket and process complete replies.
Definition: torcontrol.cpp:148
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:112
TorControlConnection(CThreadInterrupt &interrupt)
Create a new TorControlConnection.
Definition: torcontrol.cpp:76
bool Connect(const std::string &tor_control_center)
Connect to a Tor control port.
Definition: torcontrol.cpp:86
std::unique_ptr< Sock > m_sock
Socket for the connection.
Definition: torcontrol.h:106
bool IsConnected() const
Check if the connection is established.
Definition: torcontrol.cpp:120
Reply from Tor, can be single or multi-line.
Definition: torcontrol.h:38
std::vector< std::string > lines
Definition: torcontrol.h:43
CThreadInterrupt m_interrupt
Definition: torcontrol.h:140
std::thread m_thread
Definition: torcontrol.h:141
CService m_service
Definition: torcontrol.h:148
void ThreadControl()
Definition: torcontrol.cpp:389
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:727
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:702
void get_socks_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for GETINFO net/listeners/socks result.
Definition: torcontrol.cpp:413
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply, bool pow_was_enabled)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:494
const std::string m_tor_control_center
Definition: torcontrol.h:142
std::vector< uint8_t > m_client_nonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.h:153
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:710
const CService m_target
Definition: torcontrol.h:149
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:587
TorControlConnection m_conn
Definition: torcontrol.h:143
std::string m_service_id
Definition: torcontrol.h:145
std::atomic< bool > m_reconnect
Definition: torcontrol.h:146
void Interrupt()
Interrupt the controller thread.
Definition: torcontrol.cpp:376
std::string m_private_key
Definition: torcontrol.h:144
void Join()
Wait for the controller thread to exit.
Definition: torcontrol.cpp:382
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:535
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:626
std::chrono::duration< double > m_reconnect_timeout
Definition: torcontrol.h:147
std::vector< uint8_t > m_cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.h:151
size_t Consumed() const
Returns number of bytes already read from buffer.
Definition: string.cpp:85
std::optional< std::string_view > ReadLine() LIFETIMEBOUND
Returns a string from current iterator position up to (but not including) next and advances iterator...
Definition: string.cpp:35
#define WSAEWOULDBLOCK
Definition: compat.h:61
#define WSAGetLastError()
Definition: compat.h:59
#define MSG_DONTWAIT
Definition: compat.h:115
#define WSAEINPROGRESS
Definition: compat.h:65
#define WSAEINTR
Definition: compat.h:64
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:160
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:183
std::string HexStr(const std::span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: hex_base.cpp:30
util::LineReader reader
std::thread thread
Thread variable should be after other struct members so the thread does not start until the other mem...
#define LogWarning(...)
Definition: log.h:126
#define LogInfo(...)
Definition: log.h:125
#define LogDebug(category,...)
Definition: log.h:143
@ TOR
Definition: categories.h:17
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:153
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:15
void ReplaceAll(std::string &in_out, std::string_view search, std::string_view substitute)
Replace every non-overlapping occurrence of search with substitute, treating both literally; the repl...
Definition: string.cpp:14
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:250
void RemoveLocal(const CService &addr)
Definition: net.cpp:313
bool AddLocal(const CService &addr_, int nScore, bool add_even_if_unreachable)
Definition: net.cpp:278
@ LOCAL_MANUAL
Definition: net.h:160
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:44
std::unique_ptr< Sock > ConnectDirectly(const CService &dest, bool manual_connection)
Create a socket and try to connect to the specified service.
Definition: netbase.cpp:650
bool SetProxy(enum Network net, const Proxy &addrProxy)
Definition: netbase.cpp:717
std::vector< CService > Lookup(const std::string &name, uint16_t portDefault, bool fAllowLookup, unsigned int nMaxSolutions, DNSLookupFn dns_lookup_function)
Resolve a service string to its corresponding service.
Definition: netbase.cpp:191
ReachableNets g_reachable_nets
Definition: netbase.cpp:43
bool fNameLookup
Definition: netbase.cpp:37
CService LookupNumeric(const std::string &name, uint16_t portDefault, DNSLookupFn dns_lookup_function)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:216
void GetRandBytes(std::span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:601
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize)
Read full contents of a file and return them in a std::string.
std::string NetworkErrorString(int err)
Return readable error string for a network error code.
Definition: sock.cpp:426
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:69
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:54
constexpr std::chrono::duration< double > RECONNECT_TIMEOUT_MAX
Maximum reconnect timeout in seconds to prevent excessive delays.
Definition: torcontrol.cpp:60
constexpr int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:48
constexpr int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:50
constexpr std::chrono::duration< double > RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:56
static std::string MakeAddOnionCmd(const std::string &private_key, const std::string &target, bool enable_pow)
Definition: torcontrol.cpp:484
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
Definition: torcontrol.cpp:46
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:239
static const std::string TOR_SAFE_SERVERKEY
For computing server_hash in SAFECOOKIE.
Definition: torcontrol.cpp:52
static std::vector< uint8_t > ComputeResponse(std::string_view key, std::span< const uint8_t > cookie, std::span< const uint8_t > client_nonce, std::span< const uint8_t > server_nonce)
Compute Tor SAFECOOKIE response.
Definition: torcontrol.cpp:576
constexpr int MAX_LINE_COUNT
Maximum number of lines received on TorControlConnection per reply to avoid memory exhaustion.
Definition: torcontrol.cpp:70
constexpr double RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:58
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
Definition: torcontrol.cpp:258
CService DefaultOnionServiceTarget(uint16_t port)
Definition: torcontrol.cpp:732
constexpr auto SOCKET_SEND_TIMEOUT
Timeout for socket operations.
Definition: torcontrol.cpp:72
constexpr int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:65
constexpr int TOR_REPLY_SYNTAX_ERROR
Syntax error in command argument.
Definition: torcontrol.h:32
constexpr uint16_t DEFAULT_TOR_SOCKS_PORT
Functionality for communicating with Tor.
Definition: torcontrol.h:24
constexpr int TOR_REPLY_OK
Tor control reply code.
Definition: torcontrol.h:30
constexpr int TOR_REPLY_UNRECOGNIZED
Definition: torcontrol.h:31
constexpr int DEFAULT_TOR_CONTROL_PORT
Definition: torcontrol.h:25
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.