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