Bitcoin Core 32.99.0
P2P Digital Currency
Loading...
Searching...
No Matches
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;
73constexpr std::string_view PRIVATE_KEY_NEW{"NEW:ED25519-V3"};
74constexpr std::string_view PRIVATE_KEY_PREFIX{"ED25519-V3:"};
75
77static bool IsWellFormedPrivateKey(std::string_view key)
78{
79 if (key == PRIVATE_KEY_NEW) return true;
80 if (!key.starts_with(PRIVATE_KEY_PREFIX)) return false;
81 const auto decoded{DecodeBase64(key.substr(PRIVATE_KEY_PREFIX.size()))};
82 return decoded && decoded->size() == 64; // A 32-byte secret scalar followed by a 32-byte PRF secret
83}
84
85/****** Low-level TorControlConnection ********/
86
88 : m_interrupt(interrupt)
89{
90}
91
96
98{
99 if (m_sock) {
100 Disconnect();
101 }
102
104 if (!control_service.has_value()) {
105 LogWarning("tor: Failed to look up control center %s", tor_control_center);
106 return false;
107 }
108
109 m_sock = ConnectDirectly(control_service.value(), /*manual_connection=*/true);
110 if (!m_sock) {
111 LogWarning("tor: Error connecting to address %s", tor_control_center);
112 return false;
113 }
114
115 m_recv_buffer.clear();
117 m_reply_handlers.clear();
118
119 LogDebug(BCLog::TOR, "Successfully connected to Tor control port");
120 return true;
121}
122
124{
125 m_sock.reset();
126 m_recv_buffer.clear();
128 m_reply_handlers.clear();
129}
130
132{
133 if (!m_sock) return false;
134 std::string errmsg;
135 const bool connected{m_sock->IsConnected(errmsg)};
136 if (!connected && !errmsg.empty()) {
137 LogDebug(BCLog::TOR, "Connection check failed: %s", errmsg);
138 }
139 return connected;
140}
141
142bool TorControlConnection::WaitForData(std::chrono::milliseconds timeout)
143{
144 if (!m_sock) return false;
145
146 Sock::Event event{0};
147 if (!m_sock->Wait(timeout, Sock::RecvEvent, &event)) {
148 return false;
149 }
150 if (event & Sock::ErrorEvent) {
151 LogDebug(BCLog::TOR, "Socket error detected");
152 Disconnect();
153 return false;
154 }
155
156 return (event & Sock::RecvEvent);
157}
158
160{
161 if (!m_sock) return false;
162
163 char buf[4096];
164 ssize_t nread = m_sock->Recv(buf, sizeof(buf), MSG_DONTWAIT);
165
166 if (nread < 0) {
167 int err = WSAGetLastError();
168 if (err == WSAEWOULDBLOCK || err == WSAEINTR || err == WSAEINPROGRESS) {
169 // No data available currently
170 return true;
171 }
172 LogWarning("tor: Error reading from socket: %s", NetworkErrorString(err));
173 return false;
174 }
175
176 if (nread == 0) {
177 LogDebug(BCLog::TOR, "End of stream");
178 return false;
179 }
180
181 m_recv_buffer.insert(m_recv_buffer.end(), buf, buf + nread);
182 try {
183 return ProcessBuffer();
184 } catch (const std::runtime_error& e) {
185 LogWarning("tor: Error processing receive buffer: %s", e.what());
186 return false;
187 }
188}
189
191{
193
194 while (auto line = reader.ReadLine()) {
195 if (m_message.lines.size() == MAX_LINE_COUNT) {
196 throw std::runtime_error(strprintf("Control port reply exceeded %d lines, disconnecting", MAX_LINE_COUNT));
197 }
198 // Skip short lines
199 if (line->size() < 4) continue;
200
201 // Parse: <code><separator><data>
202 // <status>(-|+| )<data>
203 m_message.code = ToIntegral<int>(line->substr(0, 3)).value_or(0);
204 m_message.lines.emplace_back(line->substr(4));
205 char separator = (*line)[3]; // '-', '+', or ' '
206
207 if (separator == ' ') {
208 if (m_message.code >= 600) {
209 // Async notifications are currently unused
210 // Synchronous and asynchronous messages are never interleaved
211 LogDebug(BCLog::TOR, "Received async notification %i", m_message.code);
212 } else if (!m_reply_handlers.empty()) {
213 // Invoke reply handler with message
214 m_reply_handlers.front()(*this, m_message);
215 m_reply_handlers.pop_front();
216 } else {
217 LogDebug(BCLog::TOR, "Received unexpected sync reply %i", m_message.code);
218 }
220 }
221 }
222
223 m_recv_buffer.erase(m_recv_buffer.begin(), m_recv_buffer.begin() + reader.Consumed());
224 return true;
225}
226
228{
229 if (!m_sock) return false;
230
231 std::string command = cmd + "\r\n";
232 try {
233 m_sock->SendComplete(std::span<const char>{command}, SOCKET_SEND_TIMEOUT, m_interrupt);
234 } catch (const std::runtime_error& e) {
235 LogWarning("tor: Error sending command: %s", e.what());
236 return false;
237 }
238
240 return true;
241}
242
243/****** General parsing utilities ********/
244
245/* Split reply line in the form 'AUTH METHODS=...' into a type
246 * 'AUTH' and arguments 'METHODS=...'.
247 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
248 * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
249 */
250std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
251{
252 size_t ptr=0;
253 std::string type;
254 while (ptr < s.size() && s[ptr] != ' ') {
255 type.push_back(s[ptr]);
256 ++ptr;
257 }
258 if (ptr < s.size())
259 ++ptr; // skip ' '
260 return make_pair(type, s.substr(ptr));
261}
262
269std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
270{
271 std::map<std::string,std::string> mapping;
272 size_t ptr=0;
273 while (ptr < s.size()) {
274 std::string key, value;
275 while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
276 key.push_back(s[ptr]);
277 ++ptr;
278 }
279 if (ptr == s.size()) // unexpected end of line
280 return std::map<std::string,std::string>();
281 if (s[ptr] == ' ') // The remaining string is an OptArguments
282 break;
283 ++ptr; // skip '='
284 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
285 ++ptr; // skip opening '"'
286 bool escape_next = false;
287 while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
288 // Repeated backslashes must be interpreted as pairs
289 escape_next = (s[ptr] == '\\' && !escape_next);
290 value.push_back(s[ptr]);
291 ++ptr;
292 }
293 if (ptr == s.size()) // unexpected end of line
294 return std::map<std::string,std::string>();
295 ++ptr; // skip closing '"'
306 std::string escaped_value;
307 for (size_t i = 0; i < value.size(); ++i) {
308 if (value[i] == '\\') {
309 // This will always be valid, because if the QuotedString
310 // ended in an odd number of backslashes, then the parser
311 // would already have returned above, due to a missing
312 // terminating double-quote.
313 ++i;
314 if (value[i] == 'n') {
315 escaped_value.push_back('\n');
316 } else if (value[i] == 't') {
317 escaped_value.push_back('\t');
318 } else if (value[i] == 'r') {
319 escaped_value.push_back('\r');
320 } else if ('0' <= value[i] && value[i] <= '7') {
321 size_t j;
322 // Octal escape sequences have a limit of three octal digits,
323 // but terminate at the first character that is not a valid
324 // octal digit if encountered sooner.
325 for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
326 // Tor restricts first digit to 0-3 for three-digit octals.
327 // A leading digit of 4-7 would therefore be interpreted as
328 // a two-digit octal.
329 if (j == 3 && value[i] > '3') {
330 j--;
331 }
332 const auto end{i + j};
333 uint8_t val{0};
334 while (i < end) {
335 val *= 8;
336 val += value[i++] - '0';
337 }
338 escaped_value.push_back(char(val));
339 // Account for automatic incrementing at loop end
340 --i;
341 } else {
342 escaped_value.push_back(value[i]);
343 }
344 } else {
345 escaped_value.push_back(value[i]);
346 }
347 }
348 value = escaped_value;
349 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
350 while (ptr < s.size() && s[ptr] != ' ') {
351 value.push_back(s[ptr]);
352 ++ptr;
353 }
354 }
355 if (ptr < s.size() && s[ptr] == ' ')
356 ++ptr; // skip ' ' after key=value
357 mapping[key] = value;
358 }
359 return mapping;
360}
361
363 : m_tor_control_center(tor_control_center),
364 m_conn(m_interrupt),
365 m_reconnect(true),
366 m_reconnect_timeout(RECONNECT_TIMEOUT_START),
367 m_target(target)
368{
369 // Read service private key if cached
370 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
371 if (pkf.first) {
372 LogDebug(BCLog::TOR, "Reading cached private key from %s", fs::PathToString(GetPrivateKeyFile()));
373 m_private_key = pkf.second;
374 }
375 m_thread = std::thread(&util::TraceThread, "torcontrol", [this] { ThreadControl(); });
376}
377
379{
380 Interrupt();
381 Join();
382 if (m_service.IsValid()) {
384 }
385}
386
388{
389 m_reconnect = false;
390 m_interrupt();
391}
392
394{
395 if (m_thread.joinable()) {
396 m_thread.join();
397 }
398}
399
401{
402 LogDebug(BCLog::TOR, "Entering Tor control thread");
403
404 while (!m_interrupt) {
405 LogDebug(BCLog::TOR, "Attempting to connect to Tor control port %s", m_tor_control_center);
408 while (!m_interrupt) {
409 if (!m_conn.WaitForData(std::chrono::seconds(1))) {
410 if (m_conn.IsConnected()) continue;
411 LogDebug(BCLog::TOR, "Lost connection to Tor control port");
412 break;
413 }
414 if (!m_conn.ReceiveAndProcess()) break;
415 }
416 } else {
417 LogWarning("tor: Initiating connection to Tor control port %s failed", m_tor_control_center);
418 }
420 }
421 LogDebug(BCLog::TOR, "Exited Tor control thread");
422}
423
425{
426 // NOTE: We can only get here if -onion is unset
427 std::string socks_location;
428 if (reply.code == TOR_REPLY_OK) {
429 for (const auto& line : reply.lines) {
430 if (line.starts_with("net/listeners/socks=")) {
431 const std::string port_list_str = line.substr(20);
432 std::vector<std::string> port_list = SplitString(port_list_str, ' ');
433
434 for (auto& portstr : port_list) {
435 if (portstr.empty()) continue;
436 if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
437 portstr = portstr.substr(1, portstr.size() - 2);
438 if (portstr.empty()) continue;
439 }
441 if (portstr.starts_with("127.0.0.1:")) {
442 // Prefer localhost - ignore other ports
443 break;
444 }
445 }
446 }
447 }
448 if (!socks_location.empty()) {
449 LogDebug(BCLog::TOR, "Get SOCKS port command yielded %s", socks_location);
450 } else {
451 LogWarning("tor: Get SOCKS port command returned nothing");
452 }
453 } else if (reply.code == TOR_REPLY_UNRECOGNIZED) {
454 LogWarning("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)");
455 } else {
456 LogWarning("tor: Get SOCKS port command failed; error code %d", reply.code);
457 }
458
459 CService resolved;
460 Assume(!resolved.IsValid());
461 if (!socks_location.empty()) {
463 }
464 if (!resolved.IsValid()) {
465 // Fallback to old behaviour
466 resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT);
467 }
468
469 Assume(resolved.IsValid());
470 LogDebug(BCLog::TOR, "Configuring onion proxy for %s", resolved.ToStringAddrPort());
471
472 // Add Tor as proxy for .onion addresses.
473 // Enable stream isolation to prevent connection correlation and enhance privacy, by forcing a different Tor circuit for every connection.
474 // 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).
475 Proxy addrOnion = Proxy(resolved, /*tor_stream_isolation=*/ true);
477
478 const auto onlynets = gArgs.GetArgs("-onlynet");
479
480 const bool onion_allowed_by_onlynet{
481 onlynets.empty() ||
482 std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) {
483 return ParseNetwork(n) == NET_ONION;
484 })};
485
487 // If NET_ONION is reachable, then the below is a noop.
488 //
489 // If NET_ONION is not reachable, then none of -proxy or -onion was given.
490 // Since we are here, then -torcontrol and -torpassword were given.
492 }
493}
494
495static std::string MakeAddOnionCmd(const std::string& private_key, const std::string& target, bool enable_pow)
496{
497 // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
498 return strprintf("ADD_ONION %s%s Port=%i,%s",
499 private_key,
500 enable_pow ? " PoWDefensesEnabled=1" : "",
502 target);
503}
504
506{
507 if (reply.code == TOR_REPLY_OK) {
508 LogDebug(BCLog::TOR, "ADD_ONION successful (PoW defenses %s)", pow_was_enabled ? "enabled" : "disabled");
509 std::string service_id;
510 std::string private_key;
511 for (const std::string &s : reply.lines) {
512 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
513 std::map<std::string,std::string>::iterator i;
514 if ((i = m.find("ServiceID")) != m.end())
515 service_id = i->second;
516 if ((i = m.find("PrivateKey")) != m.end()) {
517 if (!IsWellFormedPrivateKey(i->second)) { // Never adopt or cache such a key
518 LogWarning("tor: ADD_ONION returned a malformed private key");
519 return;
520 }
521 private_key = i->second;
522 }
523 }
524 if (service_id.empty()) {
525 LogWarning("tor: Error parsing ADD_ONION parameters:");
526 for (const std::string &s : reply.lines) {
527 LogWarning(" %s", SanitizeString(s));
528 }
529 return;
530 }
531 const auto service{LookupNumeric(service_id + ".onion", Params().GetDefaultPort())};
532 if (!service.IsTor()) {
533 LogWarning("tor: ADD_ONION returned an invalid service ID");
534 return;
535 }
536 if (!private_key.empty()) m_private_key = std::move(private_key);
538 LogInfo("Got tor service ID %s, advertising service %s", service_id, m_service.ToStringAddrPort());
540 LogDebug(BCLog::TOR, "Cached service private key to %s", fs::PathToString(GetPrivateKeyFile()));
541 } else {
542 LogWarning("tor: Error writing service private key to %s", fs::PathToString(GetPrivateKeyFile()));
543 }
545 // ... onion requested - keep connection open
546 } else if (reply.code == TOR_REPLY_UNRECOGNIZED) {
547 LogWarning("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)");
548 } else if (pow_was_enabled && reply.code == TOR_REPLY_SYNTAX_ERROR) {
549 LogDebug(BCLog::TOR, "ADD_ONION failed with PoW defenses, retrying without");
550 _conn.Command(MakeAddOnionCmd(m_private_key, m_target.ToStringAddrPort(), /*enable_pow=*/false),
551 [this](TorControlConnection& conn, const TorControlReply& reply) {
552 add_onion_cb(conn, reply, /*pow_was_enabled=*/false);
553 });
554 } else {
555 LogWarning("tor: Add onion failed; error code %d", reply.code);
556 }
557}
558
560{
561 if (reply.code == TOR_REPLY_OK) {
562 LogDebug(BCLog::TOR, "Authentication successful");
563
564 // Now that we know Tor is running setup the proxy for onion addresses
565 // if -onion isn't set to something else.
566 if (gArgs.GetArg("-onion", "") == "") {
567 _conn.Command("GETINFO net/listeners/socks", std::bind_front(&TorController::get_socks_cb, this));
568 }
569
570 // Finally - now create the service
571 if (m_private_key.empty()) { // No private key, generate one
572 m_private_key = PRIVATE_KEY_NEW; // Explicitly request key type - see issue #9214
574 // add_onion_cb() never adopts such a key, so it can only come from the cache file
575 LogWarning("tor: Refusing to use cached private key %s because it is malformed; remove the file to generate a new key", fs::PathToString(GetPrivateKeyFile()));
576 return;
577 }
578 // Request onion service, redirect port.
579 _conn.Command(MakeAddOnionCmd(m_private_key, m_target.ToStringAddrPort(), /*enable_pow=*/true),
580 [this](TorControlConnection& conn, const TorControlReply& reply) {
581 add_onion_cb(conn, reply, /*pow_was_enabled=*/true);
582 });
583 } else {
584 LogWarning("tor: Authentication failed");
585 }
586}
587
604static 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)
605{
606 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
607 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
608 computeHash.Write(cookie.data(), cookie.size());
609 computeHash.Write(client_nonce.data(), client_nonce.size());
610 computeHash.Write(server_nonce.data(), server_nonce.size());
611 computeHash.Finalize(computedHash.data());
612 return computedHash;
613}
614
616{
617 if (reply.code == TOR_REPLY_OK) {
618 LogDebug(BCLog::TOR, "SAFECOOKIE authentication challenge successful");
619 if (reply.lines.empty()) {
620 LogWarning("tor: AUTHCHALLENGE reply was empty");
621 return;
622 }
623 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
624 if (l.first == "AUTHCHALLENGE") {
625 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
626 if (m.empty()) {
627 LogWarning("tor: Error parsing AUTHCHALLENGE parameters: %s", SanitizeString(l.second));
628 return;
629 }
630 std::vector<uint8_t> server_hash = ParseHex(m["SERVERHASH"]);
631 std::vector<uint8_t> server_nonce = ParseHex(m["SERVERNONCE"]);
632 LogDebug(BCLog::TOR, "AUTHCHALLENGE ServerHash %s ServerNonce %s", HexStr(server_hash), HexStr(server_nonce));
633 if (server_nonce.size() != 32) {
634 LogWarning("tor: ServerNonce is not 32 bytes, as required by spec");
635 return;
636 }
637
640 LogWarning("tor: ServerHash %s does not match expected ServerHash %s", HexStr(server_hash), HexStr(computed_server_hash));
641 return;
642 }
643
645 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind_front(&TorController::auth_cb, this));
646 } else {
647 LogWarning("tor: Invalid reply to AUTHCHALLENGE");
648 }
649 } else {
650 LogWarning("tor: SAFECOOKIE authentication challenge failed");
651 }
652}
653
655{
656 if (reply.code == TOR_REPLY_OK) {
657 std::set<std::string> methods;
658 std::string cookiefile;
659 /*
660 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
661 * 250-AUTH METHODS=NULL
662 * 250-AUTH METHODS=HASHEDPASSWORD
663 */
664 for (const std::string &s : reply.lines) {
665 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
666 if (l.first == "AUTH") {
667 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
668 std::map<std::string,std::string>::iterator i;
669 if ((i = m.find("METHODS")) != m.end()) {
670 std::vector<std::string> m_vec = SplitString(i->second, ',');
671 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
672 }
673 if ((i = m.find("COOKIEFILE")) != m.end())
674 cookiefile = i->second;
675 } else if (l.first == "VERSION") {
676 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
677 std::map<std::string,std::string>::iterator i;
678 if ((i = m.find("Tor")) != m.end()) {
679 LogDebug(BCLog::TOR, "Connected to Tor version %s", i->second);
680 }
681 }
682 }
683 for (const std::string &s : methods) {
684 LogDebug(BCLog::TOR, "Supported authentication method: %s", s);
685 }
686 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
687 /* Authentication:
688 * cookie: hex-encoded ~/.tor/control_auth_cookie
689 * password: "password"
690 */
691 std::string torpassword = gArgs.GetArg("-torpassword", "");
692 if (!torpassword.empty()) {
693 if (methods.contains("HASHEDPASSWORD")) {
694 LogDebug(BCLog::TOR, "Using HASHEDPASSWORD authentication");
695 ReplaceAll(torpassword, "\"", "\\\"");
696 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind_front(&TorController::auth_cb, this));
697 } else {
698 LogWarning("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available");
699 }
700 } else if (methods.contains("NULL")) {
701 LogDebug(BCLog::TOR, "Using NULL authentication");
702 _conn.Command("AUTHENTICATE", std::bind_front(&TorController::auth_cb, this));
703 } else if (methods.contains("SAFECOOKIE")) {
704 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
705 LogDebug(BCLog::TOR, "Using SAFECOOKIE authentication, reading cookie authentication from %s", cookiefile);
707 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
708 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind_front(&TorController::auth_cb, this));
709 m_cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
710 m_client_nonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
712 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(m_client_nonce), std::bind_front(&TorController::authchallenge_cb, this));
713 } else {
714 if (status_cookie.first) {
715 LogWarning("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec", cookiefile, TOR_COOKIE_SIZE);
716 } else {
717 LogWarning("tor: Authentication cookie %s could not be opened (check permissions)", cookiefile);
718 }
719 }
720 } else if (methods.contains("HASHEDPASSWORD")) {
721 LogWarning("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword");
722 } else {
723 LogWarning("tor: No supported authentication method");
724 }
725 } else {
726 LogWarning("tor: Requesting protocol info failed");
727 }
728}
729
731{
733 // First send a PROTOCOLINFO command to figure out what authentication is expected
734 if (!_conn.Command("PROTOCOLINFO 1", std::bind_front(&TorController::protocolinfo_cb, this)))
735 LogWarning("tor: Error sending initial protocolinfo command");
736}
737
739{
740 // Stop advertising service when disconnected
741 if (m_service.IsValid())
744 if (!m_reconnect)
745 return;
746
747 LogDebug(BCLog::TOR, "Not connected to Tor control port %s, retrying in %.2f s",
749 _conn.Disconnect();
750
751 m_interrupt.sleep_for(std::chrono::duration_cast<std::chrono::milliseconds>(m_reconnect_timeout));
753}
754
756{
757 return gArgs.GetDataDirNet() / "onion_v3_private_key";
758}
759
ArgsManager gArgs
Definition args.cpp:39
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:131
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:423
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:518
fs::path GetDataDirNet() const EXCLUSIVE_LOCKS_REQUIRED(!cs_args)
Get data directory path with appended network identifier.
Definition args.cpp:329
uint16_t GetDefaultPort() const
Definition chainparams.h:91
A hasher class for HMAC-SHA-256.
Definition hmac_sha256.h:14
static constexpr size_t OUTPUT_SIZE
Definition hmac_sha256.h:20
bool IsValid() const
A combination of a network address (CNetAddr) and a (TCP) port.
Definition netaddress.h:531
std::string ToStringAddrPort() const
A helper class for interruptible sleeps.
virtual bool sleep_for(Clock::duration rel_time) EXCLUSIVE_LOCKS_REQUIRED(!mut)
Sleep for the given duration.
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition netbase.h:100
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.
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.
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.
bool ReceiveAndProcess()
Read available data from socket and process complete replies.
void Disconnect()
Disconnect from Tor control port.
TorControlConnection(CThreadInterrupt &interrupt)
Create a new TorControlConnection.
bool Connect(const std::string &tor_control_center)
Connect to a Tor control port.
std::unique_ptr< Sock > m_sock
Socket for the connection.
Definition torcontrol.h:106
bool IsConnected() const
Check if the connection is established.
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:147
void ThreadControl()
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
void get_socks_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for GETINFO net/listeners/socks result.
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply, bool pow_was_enabled)
Callback for ADD_ONION result.
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:152
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
const CService m_target
Definition torcontrol.h:148
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
TorControlConnection m_conn
Definition torcontrol.h:143
std::atomic< bool > m_reconnect
Definition torcontrol.h:145
void Interrupt()
Interrupt the controller thread.
std::string m_private_key
Definition torcontrol.h:144
void Join()
Wait for the controller thread to exit.
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
std::chrono::duration< double > m_reconnect_timeout
Definition torcontrol.h:146
std::vector< uint8_t > m_cookie
Cookie for SAFECOOKIE auth.
Definition torcontrol.h:150
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
#define LogWarning(...)
Definition log.h:137
#define LogInfo(...)
Definition log.h:136
#define LogDebug(category,...)
Definition log.h:154
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:330
bool AddLocal(const CService &addr_, int nScore, bool add_even_if_unreachable)
Definition net.cpp:295
@ LOCAL_MANUAL
Definition net.h:164
@ 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:430
Utilities for converting data from/to strings.
std::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
constexpr std::chrono::duration< double > RECONNECT_TIMEOUT_MAX
Maximum reconnect timeout in seconds to prevent excessive delays.
constexpr int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
constexpr int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
constexpr std::chrono::duration< double > RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
static std::string MakeAddOnionCmd(const std::string &private_key, const std::string &target, bool enable_pow)
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
static const std::string TOR_SAFE_SERVERKEY
For computing server_hash in SAFECOOKIE.
static bool IsWellFormedPrivateKey(std::string_view key)
Whether the value requests a new Ed25519 v3 key or has the expected key format.
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.
constexpr int MAX_LINE_COUNT
Maximum number of lines received on TorControlConnection per reply to avoid memory exhaustion.
constexpr double RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
CService DefaultOnionServiceTarget(uint16_t port)
constexpr std::string_view PRIVATE_KEY_NEW
constexpr std::string_view PRIVATE_KEY_PREFIX
constexpr auto SOCKET_SEND_TIMEOUT
Timeout for socket operations.
constexpr int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Functionality for communicating with Tor.
constexpr int TOR_REPLY_SYNTAX_ERROR
Syntax error in command argument.
Definition torcontrol.h:32
constexpr uint16_t DEFAULT_TOR_SOCKS_PORT
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::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
std::map< std::string, std::string > ParseTorReplyMapping(const std::string &s)
Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
constexpr auto Ticks(Dur2 d)
Helper to count the seconds of a duration/time_point.
Definition time.h:82