Bitcoin ABC  0.24.7
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2016 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 <crypto/hmac_sha256.h>
11 #include <net.h>
12 #include <netaddress.h>
13 #include <netbase.h>
14 #include <util/strencodings.h>
15 #include <util/system.h>
16 
17 #include <boost/algorithm/string/classification.hpp>
18 #include <boost/algorithm/string/replace.hpp>
19 #include <boost/algorithm/string/split.hpp>
20 #include <boost/signals2/signal.hpp>
21 
22 #include <event2/buffer.h>
23 #include <event2/bufferevent.h>
24 #include <event2/event.h>
25 #include <event2/thread.h>
26 #include <event2/util.h>
27 
28 #include <cstdlib>
29 #include <deque>
30 #include <set>
31 #include <vector>
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 =
41  "Tor safe cookie authentication server-to-controller hash";
43 static const std::string TOR_SAFE_CLIENTKEY =
44  "Tor safe cookie authentication controller-to-server hash";
46 static const float RECONNECT_TIMEOUT_START = 1.0;
48 static const float RECONNECT_TIMEOUT_EXP = 1.5;
55 static const int MAX_LINE_LENGTH = 100000;
56 
57 /****** Low-level TorControlConnection ********/
58 
61 public:
63 
64  int code;
65  std::vector<std::string> lines;
66 
67  void Clear() {
68  code = 0;
69  lines.clear();
70  }
71 };
72 
78 public:
79  typedef std::function<void(TorControlConnection &)> ConnectionCB;
80  typedef std::function<void(TorControlConnection &, const TorControlReply &)>
82 
85  explicit TorControlConnection(struct event_base *base);
87 
96  bool Connect(const std::string &tor_control_center,
97  const ConnectionCB &connected,
98  const ConnectionCB &disconnected);
99 
103  void Disconnect();
104 
110  bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler);
111 
113  boost::signals2::signal<void(TorControlConnection &,
114  const TorControlReply &)>
116 
117 private:
119  std::function<void(TorControlConnection &)> connected;
121  std::function<void(TorControlConnection &)> disconnected;
123  struct event_base *base;
125  struct bufferevent *b_conn;
129  std::deque<ReplyHandlerCB> reply_handlers;
130 
132  static void readcb(struct bufferevent *bev, void *ctx);
133  static void eventcb(struct bufferevent *bev, short what, void *ctx);
134 };
135 
137  : base(_base), b_conn(nullptr) {}
138 
140  if (b_conn) {
141  bufferevent_free(b_conn);
142  }
143 }
144 
145 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx) {
146  TorControlConnection *self = static_cast<TorControlConnection *>(ctx);
147  struct evbuffer *input = bufferevent_get_input(bev);
148  size_t n_read_out = 0;
149  char *line;
150  assert(input);
151  // If there is not a whole line to read, evbuffer_readln returns nullptr
152  while ((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) !=
153  nullptr) {
154  std::string s(line, n_read_out);
155  free(line);
156  // Short line
157  if (s.size() < 4) {
158  continue;
159  }
160  // <status>(-|+| )<data><CRLF>
161  self->message.code = atoi(s.substr(0, 3));
162  self->message.lines.push_back(s.substr(4));
163  // '-','+' or ' '
164  char ch = s[3];
165  if (ch == ' ') {
166  // Final line, dispatch reply and clean up
167  if (self->message.code >= 600) {
168  // Dispatch async notifications to async handler.
169  // Synchronous and asynchronous messages are never interleaved
170  self->async_handler(*self, self->message);
171  } else {
172  if (!self->reply_handlers.empty()) {
173  // Invoke reply handler with message
174  self->reply_handlers.front()(*self, self->message);
175  self->reply_handlers.pop_front();
176  } else {
178  "tor: Received unexpected sync reply %i\n",
179  self->message.code);
180  }
181  }
182  self->message.Clear();
183  }
184  }
185 
186  // Check for size of buffer - protect against memory exhaustion with very
187  // long lines. Do this after evbuffer_readln to make sure all full lines
188  // have been removed from the buffer. Everything left is an incomplete line.
189  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
190  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
191  self->Disconnect();
192  }
193 }
194 
195 void TorControlConnection::eventcb(struct bufferevent *bev, short what,
196  void *ctx) {
197  TorControlConnection *self = static_cast<TorControlConnection *>(ctx);
198  if (what & BEV_EVENT_CONNECTED) {
199  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
200  self->connected(*self);
201  } else if (what & (BEV_EVENT_EOF | BEV_EVENT_ERROR)) {
202  if (what & BEV_EVENT_ERROR) {
204  "tor: Error connecting to Tor control socket\n");
205  } else {
206  LogPrint(BCLog::TOR, "tor: End of stream\n");
207  }
208  self->Disconnect();
209  self->disconnected(*self);
210  }
211 }
212 
213 bool TorControlConnection::Connect(const std::string &tor_control_center,
214  const ConnectionCB &_connected,
215  const ConnectionCB &_disconnected) {
216  if (b_conn) {
217  Disconnect();
218  }
219  // Parse tor_control_center address:port
220  struct sockaddr_storage connect_to_addr;
221  int connect_to_addrlen = sizeof(connect_to_addr);
222  if (evutil_parse_sockaddr_port(tor_control_center.c_str(),
223  (struct sockaddr *)&connect_to_addr,
224  &connect_to_addrlen) < 0) {
225  LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
226  return false;
227  }
228 
229  // Create a new socket, set up callbacks and enable notification bits
230  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
231  if (!b_conn) {
232  return false;
233  }
234  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr,
236  bufferevent_enable(b_conn, EV_READ | EV_WRITE);
237  this->connected = _connected;
238  this->disconnected = _disconnected;
239 
240  // Finally, connect to tor_control_center
241  if (bufferevent_socket_connect(b_conn, (struct sockaddr *)&connect_to_addr,
242  connect_to_addrlen) < 0) {
243  LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
244  return false;
245  }
246  return true;
247 }
248 
250  if (b_conn) {
251  bufferevent_free(b_conn);
252  }
253  b_conn = nullptr;
254 }
255 
256 bool TorControlConnection::Command(const std::string &cmd,
257  const ReplyHandlerCB &reply_handler) {
258  if (!b_conn) {
259  return false;
260  }
261  struct evbuffer *buf = bufferevent_get_output(b_conn);
262  if (!buf) {
263  return false;
264  }
265  evbuffer_add(buf, cmd.data(), cmd.size());
266  evbuffer_add(buf, "\r\n", 2);
267  reply_handlers.push_back(reply_handler);
268  return true;
269 }
270 
271 /****** General parsing utilities ********/
272 
273 /* Split reply line in the form 'AUTH METHODS=...' into a type
274  * 'AUTH' and arguments 'METHODS=...'.
275  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
276  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
277  */
278 std::pair<std::string, std::string> SplitTorReplyLine(const std::string &s) {
279  size_t ptr = 0;
280  std::string type;
281  while (ptr < s.size() && s[ptr] != ' ') {
282  type.push_back(s[ptr]);
283  ++ptr;
284  }
285  if (ptr < s.size()) {
286  // skip ' '
287  ++ptr;
288  }
289  return make_pair(type, s.substr(ptr));
290 }
291 
300 std::map<std::string, std::string> ParseTorReplyMapping(const std::string &s) {
301  std::map<std::string, std::string> mapping;
302  size_t ptr = 0;
303  while (ptr < s.size()) {
304  std::string key, value;
305  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
306  key.push_back(s[ptr]);
307  ++ptr;
308  }
309  // unexpected end of line
310  if (ptr == s.size()) {
311  return std::map<std::string, std::string>();
312  }
313  // The remaining string is an OptArguments
314  if (s[ptr] == ' ') {
315  break;
316  }
317  // skip '='
318  ++ptr;
319  // Quoted string
320  if (ptr < s.size() && s[ptr] == '"') {
321  // skip opening '"'
322  ++ptr;
323  bool escape_next = false;
324  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
325  // Repeated backslashes must be interpreted as pairs
326  escape_next = (s[ptr] == '\\' && !escape_next);
327  value.push_back(s[ptr]);
328  ++ptr;
329  }
330  // unexpected end of line
331  if (ptr == s.size()) {
332  return std::map<std::string, std::string>();
333  }
334  // skip closing '"'
335  ++ptr;
348  std::string escaped_value;
349  for (size_t i = 0; i < value.size(); ++i) {
350  if (value[i] == '\\') {
351  // This will always be valid, because if the QuotedString
352  // ended in an odd number of backslashes, then the parser
353  // would already have returned above, due to a missing
354  // terminating double-quote.
355  ++i;
356  if (value[i] == 'n') {
357  escaped_value.push_back('\n');
358  } else if (value[i] == 't') {
359  escaped_value.push_back('\t');
360  } else if (value[i] == 'r') {
361  escaped_value.push_back('\r');
362  } else if ('0' <= value[i] && value[i] <= '7') {
363  size_t j;
364  // Octal escape sequences have a limit of three octal
365  // digits, but terminate at the first character that is
366  // not a valid octal digit if encountered sooner.
367  for (j = 1; j < 3 && (i + j) < value.size() &&
368  '0' <= value[i + j] && value[i + j] <= '7';
369  ++j) {
370  }
371  // Tor restricts first digit to 0-3 for three-digit
372  // octals. A leading digit of 4-7 would therefore be
373  // interpreted as a two-digit octal.
374  if (j == 3 && value[i] > '3') {
375  j--;
376  }
377  escaped_value.push_back(
378  strtol(value.substr(i, j).c_str(), NULL, 8));
379  // Account for automatic incrementing at loop end
380  i += j - 1;
381  } else {
382  escaped_value.push_back(value[i]);
383  }
384  } else {
385  escaped_value.push_back(value[i]);
386  }
387  }
388  value = escaped_value;
389  } else {
390  // Unquoted value. Note that values can contain '=' at will, just no
391  // spaces
392  while (ptr < s.size() && s[ptr] != ' ') {
393  value.push_back(s[ptr]);
394  ++ptr;
395  }
396  }
397  if (ptr < s.size() && s[ptr] == ' ') {
398  // skip ' ' after key=value
399  ++ptr;
400  }
401  mapping[key] = value;
402  }
403  return mapping;
404 }
405 
416 static std::pair<bool, std::string>
417 ReadBinaryFile(const fs::path &filename,
418  size_t maxsize = std::numeric_limits<size_t>::max()) {
419  FILE *f = fsbridge::fopen(filename, "rb");
420  if (f == nullptr) {
421  return std::make_pair(false, "");
422  }
423  std::string retval;
424  char buffer[128];
425  size_t n;
426  while ((n = fread(buffer, 1, sizeof(buffer), f)) > 0) {
427  // Check for reading errors so we don't return any data if we couldn't
428  // read the entire file (or up to maxsize)
429  if (ferror(f)) {
430  fclose(f);
431  return std::make_pair(false, "");
432  }
433  retval.append(buffer, buffer + n);
434  if (retval.size() > maxsize) {
435  break;
436  }
437  }
438  fclose(f);
439  return std::make_pair(true, retval);
440 }
441 
446 static bool WriteBinaryFile(const fs::path &filename, const std::string &data) {
447  FILE *f = fsbridge::fopen(filename, "wb");
448  if (f == nullptr) {
449  return false;
450  }
451  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
452  fclose(f);
453  return false;
454  }
455  fclose(f);
456  return true;
457 }
458 
459 /****** Bitcoin specific TorController implementation ********/
460 
466 public:
467  TorController(struct event_base *base,
468  const std::string &tor_control_center,
469  const CService &target);
470  ~TorController();
471 
473  fs::path GetPrivateKeyFile();
474 
476  void Reconnect();
477 
478 private:
479  struct event_base *base;
480  const std::string m_tor_control_center;
482  std::string private_key;
483  std::string service_id;
484  bool reconnect;
485  struct event *reconnect_ev;
490  std::vector<uint8_t> cookie;
492  std::vector<uint8_t> clientNonce;
493 
497  void auth_cb(TorControlConnection &conn, const TorControlReply &reply);
500  const TorControlReply &reply);
503  const TorControlReply &reply);
508 
510  static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
511 };
512 
513 TorController::TorController(struct event_base *_base,
514  const std::string &tor_control_center,
515  const CService &target)
516  : base(_base), m_tor_control_center(tor_control_center), conn(base),
517  reconnect(true), reconnect_ev(0),
518  reconnect_timeout(RECONNECT_TIMEOUT_START), m_target(target) {
519  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
520  if (!reconnect_ev) {
521  LogPrintf(
522  "tor: Failed to create event for reconnection: out of memory?\n");
523  }
524  // Start connection attempts immediately
526  std::bind(&TorController::connected_cb, this,
527  std::placeholders::_1),
528  std::bind(&TorController::disconnected_cb, this,
529  std::placeholders::_1))) {
530  LogPrintf("tor: Initiating connection to Tor control port %s failed\n",
532  }
533  // Read service private key if cached
534  std::pair<bool, std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
535  if (pkf.first) {
536  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n",
538  private_key = pkf.second;
539  }
540 }
541 
543  if (reconnect_ev) {
544  event_free(reconnect_ev);
545  reconnect_ev = nullptr;
546  }
547  if (service.IsValid()) {
549  }
550 }
551 
553  const TorControlReply &reply) {
554  if (reply.code == 250) {
555  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
556  for (const std::string &s : reply.lines) {
557  std::map<std::string, std::string> m = ParseTorReplyMapping(s);
558  std::map<std::string, std::string>::iterator i;
559  if ((i = m.find("ServiceID")) != m.end()) {
560  service_id = i->second;
561  }
562  if ((i = m.find("PrivateKey")) != m.end()) {
563  private_key = i->second;
564  }
565  }
566  if (service_id.empty()) {
567  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
568  for (const std::string &s : reply.lines) {
569  LogPrintf(" %s\n", SanitizeString(s));
570  }
571  return;
572  }
573  service = LookupNumeric(std::string(service_id + ".onion"),
574  Params().GetDefaultPort());
575  LogPrintf("tor: Got service ID %s, advertising service %s\n",
578  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n",
580  } else {
581  LogPrintf("tor: Error writing service private key to %s\n",
583  }
585  // ... onion requested - keep connection open
586  } else if (reply.code == 510) { // 510 Unrecognized command
587  LogPrintf("tor: Add onion failed with unrecognized command (You "
588  "probably need to upgrade Tor)\n");
589  } else {
590  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
591  }
592 }
593 
595  const TorControlReply &reply) {
596  if (reply.code == 250) {
597  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
598 
599  // Now that we know Tor is running setup the proxy for onion addresses
600  // if -onion isn't set to something else.
601  if (gArgs.GetArg("-onion", "") == "") {
602  CService resolved(LookupNumeric("127.0.0.1", 9050));
603  proxyType addrOnion = proxyType(resolved, true);
604  SetProxy(NET_ONION, addrOnion);
605  SetReachable(NET_ONION, true);
606  }
607 
608  // Finally - now create the service
609  // No private key, generate one
610  if (private_key.empty()) {
611  // Explicitly request key type - see issue #9214
612  private_key = "NEW:ED25519-V3";
613  }
614  // Request onion service, redirect port.
615  // Note that the 'virtual' port doesn't have to be the same as our
616  // internal port, but this is just a convenient choice. TODO; refactor
617  // the shutdown sequence some day.
618  _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key,
621  std::bind(&TorController::add_onion_cb, this,
622  std::placeholders::_1, std::placeholders::_2));
623  } else {
624  LogPrintf("tor: Authentication failed\n");
625  }
626 }
627 
644 static std::vector<uint8_t>
645 ComputeResponse(const std::string &key, const std::vector<uint8_t> &cookie,
646  const std::vector<uint8_t> &clientNonce,
647  const std::vector<uint8_t> &serverNonce) {
648  CHMAC_SHA256 computeHash((const uint8_t *)key.data(), key.size());
649  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
650  computeHash.Write(cookie.data(), cookie.size());
651  computeHash.Write(clientNonce.data(), clientNonce.size());
652  computeHash.Write(serverNonce.data(), serverNonce.size());
653  computeHash.Finalize(computedHash.data());
654  return computedHash;
655 }
656 
658  const TorControlReply &reply) {
659  if (reply.code == 250) {
661  "tor: SAFECOOKIE authentication challenge successful\n");
662  std::pair<std::string, std::string> l =
663  SplitTorReplyLine(reply.lines[0]);
664  if (l.first == "AUTHCHALLENGE") {
665  std::map<std::string, std::string> m =
666  ParseTorReplyMapping(l.second);
667  if (m.empty()) {
668  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n",
669  SanitizeString(l.second));
670  return;
671  }
672  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
673  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
675  "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n",
676  HexStr(serverHash), HexStr(serverNonce));
677  if (serverNonce.size() != 32) {
678  LogPrintf(
679  "tor: ServerNonce is not 32 bytes, as required by spec\n");
680  return;
681  }
682 
683  std::vector<uint8_t> computedServerHash = ComputeResponse(
684  TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
685  if (computedServerHash != serverHash) {
686  LogPrintf("tor: ServerHash %s does not match expected "
687  "ServerHash %s\n",
688  HexStr(serverHash), HexStr(computedServerHash));
689  return;
690  }
691 
692  std::vector<uint8_t> computedClientHash = ComputeResponse(
693  TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
694  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash),
695  std::bind(&TorController::auth_cb, this,
696  std::placeholders::_1,
697  std::placeholders::_2));
698  } else {
699  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
700  }
701  } else {
702  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
703  }
704 }
705 
707  const TorControlReply &reply) {
708  if (reply.code == 250) {
709  std::set<std::string> methods;
710  std::string cookiefile;
711  /*
712  * 250-AUTH METHODS=COOKIE,SAFECOOKIE
713  * COOKIEFILE="/home/x/.tor/control_auth_cookie"
714  * 250-AUTH METHODS=NULL
715  * 250-AUTH METHODS=HASHEDPASSWORD
716  */
717  for (const std::string &s : reply.lines) {
718  std::pair<std::string, std::string> l = SplitTorReplyLine(s);
719  if (l.first == "AUTH") {
720  std::map<std::string, std::string> m =
721  ParseTorReplyMapping(l.second);
722  std::map<std::string, std::string>::iterator i;
723  if ((i = m.find("METHODS")) != m.end()) {
724  boost::split(methods, i->second, boost::is_any_of(","));
725  }
726  if ((i = m.find("COOKIEFILE")) != m.end()) {
727  cookiefile = i->second;
728  }
729  } else if (l.first == "VERSION") {
730  std::map<std::string, std::string> m =
731  ParseTorReplyMapping(l.second);
732  std::map<std::string, std::string>::iterator i;
733  if ((i = m.find("Tor")) != m.end()) {
734  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n",
735  i->second);
736  }
737  }
738  }
739  for (const std::string &s : methods) {
740  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n",
741  s);
742  }
743  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use
744  // HASHEDPASSWORD
745  /* Authentication:
746  * cookie: hex-encoded ~/.tor/control_auth_cookie
747  * password: "password"
748  */
749  std::string torpassword = gArgs.GetArg("-torpassword", "");
750  if (!torpassword.empty()) {
751  if (methods.count("HASHEDPASSWORD")) {
753  "tor: Using HASHEDPASSWORD authentication\n");
754  boost::replace_all(torpassword, "\"", "\\\"");
755  _conn.Command("AUTHENTICATE \"" + torpassword + "\"",
756  std::bind(&TorController::auth_cb, this,
757  std::placeholders::_1,
758  std::placeholders::_2));
759  } else {
760  LogPrintf("tor: Password provided with -torpassword, but "
761  "HASHEDPASSWORD authentication is not available\n");
762  }
763  } else if (methods.count("NULL")) {
764  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
765  _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb,
766  this, std::placeholders::_1,
767  std::placeholders::_2));
768  } else if (methods.count("SAFECOOKIE")) {
769  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
771  "tor: Using SAFECOOKIE authentication, "
772  "reading cookie authentication from %s\n",
773  cookiefile);
774  std::pair<bool, std::string> status_cookie =
775  ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
776  if (status_cookie.first &&
777  status_cookie.second.size() == TOR_COOKIE_SIZE) {
778  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second),
779  // std::bind(&TorController::auth_cb, this,
780  // std::placeholders::_1, std::placeholders::_2));
781  cookie = std::vector<uint8_t>(status_cookie.second.begin(),
782  status_cookie.second.end());
783  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
785  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce),
786  std::bind(&TorController::authchallenge_cb, this,
787  std::placeholders::_1,
788  std::placeholders::_2));
789  } else {
790  if (status_cookie.first) {
791  LogPrintf("tor: Authentication cookie %s is not exactly %i "
792  "bytes, as is required by the spec\n",
793  cookiefile, TOR_COOKIE_SIZE);
794  } else {
795  LogPrintf("tor: Authentication cookie %s could not be "
796  "opened (check permissions)\n",
797  cookiefile);
798  }
799  }
800  } else if (methods.count("HASHEDPASSWORD")) {
801  LogPrintf("tor: The only supported authentication mechanism left "
802  "is password, but no password provided with "
803  "-torpassword\n");
804  } else {
805  LogPrintf("tor: No supported authentication method\n");
806  }
807  } else {
808  LogPrintf("tor: Requesting protocol info failed\n");
809  }
810 }
811 
814  // First send a PROTOCOLINFO command to figure out what authentication is
815  // expected
816  if (!_conn.Command("PROTOCOLINFO 1",
817  std::bind(&TorController::protocolinfo_cb, this,
818  std::placeholders::_1,
819  std::placeholders::_2))) {
820  LogPrintf("tor: Error sending initial protocolinfo command\n");
821  }
822 }
823 
825  // Stop advertising service when disconnected
826  if (service.IsValid()) {
828  }
829  service = CService();
830  if (!reconnect) {
831  return;
832  }
833 
835  "tor: Not connected to Tor control port %s, trying to reconnect\n",
837 
838  // Single-shot timer for reconnect. Use exponential backoff.
839  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
840  if (reconnect_ev) {
841  event_add(reconnect_ev, &time);
842  }
844 }
845 
847  /* Try to reconnect and reestablish if we get booted - for example, Tor may
848  * be restarting.
849  */
851  std::bind(&TorController::connected_cb, this,
852  std::placeholders::_1),
853  std::bind(&TorController::disconnected_cb, this,
854  std::placeholders::_1))) {
855  LogPrintf(
856  "tor: Re-initiating connection to Tor control port %s failed\n",
858  }
859 }
860 
862  return GetDataDir() / "onion_v3_private_key";
863 }
864 
865 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg) {
866  TorController *self = static_cast<TorController *>(arg);
867  self->Reconnect();
868 }
869 
870 /****** Thread ********/
871 static struct event_base *gBase;
872 static std::thread torControlThread;
873 
874 static void TorControlThread(CService onion_service_target) {
875  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL),
876  onion_service_target);
877 
878  event_base_dispatch(gBase);
879 }
880 
881 void StartTorControl(CService onion_service_target) {
882  assert(!gBase);
883 #ifdef WIN32
884  evthread_use_windows_threads();
885 #else
886  evthread_use_pthreads();
887 #endif
888  gBase = event_base_new();
889  if (!gBase) {
890  LogPrintf("tor: Unable to create event_base\n");
891  return;
892  }
893 
894  torControlThread = std::thread(
895  &TraceThread<std::function<void()>>, "torcontrol",
896  [onion_service_target] { TorControlThread(onion_service_target); });
897 }
898 
900  if (gBase) {
901  LogPrintf("tor: Thread interrupt\n");
902  event_base_once(
903  gBase, -1, EV_TIMEOUT,
904  [](evutil_socket_t, short, void *) { event_base_loopbreak(gBase); },
905  nullptr, nullptr);
906  }
907 }
908 
910  if (gBase) {
911  torControlThread.join();
912  event_base_free(gBase);
913  gBase = nullptr;
914  }
915 }
916 
918  struct in_addr onion_service_target;
919  onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
920  return {onion_service_target, BaseParams().OnionServiceTargetPort()};
921 }
ReadBinaryFile
static 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.
Definition: torcontrol.cpp:417
TorControlReply
Reply from Tor, can be single or multi-line.
Definition: torcontrol.cpp:60
TorController::conn
TorControlConnection conn
Definition: torcontrol.cpp:481
CService
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:514
TOR_SAFE_CLIENTKEY
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:43
hmac_sha256.h
GetDataDir
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:779
ParseHex
std::vector< uint8_t > ParseHex(const char *psz)
Definition: strencodings.cpp:87
RemoveLocal
void RemoveLocal(const CService &addr)
Definition: net.cpp:283
TorControlConnection::b_conn
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.cpp:125
TorControlReply::code
int code
Definition: torcontrol.cpp:64
TorController::m_tor_control_center
const std::string m_tor_control_center
Definition: torcontrol.cpp:480
RECONNECT_TIMEOUT_START
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:46
TorController::connected_cb
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:812
TorController::protocolinfo_cb
void protocolinfo_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for PROTOCOLINFO result.
Definition: torcontrol.cpp:706
ParseTorReplyMapping
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:300
fsbridge::fopen
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
TorControlConnection
Low-level handling for Tor control connection.
Definition: torcontrol.cpp:77
atoi
int atoi(const std::string &str)
Definition: strencodings.cpp:477
CHMAC_SHA256
A hasher class for HMAC-SHA-256.
Definition: hmac_sha256.h:14
TorController::cookie
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.cpp:490
TorControlConnection::reply_handlers
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:129
chainparamsbase.h
WriteBinaryFile
static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
Definition: torcontrol.cpp:446
StartTorControl
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:881
TorController::~TorController
~TorController()
Definition: torcontrol.cpp:542
TorControlConnection::disconnected
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.cpp:121
TorControlReply::Clear
void Clear()
Definition: torcontrol.cpp:67
InterruptTorControl
void InterruptTorControl()
Definition: torcontrol.cpp:899
CHMAC_SHA256::Finalize
void Finalize(uint8_t hash[OUTPUT_SIZE])
Definition: hmac_sha256.cpp:30
TorControlConnection::readcb
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:145
GetRandBytes
void GetRandBytes(uint8_t *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:634
TorControlConnection::Connect
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:213
TorController::disconnected_cb
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:824
chainparams.h
TorControlConnection::connected
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.cpp:119
TorControlConnection::ConnectionCB
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.cpp:79
proxyType
Definition: netbase.h:28
CService::ToStringIPPort
std::string ToStringIPPort() const
Definition: netaddress.cpp:1012
TorController::reconnect_ev
struct event * reconnect_ev
Definition: torcontrol.cpp:485
TOR_NONCE_SIZE
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:38
strencodings.h
TraceThread
void TraceThread(const char *name, Callable func)
Definition: system.h:446
CService::ToString
std::string ToString() const
Definition: netaddress.cpp:1020
TOR_COOKIE_SIZE
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:36
LOCAL_MANUAL
@ LOCAL_MANUAL
Definition: net.h:708
torControlThread
static std::thread torControlThread
Definition: torcontrol.cpp:872
DEFAULT_TOR_CONTROL
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:34
TorController::add_onion_cb
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:552
MillisToTimeval
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:284
DefaultOnionServiceTarget
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:917
TorController::service_id
std::string service_id
Definition: torcontrol.cpp:483
TorControlReply::TorControlReply
TorControlReply()
Definition: torcontrol.cpp:62
TorControlConnection::TorControlConnection
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:136
netaddress.h
CBaseChainParams::OnionServiceTargetPort
uint16_t OnionServiceTargetPort() const
Definition: chainparamsbase.h:27
SetReachable
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:289
TorControlReply::lines
std::vector< std::string > lines
Definition: torcontrol.cpp:65
ArgsManager::GetArg
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:498
gBase
static struct event_base * gBase
Definition: torcontrol.cpp:871
TOR_SAFE_SERVERKEY
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:40
CNetAddr::IsValid
bool IsValid() const
Definition: netaddress.cpp:438
BCLog::TOR
@ TOR
Definition: logging.h:39
SplitTorReplyLine
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:278
TorControlConnection::Disconnect
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:249
TorController::service
CService service
Definition: torcontrol.cpp:487
TorController::base
struct event_base * base
Definition: torcontrol.cpp:479
LogPrint
#define LogPrint(category,...)
Definition: logging.h:193
TorController::auth_cb
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:594
MAX_LINE_LENGTH
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:55
TorController::reconnect
bool reconnect
Definition: torcontrol.cpp:484
CHMAC_SHA256::OUTPUT_SIZE
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:20
ctx
secp256k1_context * ctx
Definition: bench_multiset.c:12
system.h
TorController::Reconnect
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:846
SetProxy
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:773
strprintf
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1201
TorController::clientNonce
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.cpp:492
SanitizeString
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
Definition: strencodings.cpp:31
TorControlConnection::async_handler
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
Definition: torcontrol.cpp:115
TorController::TorController
TorController(struct event_base *base, const std::string &tor_control_center, const CService &target)
Definition: torcontrol.cpp:513
ComputeResponse
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:645
torcontrol.h
BaseParams
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
Definition: chainparamsbase.cpp:36
TorControlConnection::Command
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:256
TorController::m_target
const CService m_target
Definition: torcontrol.cpp:488
gArgs
ArgsManager gArgs
Definition: system.cpp:75
GetDefaultPort
static uint16_t GetDefaultPort()
Definition: bitcoin.h:16
CHMAC_SHA256::Write
CHMAC_SHA256 & Write(const uint8_t *data, size_t len)
Definition: hmac_sha256.h:23
NET_ONION
@ NET_ONION
TOR (v2 or v3)
Definition: netaddress.h:55
TorController::reconnect_timeout
float reconnect_timeout
Definition: torcontrol.cpp:486
TorController::authchallenge_cb
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:657
RECONNECT_TIMEOUT_EXP
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:48
Params
const CChainParams & Params()
Return the currently selected parameters.
Definition: chainparams.cpp:508
TorController
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.cpp:465
LookupNumeric
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:271
StopTorControl
void StopTorControl()
Definition: torcontrol.cpp:909
netbase.h
TorController::private_key
std::string private_key
Definition: torcontrol.cpp:482
TorController::GetPrivateKeyFile
fs::path GetPrivateKeyFile()
Get name fo file to store private key in.
Definition: torcontrol.cpp:861
TorControlConnection::~TorControlConnection
~TorControlConnection()
Definition: torcontrol.cpp:139
net.h
TorControlConnection::eventcb
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:195
HexStr
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
Definition: strencodings.cpp:656
TorControlConnection::message
TorControlReply message
Message being received.
Definition: torcontrol.cpp:127
TorControlConnection::ReplyHandlerCB
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.cpp:81
TorControlConnection::base
struct event_base * base
Libevent event base.
Definition: torcontrol.cpp:123
TorControlThread
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:874
LogPrintf
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:175
TorController::reconnect_cb
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:865
AddLocal
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:251