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