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