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