Bitcoin Core 29.99.0
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1// Copyright (c) 2015-2022 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 <logging.h>
14#include <net.h>
15#include <netaddress.h>
16#include <netbase.h>
17#include <random.h>
18#include <tinyformat.h>
19#include <util/check.h>
20#include <util/fs.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 <cstdint>
30#include <cstdlib>
31#include <deque>
32#include <functional>
33#include <map>
34#include <optional>
35#include <set>
36#include <thread>
37#include <utility>
38#include <vector>
39
40#include <event2/buffer.h>
41#include <event2/bufferevent.h>
42#include <event2/event.h>
43#include <event2/thread.h>
44#include <event2/util.h>
45
48using util::ToString;
49
51const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:" + ToString(DEFAULT_TOR_CONTROL_PORT);
53static const int TOR_COOKIE_SIZE = 32;
55static const int TOR_NONCE_SIZE = 32;
57static const int TOR_REPLY_OK = 250;
58static const int TOR_REPLY_UNRECOGNIZED = 510;
60static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
62static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
64static const float RECONNECT_TIMEOUT_START = 1.0;
66static const float RECONNECT_TIMEOUT_EXP = 1.5;
68static const float RECONNECT_TIMEOUT_MAX = 600.0;
73static const int MAX_LINE_LENGTH = 100000;
74static const uint16_t DEFAULT_TOR_SOCKS_PORT = 9050;
75
76/****** Low-level TorControlConnection ********/
77
79 : base(_base)
80{
81}
82
84{
85 if (b_conn)
86 bufferevent_free(b_conn);
87}
88
89void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
90{
91 TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
92 struct evbuffer *input = bufferevent_get_input(bev);
93 size_t n_read_out = 0;
94 char *line;
95 assert(input);
96 // If there is not a whole line to read, evbuffer_readln returns nullptr
97 while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
98 {
99 std::string s(line, n_read_out);
100 free(line);
101 if (s.size() < 4) // Short line
102 continue;
103 // <status>(-|+| )<data><CRLF>
104 self->message.code = ToIntegral<int>(s.substr(0, 3)).value_or(0);
105 self->message.lines.push_back(s.substr(4));
106 char ch = s[3]; // '-','+' or ' '
107 if (ch == ' ') {
108 // Final line, dispatch reply and clean up
109 if (self->message.code >= 600) {
110 // (currently unused)
111 // Dispatch async notifications to async handler
112 // Synchronous and asynchronous messages are never interleaved
113 } else {
114 if (!self->reply_handlers.empty()) {
115 // Invoke reply handler with message
116 self->reply_handlers.front()(*self, self->message);
117 self->reply_handlers.pop_front();
118 } else {
119 LogDebug(BCLog::TOR, "Received unexpected sync reply %i\n", self->message.code);
120 }
121 }
122 self->message.Clear();
123 }
124 }
125 // Check for size of buffer - protect against memory exhaustion with very long lines
126 // Do this after evbuffer_readln to make sure all full lines have been
127 // removed from the buffer. Everything left is an incomplete line.
128 if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
129 LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
130 self->Disconnect();
131 }
132}
133
134void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
135{
136 TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
137 if (what & BEV_EVENT_CONNECTED) {
138 LogDebug(BCLog::TOR, "Successfully connected!\n");
139 self->connected(*self);
140 } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
141 if (what & BEV_EVENT_ERROR) {
142 LogDebug(BCLog::TOR, "Error connecting to Tor control socket\n");
143 } else {
144 LogDebug(BCLog::TOR, "End of stream\n");
145 }
146 self->Disconnect();
147 self->disconnected(*self);
148 }
149}
150
151bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
152{
153 if (b_conn) {
154 Disconnect();
155 }
156
157 const std::optional<CService> control_service{Lookup(tor_control_center, DEFAULT_TOR_CONTROL_PORT, fNameLookup)};
158 if (!control_service.has_value()) {
159 LogPrintf("tor: Failed to look up control center %s\n", tor_control_center);
160 return false;
161 }
162
163 struct sockaddr_storage control_address;
164 socklen_t control_address_len = sizeof(control_address);
165 if (!control_service.value().GetSockAddr(reinterpret_cast<struct sockaddr*>(&control_address), &control_address_len)) {
166 LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
167 return false;
168 }
169
170 // Create a new socket, set up callbacks and enable notification bits
171 b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
172 if (!b_conn) {
173 return false;
174 }
175 bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
176 bufferevent_enable(b_conn, EV_READ|EV_WRITE);
177 this->connected = _connected;
178 this->disconnected = _disconnected;
179
180 // Finally, connect to tor_control_center
181 if (bufferevent_socket_connect(b_conn, reinterpret_cast<struct sockaddr*>(&control_address), control_address_len) < 0) {
182 LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
183 return false;
184 }
185 return true;
186}
187
189{
190 if (b_conn)
191 bufferevent_free(b_conn);
192 b_conn = nullptr;
193}
194
195bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
196{
197 if (!b_conn)
198 return false;
199 struct evbuffer *buf = bufferevent_get_output(b_conn);
200 if (!buf)
201 return false;
202 evbuffer_add(buf, cmd.data(), cmd.size());
203 evbuffer_add(buf, "\r\n", 2);
204 reply_handlers.push_back(reply_handler);
205 return true;
206}
207
208/****** General parsing utilities ********/
209
210/* Split reply line in the form 'AUTH METHODS=...' into a type
211 * 'AUTH' and arguments 'METHODS=...'.
212 * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
213 * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
214 */
215std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
216{
217 size_t ptr=0;
218 std::string type;
219 while (ptr < s.size() && s[ptr] != ' ') {
220 type.push_back(s[ptr]);
221 ++ptr;
222 }
223 if (ptr < s.size())
224 ++ptr; // skip ' '
225 return make_pair(type, s.substr(ptr));
226}
227
234std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
235{
236 std::map<std::string,std::string> mapping;
237 size_t ptr=0;
238 while (ptr < s.size()) {
239 std::string key, value;
240 while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
241 key.push_back(s[ptr]);
242 ++ptr;
243 }
244 if (ptr == s.size()) // unexpected end of line
245 return std::map<std::string,std::string>();
246 if (s[ptr] == ' ') // The remaining string is an OptArguments
247 break;
248 ++ptr; // skip '='
249 if (ptr < s.size() && s[ptr] == '"') { // Quoted string
250 ++ptr; // skip opening '"'
251 bool escape_next = false;
252 while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
253 // Repeated backslashes must be interpreted as pairs
254 escape_next = (s[ptr] == '\\' && !escape_next);
255 value.push_back(s[ptr]);
256 ++ptr;
257 }
258 if (ptr == s.size()) // unexpected end of line
259 return std::map<std::string,std::string>();
260 ++ptr; // skip closing '"'
271 std::string escaped_value;
272 for (size_t i = 0; i < value.size(); ++i) {
273 if (value[i] == '\\') {
274 // This will always be valid, because if the QuotedString
275 // ended in an odd number of backslashes, then the parser
276 // would already have returned above, due to a missing
277 // terminating double-quote.
278 ++i;
279 if (value[i] == 'n') {
280 escaped_value.push_back('\n');
281 } else if (value[i] == 't') {
282 escaped_value.push_back('\t');
283 } else if (value[i] == 'r') {
284 escaped_value.push_back('\r');
285 } else if ('0' <= value[i] && value[i] <= '7') {
286 size_t j;
287 // Octal escape sequences have a limit of three octal digits,
288 // but terminate at the first character that is not a valid
289 // octal digit if encountered sooner.
290 for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
291 // Tor restricts first digit to 0-3 for three-digit octals.
292 // A leading digit of 4-7 would therefore be interpreted as
293 // a two-digit octal.
294 if (j == 3 && value[i] > '3') {
295 j--;
296 }
297 const auto end{i + j};
298 uint8_t val{0};
299 while (i < end) {
300 val *= 8;
301 val += value[i++] - '0';
302 }
303 escaped_value.push_back(char(val));
304 // Account for automatic incrementing at loop end
305 --i;
306 } else {
307 escaped_value.push_back(value[i]);
308 }
309 } else {
310 escaped_value.push_back(value[i]);
311 }
312 }
313 value = escaped_value;
314 } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
315 while (ptr < s.size() && s[ptr] != ' ') {
316 value.push_back(s[ptr]);
317 ++ptr;
318 }
319 }
320 if (ptr < s.size() && s[ptr] == ' ')
321 ++ptr; // skip ' ' after key=value
322 mapping[key] = value;
323 }
324 return mapping;
325}
326
327TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
328 base(_base),
329 m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_timeout(RECONNECT_TIMEOUT_START),
330 m_target(target)
331{
332 reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
333 if (!reconnect_ev)
334 LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
335 // Start connection attempts immediately
336 if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
337 std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
338 LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
339 }
340 // Read service private key if cached
341 std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
342 if (pkf.first) {
343 LogDebug(BCLog::TOR, "Reading cached private key from %s\n", fs::PathToString(GetPrivateKeyFile()));
344 private_key = pkf.second;
345 }
346}
347
349{
350 if (reconnect_ev) {
351 event_free(reconnect_ev);
352 reconnect_ev = nullptr;
353 }
354 if (service.IsValid()) {
356 }
357}
358
360{
361 // NOTE: We can only get here if -onion is unset
362 std::string socks_location;
363 if (reply.code == TOR_REPLY_OK) {
364 for (const auto& line : reply.lines) {
365 if (line.starts_with("net/listeners/socks=")) {
366 const std::string port_list_str = line.substr(20);
367 std::vector<std::string> port_list = SplitString(port_list_str, ' ');
368
369 for (auto& portstr : port_list) {
370 if (portstr.empty()) continue;
371 if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
372 portstr = portstr.substr(1, portstr.size() - 2);
373 if (portstr.empty()) continue;
374 }
375 socks_location = portstr;
376 if (portstr.starts_with("127.0.0.1:")) {
377 // Prefer localhost - ignore other ports
378 break;
379 }
380 }
381 }
382 }
383 if (!socks_location.empty()) {
384 LogDebug(BCLog::TOR, "Get SOCKS port command yielded %s\n", socks_location);
385 } else {
386 LogPrintf("tor: Get SOCKS port command returned nothing\n");
387 }
388 } else if (reply.code == TOR_REPLY_UNRECOGNIZED) {
389 LogPrintf("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)\n");
390 } else {
391 LogPrintf("tor: Get SOCKS port command failed; error code %d\n", reply.code);
392 }
393
394 CService resolved;
395 Assume(!resolved.IsValid());
396 if (!socks_location.empty()) {
397 resolved = LookupNumeric(socks_location, DEFAULT_TOR_SOCKS_PORT);
398 }
399 if (!resolved.IsValid()) {
400 // Fallback to old behaviour
401 resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT);
402 }
403
404 Assume(resolved.IsValid());
405 LogDebug(BCLog::TOR, "Configuring onion proxy for %s\n", resolved.ToStringAddrPort());
406
407 // With m_randomize_credentials = true, generates unique SOCKS credentials per proxy connection (e.g., Tor).
408 // Prevents connection correlation and enhances privacy by forcing different Tor circuits.
409 // Requires Tor's IsolateSOCKSAuth (default enabled) for effective isolation (see IsolateSOCKSAuth section in https://2019.www.torproject.org/docs/tor-manual.html.en).
410 Proxy addrOnion = Proxy(resolved, /*tor_stream_isolation=*/ true);
411 SetProxy(NET_ONION, addrOnion);
412
413 const auto onlynets = gArgs.GetArgs("-onlynet");
414
415 const bool onion_allowed_by_onlynet{
416 onlynets.empty() ||
417 std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) {
418 return ParseNetwork(n) == NET_ONION;
419 })};
420
421 if (onion_allowed_by_onlynet) {
422 // If NET_ONION is reachable, then the below is a noop.
423 //
424 // If NET_ONION is not reachable, then none of -proxy or -onion was given.
425 // Since we are here, then -torcontrol and -torpassword were given.
427 }
428}
429
431{
432 if (reply.code == TOR_REPLY_OK) {
433 LogDebug(BCLog::TOR, "ADD_ONION successful\n");
434 for (const std::string &s : reply.lines) {
435 std::map<std::string,std::string> m = ParseTorReplyMapping(s);
436 std::map<std::string,std::string>::iterator i;
437 if ((i = m.find("ServiceID")) != m.end())
438 service_id = i->second;
439 if ((i = m.find("PrivateKey")) != m.end())
440 private_key = i->second;
441 }
442 if (service_id.empty()) {
443 LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
444 for (const std::string &s : reply.lines) {
445 LogPrintf(" %s\n", SanitizeString(s));
446 }
447 return;
448 }
449 service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
450 LogInfo("Got tor service ID %s, advertising service %s\n", service_id, service.ToStringAddrPort());
452 LogDebug(BCLog::TOR, "Cached service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
453 } else {
454 LogPrintf("tor: Error writing service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
455 }
457 // ... onion requested - keep connection open
458 } else if (reply.code == TOR_REPLY_UNRECOGNIZED) {
459 LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
460 } else {
461 LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
462 }
463}
464
466{
467 if (reply.code == TOR_REPLY_OK) {
468 LogDebug(BCLog::TOR, "Authentication successful\n");
469
470 // Now that we know Tor is running setup the proxy for onion addresses
471 // if -onion isn't set to something else.
472 if (gArgs.GetArg("-onion", "") == "") {
473 _conn.Command("GETINFO net/listeners/socks", std::bind(&TorController::get_socks_cb, this, std::placeholders::_1, std::placeholders::_2));
474 }
475
476 // Finally - now create the service
477 if (private_key.empty()) { // No private key, generate one
478 private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
479 }
480 // Request onion service, redirect port.
481 // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
482 _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringAddrPort()),
483 std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
484 } else {
485 LogPrintf("tor: Authentication failed\n");
486 }
487}
488
505static std::vector<uint8_t> ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie, const std::vector<uint8_t> &clientNonce, const std::vector<uint8_t> &serverNonce)
506{
507 CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
508 std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
509 computeHash.Write(cookie.data(), cookie.size());
510 computeHash.Write(clientNonce.data(), clientNonce.size());
511 computeHash.Write(serverNonce.data(), serverNonce.size());
512 computeHash.Finalize(computedHash.data());
513 return computedHash;
514}
515
517{
518 if (reply.code == TOR_REPLY_OK) {
519 LogDebug(BCLog::TOR, "SAFECOOKIE authentication challenge successful\n");
520 std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
521 if (l.first == "AUTHCHALLENGE") {
522 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
523 if (m.empty()) {
524 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
525 return;
526 }
527 std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
528 std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
529 LogDebug(BCLog::TOR, "AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
530 if (serverNonce.size() != 32) {
531 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
532 return;
533 }
534
535 std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
536 if (computedServerHash != serverHash) {
537 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
538 return;
539 }
540
541 std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
542 _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
543 } else {
544 LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
545 }
546 } else {
547 LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
548 }
549}
550
552{
553 if (reply.code == TOR_REPLY_OK) {
554 std::set<std::string> methods;
555 std::string cookiefile;
556 /*
557 * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
558 * 250-AUTH METHODS=NULL
559 * 250-AUTH METHODS=HASHEDPASSWORD
560 */
561 for (const std::string &s : reply.lines) {
562 std::pair<std::string,std::string> l = SplitTorReplyLine(s);
563 if (l.first == "AUTH") {
564 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
565 std::map<std::string,std::string>::iterator i;
566 if ((i = m.find("METHODS")) != m.end()) {
567 std::vector<std::string> m_vec = SplitString(i->second, ',');
568 methods = std::set<std::string>(m_vec.begin(), m_vec.end());
569 }
570 if ((i = m.find("COOKIEFILE")) != m.end())
571 cookiefile = i->second;
572 } else if (l.first == "VERSION") {
573 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
574 std::map<std::string,std::string>::iterator i;
575 if ((i = m.find("Tor")) != m.end()) {
576 LogDebug(BCLog::TOR, "Connected to Tor version %s\n", i->second);
577 }
578 }
579 }
580 for (const std::string &s : methods) {
581 LogDebug(BCLog::TOR, "Supported authentication method: %s\n", s);
582 }
583 // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
584 /* Authentication:
585 * cookie: hex-encoded ~/.tor/control_auth_cookie
586 * password: "password"
587 */
588 std::string torpassword = gArgs.GetArg("-torpassword", "");
589 if (!torpassword.empty()) {
590 if (methods.count("HASHEDPASSWORD")) {
591 LogDebug(BCLog::TOR, "Using HASHEDPASSWORD authentication\n");
592 ReplaceAll(torpassword, "\"", "\\\"");
593 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
594 } else {
595 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
596 }
597 } else if (methods.count("NULL")) {
598 LogDebug(BCLog::TOR, "Using NULL authentication\n");
599 _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
600 } else if (methods.count("SAFECOOKIE")) {
601 // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
602 LogDebug(BCLog::TOR, "Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
603 std::pair<bool,std::string> status_cookie = ReadBinaryFile(fs::PathFromString(cookiefile), TOR_COOKIE_SIZE);
604 if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
605 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
606 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
607 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
609 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
610 } else {
611 if (status_cookie.first) {
612 LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
613 } else {
614 LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
615 }
616 }
617 } else if (methods.count("HASHEDPASSWORD")) {
618 LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
619 } else {
620 LogPrintf("tor: No supported authentication method\n");
621 }
622 } else {
623 LogPrintf("tor: Requesting protocol info failed\n");
624 }
625}
626
628{
630 // First send a PROTOCOLINFO command to figure out what authentication is expected
631 if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
632 LogPrintf("tor: Error sending initial protocolinfo command\n");
633}
634
636{
637 // Stop advertising service when disconnected
638 if (service.IsValid())
640 service = CService();
641 if (!reconnect)
642 return;
643
644 LogDebug(BCLog::TOR, "Not connected to Tor control port %s, retrying in %.2f s\n",
646
647 // Single-shot timer for reconnect. Use exponential backoff with a maximum.
648 struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
649 if (reconnect_ev)
650 event_add(reconnect_ev, &time);
651
653}
654
656{
657 /* Try to reconnect and reestablish if we get booted - for example, Tor
658 * may be restarting.
659 */
660 if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
661 std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
662 LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
663 }
664}
665
667{
668 return gArgs.GetDataDirNet() / "onion_v3_private_key";
669}
670
671void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
672{
673 TorController *self = static_cast<TorController*>(arg);
674 self->Reconnect();
675}
676
677/****** Thread ********/
678static struct event_base *gBase;
679static std::thread torControlThread;
680
681static void TorControlThread(CService onion_service_target)
682{
683 TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
684
685 event_base_dispatch(gBase);
686}
687
688void StartTorControl(CService onion_service_target)
689{
690 assert(!gBase);
691#ifdef WIN32
692 evthread_use_windows_threads();
693#else
694 evthread_use_pthreads();
695#endif
696 gBase = event_base_new();
697 if (!gBase) {
698 LogPrintf("tor: Unable to create event_base\n");
699 return;
700 }
701
702 torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
703 TorControlThread(onion_service_target);
704 });
705}
706
708{
709 if (gBase) {
710 LogPrintf("tor: Thread interrupt\n");
711 event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
712 event_base_loopbreak(gBase);
713 }, nullptr, nullptr);
714 }
715}
716
718{
719 if (gBase) {
720 torControlThread.join();
721 event_base_free(gBase);
722 gBase = nullptr;
723 }
724}
725
727{
728 struct in_addr onion_service_target;
729 onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
730 return {onion_service_target, port};
731}
ArgsManager gArgs
Definition: args.cpp:42
const auto cmd
const CChainParams & Params()
Return the currently selected parameters.
#define Assume(val)
Assume is the identity function.
Definition: check.h:97
std::vector< std::string > GetArgs(const std::string &strArg) const
Return a vector of strings of the given argument.
Definition: args.cpp:362
fs::path GetDataDirNet() const
Get data directory path with appended network identifier.
Definition: args.h:234
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: args.cpp:457
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:15
CHMAC_SHA256 & Write(const unsigned char *data, size_t len)
Definition: hmac_sha256.h:24
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:29
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:21
bool IsValid() const
Definition: netaddress.cpp:428
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:531
std::string ToStringAddrPort() const
Definition: netaddress.cpp:907
Definition: netbase.h:59
void Add(Network net) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Definition: netbase.h:103
Low-level handling for Tor control connection.
Definition: torcontrol.h:52
TorControlReply message
Message being received.
Definition: torcontrol.h:92
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.h:94
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:151
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:78
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:195
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.h:84
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:89
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.h:55
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:134
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.h:86
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.h:54
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:188
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.h:90
struct event_base * base
Libevent event base.
Definition: torcontrol.h:88
Reply from Tor, can be single or multi-line.
Definition: torcontrol.h:34
std::vector< std::string > lines
Definition: torcontrol.h:39
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.h:107
TorControlConnection conn
Definition: torcontrol.h:123
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:671
std::string service_id
Definition: torcontrol.h:125
struct event_base * base
Definition: torcontrol.h:121
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:666
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.h:134
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:627
void get_socks_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for GETINFO net/listeners/socks result.
Definition: torcontrol.cpp:359
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:430
const std::string m_tor_control_center
Definition: torcontrol.h:122
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:635
const CService m_target
Definition: torcontrol.h:130
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:516
CService service
Definition: torcontrol.h:129
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.h:132
struct event * reconnect_ev
Definition: torcontrol.h:127
float reconnect_timeout
Definition: torcontrol.h:128
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:465
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:655
std::string private_key
Definition: torcontrol.h:124
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:551
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:151
static path PathFromString(const std::string &string)
Convert byte string to path object.
Definition: fs.h:174
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:29
#define LogInfo(...)
Definition: logging.h:261
#define LogDebug(category,...)
Definition: logging.h:280
#define LogPrintf(...)
Definition: logging.h:266
@ TOR
Definition: logging.h:44
std::vector< std::string > SplitString(std::string_view str, char sep)
Definition: string.h:136
void TraceThread(std::string_view thread_name, std::function< void()> thread_func)
A wrapper for do-something-once thread functions.
Definition: thread.cpp:16
std::string ToString(const T &t)
Locale-independent version of std::to_string.
Definition: string.h:233
void ReplaceAll(std::string &in_out, const std::string &search, const std::string &substitute)
Definition: string.cpp:11
void RemoveLocal(const CService &addr)
Definition: net.cpp:310
bool AddLocal(const CService &addr_, int nScore)
Definition: net.cpp:277
@ LOCAL_MANUAL
Definition: net.h:152
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:43
bool SetProxy(enum Network net, const Proxy &addrProxy)
Definition: netbase.cpp:704
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:195
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:220
void GetRandBytes(std::span< unsigned char > bytes) noexcept
Generate random data via the internal PRNG.
Definition: random.cpp:603
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::vector< Byte > ParseHex(std::string_view hex_str)
Like TryParseHex, but returns an empty vector on invalid input.
Definition: strencodings.h:68
#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:62
static std::vector< uint8_t > ComputeResponse(const std::string &key, const std::vector< uint8_t > &cookie, const std::vector< uint8_t > &clientNonce, const std::vector< uint8_t > &serverNonce)
Compute Tor SAFECOOKIE response.
Definition: torcontrol.cpp:505
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:73
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:66
const std::string DEFAULT_TOR_CONTROL
Default control ip and port.
Definition: torcontrol.cpp:51
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:681
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:215
static const int TOR_REPLY_UNRECOGNIZED
Definition: torcontrol.cpp:58
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:60
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:53
static struct event_base * gBase
Definition: torcontrol.cpp:678
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:55
static const float RECONNECT_TIMEOUT_MAX
Maximum reconnect timeout in seconds to prevent excessive delays.
Definition: torcontrol.cpp:68
void InterruptTorControl()
Definition: torcontrol.cpp:707
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:234
static const int TOR_REPLY_OK
Tor control reply code.
Definition: torcontrol.cpp:57
static std::thread torControlThread
Definition: torcontrol.cpp:679
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:64
static const uint16_t DEFAULT_TOR_SOCKS_PORT
Definition: torcontrol.cpp:74
CService DefaultOnionServiceTarget(uint16_t port)
Definition: torcontrol.cpp:726
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:688
void StopTorControl()
Definition: torcontrol.cpp:717
constexpr int DEFAULT_TOR_CONTROL_PORT
Functionality for communicating with Tor.
Definition: torcontrol.h:22
std::string SanitizeString(std::string_view str, int rule)
Remove unsafe chars.
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: time.cpp:119
assert(!tx.IsCoinBase())