Bitcoin Core  0.20.99
P2P Digital Currency
torcontrol.cpp
Go to the documentation of this file.
1 // Copyright (c) 2015-2019 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 <vector>
18 #include <deque>
19 #include <set>
20 #include <stdlib.h>
21 
22 #include <boost/signals2/signal.hpp>
23 #include <boost/algorithm/string/split.hpp>
24 #include <boost/algorithm/string/classification.hpp>
25 #include <boost/algorithm/string/replace.hpp>
26 
27 #include <event2/bufferevent.h>
28 #include <event2/buffer.h>
29 #include <event2/util.h>
30 #include <event2/event.h>
31 #include <event2/thread.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 
53 /****** Low-level TorControlConnection ********/
54 
57 {
58 public:
60 
61  int code;
62  std::vector<std::string> lines;
63 
64  void Clear()
65  {
66  code = 0;
67  lines.clear();
68  }
69 };
70 
75 {
76 public:
77  typedef std::function<void(TorControlConnection&)> ConnectionCB;
78  typedef std::function<void(TorControlConnection &,const TorControlReply &)> ReplyHandlerCB;
79 
82  explicit TorControlConnection(struct event_base *base);
84 
92  bool Connect(const std::string& tor_control_center, const ConnectionCB& connected, const ConnectionCB& disconnected);
93 
97  void Disconnect();
98 
103  bool Command(const std::string &cmd, const ReplyHandlerCB& reply_handler);
104 
106  boost::signals2::signal<void(TorControlConnection &,const TorControlReply &)> async_handler;
107 private:
109  std::function<void(TorControlConnection&)> connected;
111  std::function<void(TorControlConnection&)> disconnected;
113  struct event_base *base;
115  struct bufferevent *b_conn;
119  std::deque<ReplyHandlerCB> reply_handlers;
120 
122  static void readcb(struct bufferevent *bev, void *ctx);
123  static void eventcb(struct bufferevent *bev, short what, void *ctx);
124 };
125 
127  base(_base), b_conn(nullptr)
128 {
129 }
130 
132 {
133  if (b_conn)
134  bufferevent_free(b_conn);
135 }
136 
137 void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
138 {
139  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
140  struct evbuffer *input = bufferevent_get_input(bev);
141  size_t n_read_out = 0;
142  char *line;
143  assert(input);
144  // If there is not a whole line to read, evbuffer_readln returns nullptr
145  while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
146  {
147  std::string s(line, n_read_out);
148  free(line);
149  if (s.size() < 4) // Short line
150  continue;
151  // <status>(-|+| )<data><CRLF>
152  self->message.code = atoi(s.substr(0,3));
153  self->message.lines.push_back(s.substr(4));
154  char ch = s[3]; // '-','+' or ' '
155  if (ch == ' ') {
156  // Final line, dispatch reply and clean up
157  if (self->message.code >= 600) {
158  // Dispatch async notifications to async handler
159  // Synchronous and asynchronous messages are never interleaved
160  self->async_handler(*self, self->message);
161  } else {
162  if (!self->reply_handlers.empty()) {
163  // Invoke reply handler with message
164  self->reply_handlers.front()(*self, self->message);
165  self->reply_handlers.pop_front();
166  } else {
167  LogPrint(BCLog::TOR, "tor: Received unexpected sync reply %i\n", self->message.code);
168  }
169  }
170  self->message.Clear();
171  }
172  }
173  // Check for size of buffer - protect against memory exhaustion with very long lines
174  // Do this after evbuffer_readln to make sure all full lines have been
175  // removed from the buffer. Everything left is an incomplete line.
176  if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
177  LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
178  self->Disconnect();
179  }
180 }
181 
182 void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
183 {
184  TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
185  if (what & BEV_EVENT_CONNECTED) {
186  LogPrint(BCLog::TOR, "tor: Successfully connected!\n");
187  self->connected(*self);
188  } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
189  if (what & BEV_EVENT_ERROR) {
190  LogPrint(BCLog::TOR, "tor: Error connecting to Tor control socket\n");
191  } else {
192  LogPrint(BCLog::TOR, "tor: End of stream\n");
193  }
194  self->Disconnect();
195  self->disconnected(*self);
196  }
197 }
198 
199 bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
200 {
201  if (b_conn)
202  Disconnect();
203  // Parse tor_control_center address:port
204  struct sockaddr_storage connect_to_addr;
205  int connect_to_addrlen = sizeof(connect_to_addr);
206  if (evutil_parse_sockaddr_port(tor_control_center.c_str(),
207  (struct sockaddr*)&connect_to_addr, &connect_to_addrlen)<0) {
208  LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
209  return false;
210  }
211 
212  // Create a new socket, set up callbacks and enable notification bits
213  b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
214  if (!b_conn)
215  return false;
216  bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
217  bufferevent_enable(b_conn, EV_READ|EV_WRITE);
218  this->connected = _connected;
219  this->disconnected = _disconnected;
220 
221  // Finally, connect to tor_control_center
222  if (bufferevent_socket_connect(b_conn, (struct sockaddr*)&connect_to_addr, connect_to_addrlen) < 0) {
223  LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
224  return false;
225  }
226  return true;
227 }
228 
230 {
231  if (b_conn)
232  bufferevent_free(b_conn);
233  b_conn = nullptr;
234 }
235 
236 bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
237 {
238  if (!b_conn)
239  return false;
240  struct evbuffer *buf = bufferevent_get_output(b_conn);
241  if (!buf)
242  return false;
243  evbuffer_add(buf, cmd.data(), cmd.size());
244  evbuffer_add(buf, "\r\n", 2);
245  reply_handlers.push_back(reply_handler);
246  return true;
247 }
248 
249 /****** General parsing utilities ********/
250 
251 /* Split reply line in the form 'AUTH METHODS=...' into a type
252  * 'AUTH' and arguments 'METHODS=...'.
253  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
254  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
255  */
256 std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
257 {
258  size_t ptr=0;
259  std::string type;
260  while (ptr < s.size() && s[ptr] != ' ') {
261  type.push_back(s[ptr]);
262  ++ptr;
263  }
264  if (ptr < s.size())
265  ++ptr; // skip ' '
266  return make_pair(type, s.substr(ptr));
267 }
268 
275 std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
276 {
277  std::map<std::string,std::string> mapping;
278  size_t ptr=0;
279  while (ptr < s.size()) {
280  std::string key, value;
281  while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
282  key.push_back(s[ptr]);
283  ++ptr;
284  }
285  if (ptr == s.size()) // unexpected end of line
286  return std::map<std::string,std::string>();
287  if (s[ptr] == ' ') // The remaining string is an OptArguments
288  break;
289  ++ptr; // skip '='
290  if (ptr < s.size() && s[ptr] == '"') { // Quoted string
291  ++ptr; // skip opening '"'
292  bool escape_next = false;
293  while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
294  // Repeated backslashes must be interpreted as pairs
295  escape_next = (s[ptr] == '\\' && !escape_next);
296  value.push_back(s[ptr]);
297  ++ptr;
298  }
299  if (ptr == s.size()) // unexpected end of line
300  return std::map<std::string,std::string>();
301  ++ptr; // skip closing '"'
312  std::string escaped_value;
313  for (size_t i = 0; i < value.size(); ++i) {
314  if (value[i] == '\\') {
315  // This will always be valid, because if the QuotedString
316  // ended in an odd number of backslashes, then the parser
317  // would already have returned above, due to a missing
318  // terminating double-quote.
319  ++i;
320  if (value[i] == 'n') {
321  escaped_value.push_back('\n');
322  } else if (value[i] == 't') {
323  escaped_value.push_back('\t');
324  } else if (value[i] == 'r') {
325  escaped_value.push_back('\r');
326  } else if ('0' <= value[i] && value[i] <= '7') {
327  size_t j;
328  // Octal escape sequences have a limit of three octal digits,
329  // but terminate at the first character that is not a valid
330  // octal digit if encountered sooner.
331  for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
332  // Tor restricts first digit to 0-3 for three-digit octals.
333  // A leading digit of 4-7 would therefore be interpreted as
334  // a two-digit octal.
335  if (j == 3 && value[i] > '3') {
336  j--;
337  }
338  escaped_value.push_back(strtol(value.substr(i, j).c_str(), nullptr, 8));
339  // Account for automatic incrementing at loop end
340  i += j - 1;
341  } else {
342  escaped_value.push_back(value[i]);
343  }
344  } else {
345  escaped_value.push_back(value[i]);
346  }
347  }
348  value = escaped_value;
349  } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
350  while (ptr < s.size() && s[ptr] != ' ') {
351  value.push_back(s[ptr]);
352  ++ptr;
353  }
354  }
355  if (ptr < s.size() && s[ptr] == ' ')
356  ++ptr; // skip ' ' after key=value
357  mapping[key] = value;
358  }
359  return mapping;
360 }
361 
369 static std::pair<bool,std::string> ReadBinaryFile(const fs::path &filename, size_t maxsize=std::numeric_limits<size_t>::max())
370 {
371  FILE *f = fsbridge::fopen(filename, "rb");
372  if (f == nullptr)
373  return std::make_pair(false,"");
374  std::string retval;
375  char buffer[128];
376  size_t n;
377  while ((n=fread(buffer, 1, sizeof(buffer), f)) > 0) {
378  // Check for reading errors so we don't return any data if we couldn't
379  // read the entire file (or up to maxsize)
380  if (ferror(f)) {
381  fclose(f);
382  return std::make_pair(false,"");
383  }
384  retval.append(buffer, buffer+n);
385  if (retval.size() > maxsize)
386  break;
387  }
388  fclose(f);
389  return std::make_pair(true,retval);
390 }
391 
395 static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
396 {
397  FILE *f = fsbridge::fopen(filename, "wb");
398  if (f == nullptr)
399  return false;
400  if (fwrite(data.data(), 1, data.size(), f) != data.size()) {
401  fclose(f);
402  return false;
403  }
404  fclose(f);
405  return true;
406 }
407 
408 /****** Bitcoin specific TorController implementation ********/
409 
414 {
415 public:
416  TorController(struct event_base* base, const std::string& tor_control_center, const CService& target);
417  ~TorController();
418 
420  fs::path GetPrivateKeyFile();
421 
423  void Reconnect();
424 private:
425  struct event_base* base;
426  const std::string m_tor_control_center;
428  std::string private_key;
429  std::string service_id;
430  bool reconnect;
431  struct event *reconnect_ev;
436  std::vector<uint8_t> cookie;
438  std::vector<uint8_t> clientNonce;
439 
441  void add_onion_cb(TorControlConnection& conn, const TorControlReply& reply);
443  void auth_cb(TorControlConnection& conn, const TorControlReply& reply);
445  void authchallenge_cb(TorControlConnection& conn, const TorControlReply& reply);
447  void protocolinfo_cb(TorControlConnection& conn, const TorControlReply& reply);
449  void connected_cb(TorControlConnection& conn);
451  void disconnected_cb(TorControlConnection& conn);
452 
454  static void reconnect_cb(evutil_socket_t fd, short what, void *arg);
455 };
456 
457 TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
458  base(_base),
459  m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_ev(0),
460  reconnect_timeout(RECONNECT_TIMEOUT_START),
461  m_target(target)
462 {
463  reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
464  if (!reconnect_ev)
465  LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
466  // Start connection attempts immediately
467  if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
468  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
469  LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
470  }
471  // Read service private key if cached
472  std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
473  if (pkf.first) {
474  LogPrint(BCLog::TOR, "tor: Reading cached private key from %s\n", GetPrivateKeyFile().string());
475  private_key = pkf.second;
476  }
477 }
478 
480 {
481  if (reconnect_ev) {
482  event_free(reconnect_ev);
483  reconnect_ev = nullptr;
484  }
485  if (service.IsValid()) {
487  }
488 }
489 
491 {
492  if (reply.code == 250) {
493  LogPrint(BCLog::TOR, "tor: ADD_ONION successful\n");
494  for (const std::string &s : reply.lines) {
495  std::map<std::string,std::string> m = ParseTorReplyMapping(s);
496  std::map<std::string,std::string>::iterator i;
497  if ((i = m.find("ServiceID")) != m.end())
498  service_id = i->second;
499  if ((i = m.find("PrivateKey")) != m.end())
500  private_key = i->second;
501  }
502  if (service_id.empty()) {
503  LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
504  for (const std::string &s : reply.lines) {
505  LogPrintf(" %s\n", SanitizeString(s));
506  }
507  return;
508  }
509  service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
510  LogPrintf("tor: Got service ID %s, advertising service %s\n", service_id, service.ToString());
512  LogPrint(BCLog::TOR, "tor: Cached service private key to %s\n", GetPrivateKeyFile().string());
513  } else {
514  LogPrintf("tor: Error writing service private key to %s\n", GetPrivateKeyFile().string());
515  }
517  // ... onion requested - keep connection open
518  } else if (reply.code == 510) { // 510 Unrecognized command
519  LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
520  } else {
521  LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
522  }
523 }
524 
526 {
527  if (reply.code == 250) {
528  LogPrint(BCLog::TOR, "tor: Authentication successful\n");
529 
530  // Now that we know Tor is running setup the proxy for onion addresses
531  // if -onion isn't set to something else.
532  if (gArgs.GetArg("-onion", "") == "") {
533  CService resolved(LookupNumeric("127.0.0.1", 9050));
534  proxyType addrOnion = proxyType(resolved, true);
535  SetProxy(NET_ONION, addrOnion);
536  SetReachable(NET_ONION, true);
537  }
538 
539  // Finally - now create the service
540  if (private_key.empty()) { // No private key, generate one
541  private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
542  }
543  // Request onion service, redirect port.
544  // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
545  _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringIPPort()),
546  std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
547  } else {
548  LogPrintf("tor: Authentication failed\n");
549  }
550 }
551 
568 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)
569 {
570  CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
571  std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
572  computeHash.Write(cookie.data(), cookie.size());
573  computeHash.Write(clientNonce.data(), clientNonce.size());
574  computeHash.Write(serverNonce.data(), serverNonce.size());
575  computeHash.Finalize(computedHash.data());
576  return computedHash;
577 }
578 
580 {
581  if (reply.code == 250) {
582  LogPrint(BCLog::TOR, "tor: SAFECOOKIE authentication challenge successful\n");
583  std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
584  if (l.first == "AUTHCHALLENGE") {
585  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
586  if (m.empty()) {
587  LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
588  return;
589  }
590  std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
591  std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
592  LogPrint(BCLog::TOR, "tor: AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
593  if (serverNonce.size() != 32) {
594  LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
595  return;
596  }
597 
598  std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
599  if (computedServerHash != serverHash) {
600  LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
601  return;
602  }
603 
604  std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
605  _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
606  } else {
607  LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
608  }
609  } else {
610  LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
611  }
612 }
613 
615 {
616  if (reply.code == 250) {
617  std::set<std::string> methods;
618  std::string cookiefile;
619  /*
620  * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
621  * 250-AUTH METHODS=NULL
622  * 250-AUTH METHODS=HASHEDPASSWORD
623  */
624  for (const std::string &s : reply.lines) {
625  std::pair<std::string,std::string> l = SplitTorReplyLine(s);
626  if (l.first == "AUTH") {
627  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
628  std::map<std::string,std::string>::iterator i;
629  if ((i = m.find("METHODS")) != m.end())
630  boost::split(methods, i->second, boost::is_any_of(","));
631  if ((i = m.find("COOKIEFILE")) != m.end())
632  cookiefile = i->second;
633  } else if (l.first == "VERSION") {
634  std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
635  std::map<std::string,std::string>::iterator i;
636  if ((i = m.find("Tor")) != m.end()) {
637  LogPrint(BCLog::TOR, "tor: Connected to Tor version %s\n", i->second);
638  }
639  }
640  }
641  for (const std::string &s : methods) {
642  LogPrint(BCLog::TOR, "tor: Supported authentication method: %s\n", s);
643  }
644  // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
645  /* Authentication:
646  * cookie: hex-encoded ~/.tor/control_auth_cookie
647  * password: "password"
648  */
649  std::string torpassword = gArgs.GetArg("-torpassword", "");
650  if (!torpassword.empty()) {
651  if (methods.count("HASHEDPASSWORD")) {
652  LogPrint(BCLog::TOR, "tor: Using HASHEDPASSWORD authentication\n");
653  boost::replace_all(torpassword, "\"", "\\\"");
654  _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
655  } else {
656  LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
657  }
658  } else if (methods.count("NULL")) {
659  LogPrint(BCLog::TOR, "tor: Using NULL authentication\n");
660  _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
661  } else if (methods.count("SAFECOOKIE")) {
662  // Cookie: hexdump -e '32/1 "%02x""\n"' ~/.tor/control_auth_cookie
663  LogPrint(BCLog::TOR, "tor: Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
664  std::pair<bool,std::string> status_cookie = ReadBinaryFile(cookiefile, TOR_COOKIE_SIZE);
665  if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
666  // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
667  cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
668  clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
669  GetRandBytes(clientNonce.data(), TOR_NONCE_SIZE);
670  _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
671  } else {
672  if (status_cookie.first) {
673  LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
674  } else {
675  LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
676  }
677  }
678  } else if (methods.count("HASHEDPASSWORD")) {
679  LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
680  } else {
681  LogPrintf("tor: No supported authentication method\n");
682  }
683  } else {
684  LogPrintf("tor: Requesting protocol info failed\n");
685  }
686 }
687 
689 {
691  // First send a PROTOCOLINFO command to figure out what authentication is expected
692  if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
693  LogPrintf("tor: Error sending initial protocolinfo command\n");
694 }
695 
697 {
698  // Stop advertising service when disconnected
699  if (service.IsValid())
701  service = CService();
702  if (!reconnect)
703  return;
704 
705  LogPrint(BCLog::TOR, "tor: Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center);
706 
707  // Single-shot timer for reconnect. Use exponential backoff.
708  struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
709  if (reconnect_ev)
710  event_add(reconnect_ev, &time);
712 }
713 
715 {
716  /* Try to reconnect and reestablish if we get booted - for example, Tor
717  * may be restarting.
718  */
719  if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
720  std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
721  LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
722  }
723 }
724 
726 {
727  return GetDataDir() / "onion_v3_private_key";
728 }
729 
730 void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
731 {
732  TorController *self = static_cast<TorController*>(arg);
733  self->Reconnect();
734 }
735 
736 /****** Thread ********/
737 static struct event_base *gBase;
738 static std::thread torControlThread;
739 
740 static void TorControlThread(CService onion_service_target)
741 {
742  TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
743 
744  event_base_dispatch(gBase);
745 }
746 
747 void StartTorControl(CService onion_service_target)
748 {
749  assert(!gBase);
750 #ifdef WIN32
751  evthread_use_windows_threads();
752 #else
753  evthread_use_pthreads();
754 #endif
755  gBase = event_base_new();
756  if (!gBase) {
757  LogPrintf("tor: Unable to create event_base\n");
758  return;
759  }
760 
761  torControlThread = std::thread(&TraceThread<std::function<void()>>, "torcontrol", [onion_service_target] {
762  TorControlThread(onion_service_target);
763  });
764 }
765 
767 {
768  if (gBase) {
769  LogPrintf("tor: Thread interrupt\n");
770  event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
771  event_base_loopbreak(gBase);
772  }, nullptr, nullptr);
773  }
774 }
775 
777 {
778  if (gBase) {
779  torControlThread.join();
780  event_base_free(gBase);
781  gBase = nullptr;
782  }
783 }
784 
786 {
787  struct in_addr onion_service_target;
788  onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
789  return {onion_service_target, BaseParams().OnionServiceTargetPort()};
790 }
void authchallenge_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHCHALLENGE result.
Definition: torcontrol.cpp:579
std::string SanitizeString(const std::string &str, int rule)
Remove unsafe chars.
const CService m_target
Definition: torcontrol.cpp:434
static void TorControlThread(CService onion_service_target)
Definition: torcontrol.cpp:740
static std::thread torControlThread
Definition: torcontrol.cpp:738
CService LookupNumeric(const std::string &name, int portDefault)
Resolve a service string with a numeric IP to its first corresponding service.
Definition: netbase.cpp:255
static const std::string TOR_SAFE_CLIENTKEY
For computing clientHash in SAFECOOKIE.
Definition: torcontrol.cpp:42
#define LogPrint(category,...)
Definition: logging.h:182
bool AddLocal(const CService &addr, int nScore)
Definition: net.cpp:236
FILE * fopen(const fs::path &p, const char *mode)
Definition: fs.cpp:24
std::function< void(TorControlConnection &)> disconnected
Callback when connection lost.
Definition: torcontrol.cpp:111
std::function< void(TorControlConnection &)> ConnectionCB
Definition: torcontrol.cpp:77
bool Connect(const std::string &tor_control_center, const ConnectionCB &connected, const ConnectionCB &disconnected)
Connect to a Tor control port.
Definition: torcontrol.cpp:199
struct bufferevent * b_conn
Connection to control socket.
Definition: torcontrol.cpp:115
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1164
static const int TOR_COOKIE_SIZE
Tor cookie size (from control-spec.txt)
Definition: torcontrol.cpp:36
std::vector< uint8_t > clientNonce
ClientNonce for SAFECOOKIE auth.
Definition: torcontrol.cpp:438
static struct event_base * gBase
Definition: torcontrol.cpp:737
Reply from Tor, can be single or multi-line.
Definition: torcontrol.cpp:56
std::vector< unsigned char > ParseHex(const char *psz)
void StopTorControl()
Definition: torcontrol.cpp:776
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:614
void Reconnect()
Reconnect, after getting disconnected.
Definition: torcontrol.cpp:714
static bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
Definition: torcontrol.cpp:395
std::vector< std::string > lines
Definition: torcontrol.cpp:62
static const int TOR_NONCE_SIZE
Size of client/server nonce for SAFECOOKIE.
Definition: torcontrol.cpp:38
const CBaseChainParams & BaseParams()
Return the currently selected parameters.
static void LogPrintf(const char *fmt, const Args &... args)
Definition: logging.h:166
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:369
uint16_t OnionServiceTargetPort() const
void GetRandBytes(unsigned char *buf, int num) noexcept
Overall design of the RNG and entropy sources.
Definition: random.cpp:585
float reconnect_timeout
Definition: torcontrol.cpp:432
void StartTorControl(CService onion_service_target)
Definition: torcontrol.cpp:747
std::deque< ReplyHandlerCB > reply_handlers
Response handlers.
Definition: torcontrol.cpp:119
void SetReachable(enum Network net, bool reachable)
Mark a network as reachable or unreachable (no automatic connects to it)
Definition: net.cpp:274
std::function< void(TorControlConnection &, const TorControlReply &)> ReplyHandlerCB
Definition: torcontrol.cpp:78
void disconnected_cb(TorControlConnection &conn)
Callback after connection lost or failed connection attempt.
Definition: torcontrol.cpp:696
bool IsValid() const
Definition: netaddress.cpp:428
std::string private_key
Definition: torcontrol.cpp:428
const std::string m_tor_control_center
Definition: torcontrol.cpp:426
static void readcb(struct bufferevent *bev, void *ctx)
Libevent handlers: internal.
Definition: torcontrol.cpp:137
fs::path GetPrivateKeyFile()
Get name of file to store private key in.
Definition: torcontrol.cpp:725
struct event * reconnect_ev
Definition: torcontrol.cpp:431
TorControlConnection(struct event_base *base)
Create a new TorControlConnection.
Definition: torcontrol.cpp:126
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:275
const std::string DEFAULT_TOR_CONTROL
Default control port.
Definition: torcontrol.cpp:34
std::vector< uint8_t > cookie
Cookie for SAFECOOKIE auth.
Definition: torcontrol.cpp:436
static const float RECONNECT_TIMEOUT_START
Exponential backoff configuration - initial timeout in seconds.
Definition: torcontrol.cpp:44
TorControlConnection conn
Definition: torcontrol.cpp:427
static const float RECONNECT_TIMEOUT_EXP
Exponential backoff configuration - growth factor.
Definition: torcontrol.cpp:46
static secp256k1_context * ctx
Definition: tests.c:36
int atoi(const std::string &str)
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:501
static void reconnect_cb(evutil_socket_t fd, short what, void *arg)
Callback for reconnect timer.
Definition: torcontrol.cpp:730
const fs::path & GetDataDir(bool fNetSpecific)
Definition: system.cpp:706
void add_onion_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for ADD_ONION result.
Definition: torcontrol.cpp:490
std::pair< std::string, std::string > SplitTorReplyLine(const std::string &s)
Definition: torcontrol.cpp:256
void TraceThread(const char *name, Callable func)
Definition: system.h:432
std::string HexStr(const Span< const uint8_t > s)
Convert a span of bytes to a lower-case hexadecimal string.
std::string service_id
Definition: torcontrol.cpp:429
bool SetProxy(enum Network net, const proxyType &addrProxy)
Definition: netbase.cpp:712
struct timeval MillisToTimeval(int64_t nTimeout)
Convert milliseconds to a struct timeval for e.g.
Definition: netbase.cpp:268
void auth_cb(TorControlConnection &conn, const TorControlReply &reply)
Callback for AUTHENTICATE result.
Definition: torcontrol.cpp:525
void Disconnect()
Disconnect from Tor control port.
Definition: torcontrol.cpp:229
CService service
Definition: torcontrol.cpp:433
struct event_base * base
Definition: torcontrol.cpp:425
const CChainParams & Params()
Return the currently selected parameters.
static void eventcb(struct bufferevent *bev, short what, void *ctx)
Definition: torcontrol.cpp:182
static const size_t OUTPUT_SIZE
Definition: hmac_sha256.h:21
std::string GetArg(const std::string &strArg, const std::string &strDefault) const
Return string argument or default value.
Definition: system.cpp:466
std::string ToStringIPPort() const
Definition: netaddress.cpp:968
bool Command(const std::string &cmd, const ReplyHandlerCB &reply_handler)
Send a command, register a handler for the reply.
Definition: torcontrol.cpp:236
TOR (v2 or v3)
Definition: netaddress.h:55
ArgsManager gArgs
Definition: system.cpp:76
CService DefaultOnionServiceTarget()
Definition: torcontrol.cpp:785
void connected_cb(TorControlConnection &conn)
Callback after successful connection.
Definition: torcontrol.cpp:688
std::string ToString() const
Definition: netaddress.cpp:977
Controller that connects to Tor control socket, authenticate, then create and maintain an ephemeral o...
Definition: torcontrol.cpp:413
void InterruptTorControl()
Definition: torcontrol.cpp:766
Low-level handling for Tor control connection.
Definition: torcontrol.cpp:74
static const int MAX_LINE_LENGTH
Maximum length for lines received on TorControlConnection.
Definition: torcontrol.cpp:51
static const std::string TOR_SAFE_SERVERKEY
For computing serverHash in SAFECOOKIE.
Definition: torcontrol.cpp:40
boost::signals2::signal< void(TorControlConnection &, const TorControlReply &)> async_handler
Response handlers for async replies.
Definition: torcontrol.cpp:106
if(it !=peer.m_getdata_requests.end() &&!pfrom.fPauseSend)
TorController(struct event_base *base, const std::string &tor_control_center, const CService &target)
Definition: torcontrol.cpp:457
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:568
TorControlReply message
Message being received.
Definition: torcontrol.cpp:117
void RemoveLocal(const CService &addr)
Definition: net.cpp:267
struct event_base * base
Libevent event base.
Definition: torcontrol.cpp:113
std::function< void(TorControlConnection &)> connected
Callback when ready for use.
Definition: torcontrol.cpp:109