LCOV - code coverage report
Current view: top level - src - torcontrol.cpp (source / functions) Coverage Total Hit
Test: fuzz_coverage.info Lines: 43.5 % 379 165
Test Date: 2024-11-04 04:15:01 Functions: 39.3 % 28 11
Branches: 29.5 % 662 195

             Branch data     Line data    Source code
       1                 :             : // Copyright (c) 2015-2022 The Bitcoin Core developers
       2                 :             : // Copyright (c) 2017 The Zcash developers
       3                 :             : // Distributed under the MIT software license, see the accompanying
       4                 :             : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
       5                 :             : 
       6                 :             : #include <torcontrol.h>
       7                 :             : 
       8                 :             : #include <chainparams.h>
       9                 :             : #include <chainparamsbase.h>
      10                 :             : #include <common/args.h>
      11                 :             : #include <compat/compat.h>
      12                 :             : #include <crypto/hmac_sha256.h>
      13                 :             : #include <logging.h>
      14                 :             : #include <net.h>
      15                 :             : #include <netaddress.h>
      16                 :             : #include <netbase.h>
      17                 :             : #include <random.h>
      18                 :             : #include <tinyformat.h>
      19                 :             : #include <util/check.h>
      20                 :             : #include <util/fs.h>
      21                 :             : #include <util/readwritefile.h>
      22                 :             : #include <util/strencodings.h>
      23                 :             : #include <util/string.h>
      24                 :             : #include <util/thread.h>
      25                 :             : #include <util/time.h>
      26                 :             : 
      27                 :             : #include <algorithm>
      28                 :             : #include <cassert>
      29                 :             : #include <cstdlib>
      30                 :             : #include <deque>
      31                 :             : #include <functional>
      32                 :             : #include <map>
      33                 :             : #include <optional>
      34                 :             : #include <set>
      35                 :             : #include <thread>
      36                 :             : #include <utility>
      37                 :             : #include <vector>
      38                 :             : 
      39                 :             : #include <event2/buffer.h>
      40                 :             : #include <event2/bufferevent.h>
      41                 :             : #include <event2/event.h>
      42                 :             : #include <event2/thread.h>
      43                 :             : #include <event2/util.h>
      44                 :             : 
      45                 :             : using util::ReplaceAll;
      46                 :             : using util::SplitString;
      47                 :             : using util::ToString;
      48                 :             : 
      49                 :             : /** Default control ip and port */
      50                 :             : const std::string DEFAULT_TOR_CONTROL = "127.0.0.1:" + ToString(DEFAULT_TOR_CONTROL_PORT);
      51                 :             : /** Tor cookie size (from control-spec.txt) */
      52                 :             : static const int TOR_COOKIE_SIZE = 32;
      53                 :             : /** Size of client/server nonce for SAFECOOKIE */
      54                 :             : static const int TOR_NONCE_SIZE = 32;
      55                 :             : /** For computing serverHash in SAFECOOKIE */
      56                 :             : static const std::string TOR_SAFE_SERVERKEY = "Tor safe cookie authentication server-to-controller hash";
      57                 :             : /** For computing clientHash in SAFECOOKIE */
      58                 :             : static const std::string TOR_SAFE_CLIENTKEY = "Tor safe cookie authentication controller-to-server hash";
      59                 :             : /** Exponential backoff configuration - initial timeout in seconds */
      60                 :             : static const float RECONNECT_TIMEOUT_START = 1.0;
      61                 :             : /** Exponential backoff configuration - growth factor */
      62                 :             : static const float RECONNECT_TIMEOUT_EXP = 1.5;
      63                 :             : /** Maximum length for lines received on TorControlConnection.
      64                 :             :  * tor-control-spec.txt mentions that there is explicitly no limit defined to line length,
      65                 :             :  * this is belt-and-suspenders sanity limit to prevent memory exhaustion.
      66                 :             :  */
      67                 :             : static const int MAX_LINE_LENGTH = 100000;
      68                 :             : static const uint16_t DEFAULT_TOR_SOCKS_PORT = 9050;
      69                 :             : 
      70                 :             : /****** Low-level TorControlConnection ********/
      71                 :             : 
      72                 :      120482 : TorControlConnection::TorControlConnection(struct event_base* _base)
      73         [ +  - ]:      120482 :     : base(_base)
      74                 :             : {
      75                 :      120482 : }
      76                 :             : 
      77                 :      120482 : TorControlConnection::~TorControlConnection()
      78                 :             : {
      79         [ -  + ]:      120482 :     if (b_conn)
      80                 :           0 :         bufferevent_free(b_conn);
      81                 :      120482 : }
      82                 :             : 
      83                 :           0 : void TorControlConnection::readcb(struct bufferevent *bev, void *ctx)
      84                 :             : {
      85                 :           0 :     TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
      86                 :           0 :     struct evbuffer *input = bufferevent_get_input(bev);
      87                 :           0 :     size_t n_read_out = 0;
      88                 :           0 :     char *line;
      89         [ #  # ]:           0 :     assert(input);
      90                 :             :     //  If there is not a whole line to read, evbuffer_readln returns nullptr
      91         [ #  # ]:           0 :     while((line = evbuffer_readln(input, &n_read_out, EVBUFFER_EOL_CRLF)) != nullptr)
      92                 :             :     {
      93                 :           0 :         std::string s(line, n_read_out);
      94                 :           0 :         free(line);
      95         [ #  # ]:           0 :         if (s.size() < 4) // Short line
      96                 :           0 :             continue;
      97                 :             :         // <status>(-|+| )<data><CRLF>
      98   [ #  #  #  # ]:           0 :         self->message.code = ToIntegral<int>(s.substr(0, 3)).value_or(0);
      99         [ #  # ]:           0 :         self->message.lines.push_back(s.substr(4));
     100         [ #  # ]:           0 :         char ch = s[3]; // '-','+' or ' '
     101         [ #  # ]:           0 :         if (ch == ' ') {
     102                 :             :             // Final line, dispatch reply and clean up
     103         [ #  # ]:           0 :             if (self->message.code >= 600) {
     104                 :             :                 // (currently unused)
     105                 :             :                 // Dispatch async notifications to async handler
     106                 :             :                 // Synchronous and asynchronous messages are never interleaved
     107                 :             :             } else {
     108         [ #  # ]:           0 :                 if (!self->reply_handlers.empty()) {
     109                 :             :                     // Invoke reply handler with message
     110         [ #  # ]:           0 :                     self->reply_handlers.front()(*self, self->message);
     111                 :           0 :                     self->reply_handlers.pop_front();
     112                 :             :                 } else {
     113   [ #  #  #  #  :           0 :                     LogDebug(BCLog::TOR, "Received unexpected sync reply %i\n", self->message.code);
                   #  # ]
     114                 :             :                 }
     115                 :             :             }
     116                 :           0 :             self->message.Clear();
     117                 :             :         }
     118                 :           0 :     }
     119                 :             :     //  Check for size of buffer - protect against memory exhaustion with very long lines
     120                 :             :     //  Do this after evbuffer_readln to make sure all full lines have been
     121                 :             :     //  removed from the buffer. Everything left is an incomplete line.
     122         [ #  # ]:           0 :     if (evbuffer_get_length(input) > MAX_LINE_LENGTH) {
     123                 :           0 :         LogPrintf("tor: Disconnecting because MAX_LINE_LENGTH exceeded\n");
     124                 :           0 :         self->Disconnect();
     125                 :             :     }
     126                 :           0 : }
     127                 :             : 
     128                 :           0 : void TorControlConnection::eventcb(struct bufferevent *bev, short what, void *ctx)
     129                 :             : {
     130                 :           0 :     TorControlConnection *self = static_cast<TorControlConnection*>(ctx);
     131         [ #  # ]:           0 :     if (what & BEV_EVENT_CONNECTED) {
     132         [ #  # ]:           0 :         LogDebug(BCLog::TOR, "Successfully connected!\n");
     133                 :           0 :         self->connected(*self);
     134         [ #  # ]:           0 :     } else if (what & (BEV_EVENT_EOF|BEV_EVENT_ERROR)) {
     135         [ #  # ]:           0 :         if (what & BEV_EVENT_ERROR) {
     136         [ #  # ]:           0 :             LogDebug(BCLog::TOR, "Error connecting to Tor control socket\n");
     137                 :             :         } else {
     138         [ #  # ]:           0 :             LogDebug(BCLog::TOR, "End of stream\n");
     139                 :             :         }
     140                 :           0 :         self->Disconnect();
     141                 :           0 :         self->disconnected(*self);
     142                 :             :     }
     143                 :           0 : }
     144                 :             : 
     145                 :           0 : bool TorControlConnection::Connect(const std::string& tor_control_center, const ConnectionCB& _connected, const ConnectionCB& _disconnected)
     146                 :             : {
     147         [ #  # ]:           0 :     if (b_conn) {
     148                 :           0 :         Disconnect();
     149                 :             :     }
     150                 :             : 
     151         [ #  # ]:           0 :     const std::optional<CService> control_service{Lookup(tor_control_center, DEFAULT_TOR_CONTROL_PORT, fNameLookup)};
     152         [ #  # ]:           0 :     if (!control_service.has_value()) {
     153         [ #  # ]:           0 :         LogPrintf("tor: Failed to look up control center %s\n", tor_control_center);
     154                 :             :         return false;
     155                 :             :     }
     156                 :             : 
     157                 :           0 :     struct sockaddr_storage control_address;
     158                 :           0 :     socklen_t control_address_len = sizeof(control_address);
     159   [ #  #  #  # ]:           0 :     if (!control_service.value().GetSockAddr(reinterpret_cast<struct sockaddr*>(&control_address), &control_address_len)) {
     160         [ #  # ]:           0 :         LogPrintf("tor: Error parsing socket address %s\n", tor_control_center);
     161                 :             :         return false;
     162                 :             :     }
     163                 :             : 
     164                 :             :     // Create a new socket, set up callbacks and enable notification bits
     165         [ #  # ]:           0 :     b_conn = bufferevent_socket_new(base, -1, BEV_OPT_CLOSE_ON_FREE);
     166         [ #  # ]:           0 :     if (!b_conn) {
     167                 :             :         return false;
     168                 :             :     }
     169         [ #  # ]:           0 :     bufferevent_setcb(b_conn, TorControlConnection::readcb, nullptr, TorControlConnection::eventcb, this);
     170         [ #  # ]:           0 :     bufferevent_enable(b_conn, EV_READ|EV_WRITE);
     171         [ #  # ]:           0 :     this->connected = _connected;
     172         [ #  # ]:           0 :     this->disconnected = _disconnected;
     173                 :             : 
     174                 :             :     // Finally, connect to tor_control_center
     175   [ #  #  #  # ]:           0 :     if (bufferevent_socket_connect(b_conn, reinterpret_cast<struct sockaddr*>(&control_address), control_address_len) < 0) {
     176         [ #  # ]:           0 :         LogPrintf("tor: Error connecting to address %s\n", tor_control_center);
     177                 :             :         return false;
     178                 :             :     }
     179                 :             :     return true;
     180                 :           0 : }
     181                 :             : 
     182                 :           0 : void TorControlConnection::Disconnect()
     183                 :             : {
     184         [ #  # ]:           0 :     if (b_conn)
     185                 :           0 :         bufferevent_free(b_conn);
     186                 :           0 :     b_conn = nullptr;
     187                 :           0 : }
     188                 :             : 
     189                 :       19124 : bool TorControlConnection::Command(const std::string &cmd, const ReplyHandlerCB& reply_handler)
     190                 :             : {
     191         [ -  + ]:       19124 :     if (!b_conn)
     192                 :             :         return false;
     193                 :           0 :     struct evbuffer *buf = bufferevent_get_output(b_conn);
     194         [ #  # ]:           0 :     if (!buf)
     195                 :             :         return false;
     196                 :           0 :     evbuffer_add(buf, cmd.data(), cmd.size());
     197                 :           0 :     evbuffer_add(buf, "\r\n", 2);
     198                 :           0 :     reply_handlers.push_back(reply_handler);
     199                 :           0 :     return true;
     200                 :             : }
     201                 :             : 
     202                 :             : /****** General parsing utilities ********/
     203                 :             : 
     204                 :             : /* Split reply line in the form 'AUTH METHODS=...' into a type
     205                 :             :  * 'AUTH' and arguments 'METHODS=...'.
     206                 :             :  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
     207                 :             :  * the server reply formats for PROTOCOLINFO (S3.21) and AUTHCHALLENGE (S3.24).
     208                 :             :  */
     209                 :      129180 : std::pair<std::string,std::string> SplitTorReplyLine(const std::string &s)
     210                 :             : {
     211                 :      129180 :     size_t ptr=0;
     212                 :      129180 :     std::string type;
     213   [ +  +  +  + ]:      956783 :     while (ptr < s.size() && s[ptr] != ' ') {
     214         [ +  - ]:      827603 :         type.push_back(s[ptr]);
     215                 :      827603 :         ++ptr;
     216                 :             :     }
     217         [ +  + ]:      129180 :     if (ptr < s.size())
     218                 :       47153 :         ++ptr; // skip ' '
     219         [ +  - ]:      258360 :     return make_pair(type, s.substr(ptr));
     220                 :      129180 : }
     221                 :             : 
     222                 :             : /** Parse reply arguments in the form 'METHODS=COOKIE,SAFECOOKIE COOKIEFILE=".../control_auth_cookie"'.
     223                 :             :  * Returns a map of keys to values, or an empty map if there was an error.
     224                 :             :  * Grammar is implicitly defined in https://spec.torproject.org/control-spec by
     225                 :             :  * the server reply formats for PROTOCOLINFO (S3.21), AUTHCHALLENGE (S3.24),
     226                 :             :  * and ADD_ONION (S3.27). See also sections 2.1 and 2.3.
     227                 :             :  */
     228                 :      335945 : std::map<std::string,std::string> ParseTorReplyMapping(const std::string &s)
     229                 :             : {
     230                 :      335945 :     std::map<std::string,std::string> mapping;
     231                 :      335945 :     size_t ptr=0;
     232         [ +  + ]:      488846 :     while (ptr < s.size()) {
     233                 :      309606 :         std::string key, value;
     234   [ +  +  +  +  :     1804523 :         while (ptr < s.size() && s[ptr] != '=' && s[ptr] != ' ') {
                   +  + ]
     235         [ +  - ]:     1494917 :             key.push_back(s[ptr]);
     236                 :     1494917 :             ++ptr;
     237                 :             :         }
     238         [ +  + ]:      309606 :         if (ptr == s.size()) // unexpected end of line
     239                 :      112849 :             return std::map<std::string,std::string>();
     240         [ +  + ]:      196757 :         if (s[ptr] == ' ') // The remaining string is an OptArguments
     241                 :             :             break;
     242                 :      157163 :         ++ptr; // skip '='
     243   [ +  +  +  + ]:      157163 :         if (ptr < s.size() && s[ptr] == '"') { // Quoted string
     244                 :       29413 :             ++ptr; // skip opening '"'
     245                 :       29413 :             bool escape_next = false;
     246   [ +  +  +  +  :      142893 :             while (ptr < s.size() && (escape_next || s[ptr] != '"')) {
                   +  + ]
     247                 :             :                 // Repeated backslashes must be interpreted as pairs
     248   [ +  +  +  + ]:      113480 :                 escape_next = (s[ptr] == '\\' && !escape_next);
     249         [ +  - ]:      113480 :                 value.push_back(s[ptr]);
     250                 :      113480 :                 ++ptr;
     251                 :             :             }
     252         [ +  + ]:       29413 :             if (ptr == s.size()) // unexpected end of line
     253                 :        4262 :                 return std::map<std::string,std::string>();
     254                 :       25151 :             ++ptr; // skip closing '"'
     255                 :             :             /**
     256                 :             :              * Unescape value. Per https://spec.torproject.org/control-spec section 2.1.1:
     257                 :             :              *
     258                 :             :              *   For future-proofing, controller implementers MAY use the following
     259                 :             :              *   rules to be compatible with buggy Tor implementations and with
     260                 :             :              *   future ones that implement the spec as intended:
     261                 :             :              *
     262                 :             :              *     Read \n \t \r and \0 ... \377 as C escapes.
     263                 :             :              *     Treat a backslash followed by any other character as that character.
     264                 :             :              */
     265                 :       25151 :             std::string escaped_value;
     266         [ +  + ]:       89303 :             for (size_t i = 0; i < value.size(); ++i) {
     267         [ +  + ]:       64152 :                 if (value[i] == '\\') {
     268                 :             :                     // This will always be valid, because if the QuotedString
     269                 :             :                     // ended in an odd number of backslashes, then the parser
     270                 :             :                     // would already have returned above, due to a missing
     271                 :             :                     // terminating double-quote.
     272                 :       24872 :                     ++i;
     273         [ +  + ]:       24872 :                     if (value[i] == 'n') {
     274         [ +  - ]:         277 :                         escaped_value.push_back('\n');
     275         [ +  + ]:       24595 :                     } else if (value[i] == 't') {
     276         [ +  - ]:         315 :                         escaped_value.push_back('\t');
     277         [ +  + ]:       24280 :                     } else if (value[i] == 'r') {
     278         [ +  - ]:        1234 :                         escaped_value.push_back('\r');
     279   [ +  +  +  + ]:       23046 :                     } else if ('0' <= value[i] && value[i] <= '7') {
     280                 :             :                         size_t j;
     281                 :             :                         // Octal escape sequences have a limit of three octal digits,
     282                 :             :                         // but terminate at the first character that is not a valid
     283                 :             :                         // octal digit if encountered sooner.
     284   [ +  +  +  +  :       30230 :                         for (j = 1; j < 3 && (i+j) < value.size() && '0' <= value[i+j] && value[i+j] <= '7'; ++j) {}
             +  +  +  + ]
     285                 :             :                         // Tor restricts first digit to 0-3 for three-digit octals.
     286                 :             :                         // A leading digit of 4-7 would therefore be interpreted as
     287                 :             :                         // a two-digit octal.
     288   [ +  +  +  + ]:       22101 :                         if (j == 3 && value[i] > '3') {
     289                 :        1518 :                             j--;
     290                 :             :                         }
     291                 :       22101 :                         const auto end{i + j};
     292                 :       22101 :                         uint8_t val{0};
     293         [ +  + ]:       50813 :                         while (i < end) {
     294                 :       28712 :                             val *= 8;
     295                 :       28712 :                             val += value[i++] - '0';
     296                 :             :                         }
     297         [ +  - ]:       22101 :                         escaped_value.push_back(char(val));
     298                 :             :                         // Account for automatic incrementing at loop end
     299                 :       22101 :                         --i;
     300                 :             :                     } else {
     301         [ +  - ]:         945 :                         escaped_value.push_back(value[i]);
     302                 :             :                     }
     303                 :             :                 } else {
     304         [ +  - ]:       39280 :                     escaped_value.push_back(value[i]);
     305                 :             :                 }
     306                 :             :             }
     307         [ +  - ]:       50302 :             value = escaped_value;
     308                 :       25151 :         } else { // Unquoted value. Note that values can contain '=' at will, just no spaces
     309   [ +  +  +  + ]:      510000 :             while (ptr < s.size() && s[ptr] != ' ') {
     310         [ +  - ]:      382250 :                 value.push_back(s[ptr]);
     311                 :      382250 :                 ++ptr;
     312                 :             :             }
     313                 :             :         }
     314   [ +  +  +  + ]:      152901 :         if (ptr < s.size() && s[ptr] == ' ')
     315                 :       61943 :             ++ptr; // skip ' ' after key=value
     316   [ +  -  +  - ]:      305802 :         mapping[key] = value;
     317                 :      309606 :     }
     318                 :      218834 :     return mapping;
     319                 :      335945 : }
     320                 :             : 
     321                 :           0 : TorController::TorController(struct event_base* _base, const std::string& tor_control_center, const CService& target):
     322                 :           0 :     base(_base),
     323   [ #  #  #  # ]:           0 :     m_tor_control_center(tor_control_center), conn(base), reconnect(true), reconnect_timeout(RECONNECT_TIMEOUT_START),
     324   [ #  #  #  # ]:           0 :     m_target(target)
     325                 :             : {
     326         [ #  # ]:           0 :     reconnect_ev = event_new(base, -1, 0, reconnect_cb, this);
     327         [ #  # ]:           0 :     if (!reconnect_ev)
     328         [ #  # ]:           0 :         LogPrintf("tor: Failed to create event for reconnection: out of memory?\n");
     329                 :             :     // Start connection attempts immediately
     330   [ #  #  #  #  :           0 :     if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
                   #  # ]
     331         [ #  # ]:           0 :          std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
     332         [ #  # ]:           0 :         LogPrintf("tor: Initiating connection to Tor control port %s failed\n", m_tor_control_center);
     333                 :             :     }
     334                 :             :     // Read service private key if cached
     335   [ #  #  #  # ]:           0 :     std::pair<bool,std::string> pkf = ReadBinaryFile(GetPrivateKeyFile());
     336         [ #  # ]:           0 :     if (pkf.first) {
     337   [ #  #  #  #  :           0 :         LogDebug(BCLog::TOR, "Reading cached private key from %s\n", fs::PathToString(GetPrivateKeyFile()));
             #  #  #  # ]
     338         [ #  # ]:           0 :         private_key = pkf.second;
     339                 :             :     }
     340                 :           0 : }
     341                 :             : 
     342                 :         348 : TorController::~TorController()
     343                 :             : {
     344         [ -  + ]:         348 :     if (reconnect_ev) {
     345                 :           0 :         event_free(reconnect_ev);
     346                 :           0 :         reconnect_ev = nullptr;
     347                 :             :     }
     348         [ -  + ]:         348 :     if (service.IsValid()) {
     349                 :           0 :         RemoveLocal(service);
     350                 :             :     }
     351                 :         348 : }
     352                 :             : 
     353                 :           0 : void TorController::get_socks_cb(TorControlConnection& _conn, const TorControlReply& reply)
     354                 :             : {
     355                 :             :     // NOTE: We can only get here if -onion is unset
     356         [ #  # ]:           0 :     std::string socks_location;
     357         [ #  # ]:           0 :     if (reply.code == 250) {
     358         [ #  # ]:           0 :         for (const auto& line : reply.lines) {
     359   [ #  #  #  # ]:           0 :             if (0 == line.compare(0, 20, "net/listeners/socks=")) {
     360         [ #  # ]:           0 :                 const std::string port_list_str = line.substr(20);
     361         [ #  # ]:           0 :                 std::vector<std::string> port_list = SplitString(port_list_str, ' ');
     362                 :             : 
     363         [ #  # ]:           0 :                 for (auto& portstr : port_list) {
     364         [ #  # ]:           0 :                     if (portstr.empty()) continue;
     365   [ #  #  #  #  :           0 :                     if ((portstr[0] == '"' || portstr[0] == '\'') && portstr.size() >= 2 && (*portstr.rbegin() == portstr[0])) {
             #  #  #  # ]
     366         [ #  # ]:           0 :                         portstr = portstr.substr(1, portstr.size() - 2);
     367         [ #  # ]:           0 :                         if (portstr.empty()) continue;
     368                 :             :                     }
     369         [ #  # ]:           0 :                     socks_location = portstr;
     370   [ #  #  #  # ]:           0 :                     if (0 == portstr.compare(0, 10, "127.0.0.1:")) {
     371                 :             :                         // Prefer localhost - ignore other ports
     372                 :             :                         break;
     373                 :             :                     }
     374                 :             :                 }
     375                 :           0 :             }
     376                 :             :         }
     377         [ #  # ]:           0 :         if (!socks_location.empty()) {
     378   [ #  #  #  #  :           0 :             LogDebug(BCLog::TOR, "Get SOCKS port command yielded %s\n", socks_location);
                   #  # ]
     379                 :             :         } else {
     380         [ #  # ]:           0 :             LogPrintf("tor: Get SOCKS port command returned nothing\n");
     381                 :             :         }
     382         [ #  # ]:           0 :     } else if (reply.code == 510) {  // 510 Unrecognized command
     383         [ #  # ]:           0 :         LogPrintf("tor: Get SOCKS port command failed with unrecognized command (You probably should upgrade Tor)\n");
     384                 :             :     } else {
     385         [ #  # ]:           0 :         LogPrintf("tor: Get SOCKS port command failed; error code %d\n", reply.code);
     386                 :             :     }
     387                 :             : 
     388         [ #  # ]:           0 :     CService resolved;
     389   [ #  #  #  # ]:           0 :     Assume(!resolved.IsValid());
     390         [ #  # ]:           0 :     if (!socks_location.empty()) {
     391   [ #  #  #  # ]:           0 :         resolved = LookupNumeric(socks_location, DEFAULT_TOR_SOCKS_PORT);
     392                 :             :     }
     393   [ #  #  #  # ]:           0 :     if (!resolved.IsValid()) {
     394                 :             :         // Fallback to old behaviour
     395   [ #  #  #  #  :           0 :         resolved = LookupNumeric("127.0.0.1", DEFAULT_TOR_SOCKS_PORT);
                   #  # ]
     396                 :             :     }
     397                 :             : 
     398   [ #  #  #  # ]:           0 :     Assume(resolved.IsValid());
     399   [ #  #  #  #  :           0 :     LogDebug(BCLog::TOR, "Configuring onion proxy for %s\n", resolved.ToStringAddrPort());
             #  #  #  # ]
     400                 :           0 :     Proxy addrOnion = Proxy(resolved, true);
     401         [ #  # ]:           0 :     SetProxy(NET_ONION, addrOnion);
     402                 :             : 
     403   [ #  #  #  # ]:           0 :     const auto onlynets = gArgs.GetArgs("-onlynet");
     404                 :             : 
     405                 :           0 :     const bool onion_allowed_by_onlynet{
     406   [ #  #  #  #  :           0 :         !gArgs.IsArgSet("-onlynet") ||
             #  #  #  # ]
     407         [ #  # ]:           0 :         std::any_of(onlynets.begin(), onlynets.end(), [](const auto& n) {
     408                 :           0 :             return ParseNetwork(n) == NET_ONION;
     409                 :           0 :         })};
     410                 :             : 
     411         [ #  # ]:           0 :     if (onion_allowed_by_onlynet) {
     412                 :             :         // If NET_ONION is reachable, then the below is a noop.
     413                 :             :         //
     414                 :             :         // If NET_ONION is not reachable, then none of -proxy or -onion was given.
     415                 :             :         // Since we are here, then -torcontrol and -torpassword were given.
     416         [ #  # ]:           0 :         g_reachable_nets.Add(NET_ONION);
     417                 :             :     }
     418                 :           0 : }
     419                 :             : 
     420                 :       31741 : void TorController::add_onion_cb(TorControlConnection& _conn, const TorControlReply& reply)
     421                 :             : {
     422         [ +  + ]:       31741 :     if (reply.code == 250) {
     423         [ -  + ]:       27672 :         LogDebug(BCLog::TOR, "ADD_ONION successful\n");
     424         [ +  + ]:      339125 :         for (const std::string &s : reply.lines) {
     425                 :      311453 :             std::map<std::string,std::string> m = ParseTorReplyMapping(s);
     426         [ +  - ]:      311453 :             std::map<std::string,std::string>::iterator i;
     427   [ +  -  +  + ]:      622906 :             if ((i = m.find("ServiceID")) != m.end())
     428         [ +  - ]:        2866 :                 service_id = i->second;
     429   [ +  -  +  + ]:      622906 :             if ((i = m.find("PrivateKey")) != m.end())
     430         [ +  - ]:      314844 :                 private_key = i->second;
     431                 :      311453 :         }
     432         [ +  + ]:       27672 :         if (service_id.empty()) {
     433                 :        3054 :             LogPrintf("tor: Error parsing ADD_ONION parameters:\n");
     434         [ +  + ]:       24485 :             for (const std::string &s : reply.lines) {
     435         [ +  - ]:       42862 :                 LogPrintf("    %s\n", SanitizeString(s));
     436                 :             :             }
     437                 :             :             return;
     438                 :             :         }
     439   [ +  -  +  -  :       24618 :         service = LookupNumeric(std::string(service_id+".onion"), Params().GetDefaultPort());
                   +  - ]
     440         [ +  - ]:       24618 :         LogInfo("Got tor service ID %s, advertising service %s\n", service_id, service.ToStringAddrPort());
     441   [ +  -  +  - ]:       49236 :         if (WriteBinaryFile(GetPrivateKeyFile(), private_key)) {
     442   [ -  +  -  -  :       24618 :             LogDebug(BCLog::TOR, "Cached service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
                   -  - ]
     443                 :             :         } else {
     444   [ #  #  #  # ]:           0 :             LogPrintf("tor: Error writing service private key to %s\n", fs::PathToString(GetPrivateKeyFile()));
     445                 :             :         }
     446                 :       24618 :         AddLocal(service, LOCAL_MANUAL);
     447                 :             :         // ... onion requested - keep connection open
     448         [ +  + ]:        4069 :     } else if (reply.code == 510) { // 510 Unrecognized command
     449                 :        3344 :         LogPrintf("tor: Add onion failed with unrecognized command (You probably need to upgrade Tor)\n");
     450                 :             :     } else {
     451                 :         725 :         LogPrintf("tor: Add onion failed; error code %d\n", reply.code);
     452                 :             :     }
     453                 :             : }
     454                 :             : 
     455                 :        9943 : void TorController::auth_cb(TorControlConnection& _conn, const TorControlReply& reply)
     456                 :             : {
     457         [ +  + ]:        9943 :     if (reply.code == 250) {
     458         [ -  + ]:        9562 :         LogDebug(BCLog::TOR, "Authentication successful\n");
     459                 :             : 
     460                 :             :         // Now that we know Tor is running setup the proxy for onion addresses
     461                 :             :         // if -onion isn't set to something else.
     462   [ +  -  +  -  :        9562 :         if (gArgs.GetArg("-onion", "") == "") {
                   +  - ]
     463   [ +  -  +  - ]:       19124 :             _conn.Command("GETINFO net/listeners/socks", std::bind(&TorController::get_socks_cb, this, std::placeholders::_1, std::placeholders::_2));
     464                 :             :         }
     465                 :             : 
     466                 :             :         // Finally - now create the service
     467         [ +  + ]:        9562 :         if (private_key.empty()) { // No private key, generate one
     468                 :        2569 :             private_key = "NEW:ED25519-V3"; // Explicitly request key type - see issue #9214
     469                 :             :         }
     470                 :             :         // Request onion service, redirect port.
     471                 :             :         // Note that the 'virtual' port is always the default port to avoid decloaking nodes using other ports.
     472   [ +  -  +  -  :       19124 :         _conn.Command(strprintf("ADD_ONION %s Port=%i,%s", private_key, Params().GetDefaultPort(), m_target.ToStringAddrPort()),
             +  -  +  - ]
     473                 :        9562 :             std::bind(&TorController::add_onion_cb, this, std::placeholders::_1, std::placeholders::_2));
     474                 :             :     } else {
     475                 :         381 :         LogPrintf("tor: Authentication failed\n");
     476                 :             :     }
     477                 :        9943 : }
     478                 :             : 
     479                 :             : /** Compute Tor SAFECOOKIE response.
     480                 :             :  *
     481                 :             :  *    ServerHash is computed as:
     482                 :             :  *      HMAC-SHA256("Tor safe cookie authentication server-to-controller hash",
     483                 :             :  *                  CookieString | ClientNonce | ServerNonce)
     484                 :             :  *    (with the HMAC key as its first argument)
     485                 :             :  *
     486                 :             :  *    After a controller sends a successful AUTHCHALLENGE command, the
     487                 :             :  *    next command sent on the connection must be an AUTHENTICATE command,
     488                 :             :  *    and the only authentication string which that AUTHENTICATE command
     489                 :             :  *    will accept is:
     490                 :             :  *
     491                 :             :  *      HMAC-SHA256("Tor safe cookie authentication controller-to-server hash",
     492                 :             :  *                  CookieString | ClientNonce | ServerNonce)
     493                 :             :  *
     494                 :             :  */
     495                 :           0 : 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)
     496                 :             : {
     497                 :           0 :     CHMAC_SHA256 computeHash((const uint8_t*)key.data(), key.size());
     498                 :           0 :     std::vector<uint8_t> computedHash(CHMAC_SHA256::OUTPUT_SIZE, 0);
     499         [ #  # ]:           0 :     computeHash.Write(cookie.data(), cookie.size());
     500         [ #  # ]:           0 :     computeHash.Write(clientNonce.data(), clientNonce.size());
     501         [ #  # ]:           0 :     computeHash.Write(serverNonce.data(), serverNonce.size());
     502         [ #  # ]:           0 :     computeHash.Finalize(computedHash.data());
     503                 :           0 :     return computedHash;
     504                 :           0 : }
     505                 :             : 
     506                 :       16972 : void TorController::authchallenge_cb(TorControlConnection& _conn, const TorControlReply& reply)
     507                 :             : {
     508         [ +  + ]:       16972 :     if (reply.code == 250) {
     509         [ -  + ]:       16661 :         LogDebug(BCLog::TOR, "SAFECOOKIE authentication challenge successful\n");
     510                 :       16661 :         std::pair<std::string,std::string> l = SplitTorReplyLine(reply.lines[0]);
     511         [ +  + ]:       16661 :         if (l.first == "AUTHCHALLENGE") {
     512         [ +  - ]:        2247 :             std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
     513         [ +  + ]:        2247 :             if (m.empty()) {
     514   [ +  -  +  - ]:         486 :                 LogPrintf("tor: Error parsing AUTHCHALLENGE parameters: %s\n", SanitizeString(l.second));
     515                 :         486 :                 return;
     516                 :             :             }
     517   [ +  -  +  -  :        1761 :             std::vector<uint8_t> serverHash = ParseHex(m["SERVERHASH"]);
                   +  - ]
     518   [ +  -  +  -  :        1761 :             std::vector<uint8_t> serverNonce = ParseHex(m["SERVERNONCE"]);
                   +  - ]
     519   [ +  -  -  +  :        1761 :             LogDebug(BCLog::TOR, "AUTHCHALLENGE ServerHash %s ServerNonce %s\n", HexStr(serverHash), HexStr(serverNonce));
          -  -  -  -  -  
                      - ]
     520         [ +  - ]:        1761 :             if (serverNonce.size() != 32) {
     521         [ +  - ]:        1761 :                 LogPrintf("tor: ServerNonce is not 32 bytes, as required by spec\n");
     522                 :             :                 return;
     523                 :             :             }
     524                 :             : 
     525         [ #  # ]:           0 :             std::vector<uint8_t> computedServerHash = ComputeResponse(TOR_SAFE_SERVERKEY, cookie, clientNonce, serverNonce);
     526         [ #  # ]:           0 :             if (computedServerHash != serverHash) {
     527   [ #  #  #  #  :           0 :                 LogPrintf("tor: ServerHash %s does not match expected ServerHash %s\n", HexStr(serverHash), HexStr(computedServerHash));
                   #  # ]
     528                 :           0 :                 return;
     529                 :             :             }
     530                 :             : 
     531         [ #  # ]:           0 :             std::vector<uint8_t> computedClientHash = ComputeResponse(TOR_SAFE_CLIENTKEY, cookie, clientNonce, serverNonce);
     532   [ #  #  #  #  :           0 :             _conn.Command("AUTHENTICATE " + HexStr(computedClientHash), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
             #  #  #  # ]
     533                 :        4008 :         } else {
     534         [ +  - ]:       14414 :             LogPrintf("tor: Invalid reply to AUTHCHALLENGE\n");
     535                 :             :         }
     536                 :       16661 :     } else {
     537                 :         311 :         LogPrintf("tor: SAFECOOKIE authentication challenge failed\n");
     538                 :             :     }
     539                 :             : }
     540                 :             : 
     541                 :       61478 : void TorController::protocolinfo_cb(TorControlConnection& _conn, const TorControlReply& reply)
     542                 :             : {
     543         [ +  + ]:       61478 :     if (reply.code == 250) {
     544                 :       17169 :         std::set<std::string> methods;
     545                 :       17169 :         std::string cookiefile;
     546                 :             :         /*
     547                 :             :          * 250-AUTH METHODS=COOKIE,SAFECOOKIE COOKIEFILE="/home/x/.tor/control_auth_cookie"
     548                 :             :          * 250-AUTH METHODS=NULL
     549                 :             :          * 250-AUTH METHODS=HASHEDPASSWORD
     550                 :             :          */
     551         [ +  + ]:      129688 :         for (const std::string &s : reply.lines) {
     552         [ +  - ]:      112519 :             std::pair<std::string,std::string> l = SplitTorReplyLine(s);
     553         [ +  + ]:      112519 :             if (l.first == "AUTH") {
     554         [ +  - ]:       20582 :                 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
     555         [ +  - ]:       20582 :                 std::map<std::string,std::string>::iterator i;
     556   [ +  -  +  + ]:       41164 :                 if ((i = m.find("METHODS")) != m.end()) {
     557         [ +  - ]:       17322 :                     std::vector<std::string> m_vec = SplitString(i->second, ',');
     558         [ +  - ]:       34644 :                     methods = std::set<std::string>(m_vec.begin(), m_vec.end());
     559                 :       17322 :                 }
     560   [ +  -  +  + ]:       41164 :                 if ((i = m.find("COOKIEFILE")) != m.end())
     561         [ +  - ]:       20952 :                     cookiefile = i->second;
     562         [ +  + ]:      112519 :             } else if (l.first == "VERSION") {
     563         [ +  - ]:        1663 :                 std::map<std::string,std::string> m = ParseTorReplyMapping(l.second);
     564         [ +  - ]:        1663 :                 std::map<std::string,std::string>::iterator i;
     565   [ +  -  +  + ]:        3326 :                 if ((i = m.find("Tor")) != m.end()) {
     566   [ +  -  -  +  :        1240 :                     LogDebug(BCLog::TOR, "Connected to Tor version %s\n", i->second);
                   -  - ]
     567                 :             :                 }
     568                 :        1663 :             }
     569                 :      112519 :         }
     570         [ +  + ]:       25996 :         for (const std::string &s : methods) {
     571   [ +  -  -  +  :        8827 :             LogDebug(BCLog::TOR, "Supported authentication method: %s\n", s);
                   -  - ]
     572                 :             :         }
     573                 :             :         // Prefer NULL, otherwise SAFECOOKIE. If a password is provided, use HASHEDPASSWORD
     574                 :             :         /* Authentication:
     575                 :             :          *   cookie:   hex-encoded ~/.tor/control_auth_cookie
     576                 :             :          *   password: "password"
     577                 :             :          */
     578   [ +  -  +  -  :       34338 :         std::string torpassword = gArgs.GetArg("-torpassword", "");
                   +  - ]
     579         [ -  + ]:       17169 :         if (!torpassword.empty()) {
     580   [ #  #  #  # ]:           0 :             if (methods.count("HASHEDPASSWORD")) {
     581   [ #  #  #  #  :           0 :                 LogDebug(BCLog::TOR, "Using HASHEDPASSWORD authentication\n");
                   #  # ]
     582   [ #  #  #  #  :           0 :                 ReplaceAll(torpassword, "\"", "\\\"");
                   #  # ]
     583   [ #  #  #  #  :           0 :                 _conn.Command("AUTHENTICATE \"" + torpassword + "\"", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
                   #  # ]
     584                 :             :             } else {
     585         [ #  # ]:           0 :                 LogPrintf("tor: Password provided with -torpassword, but HASHEDPASSWORD authentication is not available\n");
     586                 :             :             }
     587   [ +  -  -  + ]:       17169 :         } else if (methods.count("NULL")) {
     588   [ #  #  #  #  :           0 :             LogDebug(BCLog::TOR, "Using NULL authentication\n");
                   #  # ]
     589   [ #  #  #  #  :           0 :             _conn.Command("AUTHENTICATE", std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
                   #  # ]
     590   [ +  -  -  + ]:       17169 :         } else if (methods.count("SAFECOOKIE")) {
     591                 :             :             // Cookie: hexdump -e '32/1 "%02x""\n"'  ~/.tor/control_auth_cookie
     592   [ #  #  #  #  :           0 :             LogDebug(BCLog::TOR, "Using SAFECOOKIE authentication, reading cookie authentication from %s\n", cookiefile);
                   #  # ]
     593   [ #  #  #  # ]:           0 :             std::pair<bool,std::string> status_cookie = ReadBinaryFile(fs::PathFromString(cookiefile), TOR_COOKIE_SIZE);
     594   [ #  #  #  # ]:           0 :             if (status_cookie.first && status_cookie.second.size() == TOR_COOKIE_SIZE) {
     595                 :             :                 // _conn.Command("AUTHENTICATE " + HexStr(status_cookie.second), std::bind(&TorController::auth_cb, this, std::placeholders::_1, std::placeholders::_2));
     596   [ #  #  #  # ]:           0 :                 cookie = std::vector<uint8_t>(status_cookie.second.begin(), status_cookie.second.end());
     597         [ #  # ]:           0 :                 clientNonce = std::vector<uint8_t>(TOR_NONCE_SIZE, 0);
     598                 :           0 :                 GetRandBytes(clientNonce);
     599   [ #  #  #  #  :           0 :                 _conn.Command("AUTHCHALLENGE SAFECOOKIE " + HexStr(clientNonce), std::bind(&TorController::authchallenge_cb, this, std::placeholders::_1, std::placeholders::_2));
             #  #  #  # ]
     600                 :             :             } else {
     601         [ #  # ]:           0 :                 if (status_cookie.first) {
     602         [ #  # ]:           0 :                     LogPrintf("tor: Authentication cookie %s is not exactly %i bytes, as is required by the spec\n", cookiefile, TOR_COOKIE_SIZE);
     603                 :             :                 } else {
     604         [ #  # ]:           0 :                     LogPrintf("tor: Authentication cookie %s could not be opened (check permissions)\n", cookiefile);
     605                 :             :                 }
     606                 :             :             }
     607   [ +  -  -  + ]:       17169 :         } else if (methods.count("HASHEDPASSWORD")) {
     608         [ #  # ]:           0 :             LogPrintf("tor: The only supported authentication mechanism left is password, but no password provided with -torpassword\n");
     609                 :             :         } else {
     610         [ +  - ]:       17169 :             LogPrintf("tor: No supported authentication method\n");
     611                 :             :         }
     612                 :       17169 :     } else {
     613                 :       44309 :         LogPrintf("tor: Requesting protocol info failed\n");
     614                 :             :     }
     615                 :       61478 : }
     616                 :             : 
     617                 :           0 : void TorController::connected_cb(TorControlConnection& _conn)
     618                 :             : {
     619                 :           0 :     reconnect_timeout = RECONNECT_TIMEOUT_START;
     620                 :             :     // First send a PROTOCOLINFO command to figure out what authentication is expected
     621   [ #  #  #  #  :           0 :     if (!_conn.Command("PROTOCOLINFO 1", std::bind(&TorController::protocolinfo_cb, this, std::placeholders::_1, std::placeholders::_2)))
                   #  # ]
     622                 :           0 :         LogPrintf("tor: Error sending initial protocolinfo command\n");
     623                 :           0 : }
     624                 :             : 
     625                 :           0 : void TorController::disconnected_cb(TorControlConnection& _conn)
     626                 :             : {
     627                 :             :     // Stop advertising service when disconnected
     628         [ #  # ]:           0 :     if (service.IsValid())
     629                 :           0 :         RemoveLocal(service);
     630                 :           0 :     service = CService();
     631         [ #  # ]:           0 :     if (!reconnect)
     632                 :             :         return;
     633                 :             : 
     634         [ #  # ]:           0 :     LogDebug(BCLog::TOR, "Not connected to Tor control port %s, trying to reconnect\n", m_tor_control_center);
     635                 :             : 
     636                 :             :     // Single-shot timer for reconnect. Use exponential backoff.
     637                 :           0 :     struct timeval time = MillisToTimeval(int64_t(reconnect_timeout * 1000.0));
     638         [ #  # ]:           0 :     if (reconnect_ev)
     639                 :           0 :         event_add(reconnect_ev, &time);
     640                 :           0 :     reconnect_timeout *= RECONNECT_TIMEOUT_EXP;
     641                 :             : }
     642                 :             : 
     643                 :           0 : void TorController::Reconnect()
     644                 :             : {
     645                 :             :     /* Try to reconnect and reestablish if we get booted - for example, Tor
     646                 :             :      * may be restarting.
     647                 :             :      */
     648   [ #  #  #  #  :           0 :     if (!conn.Connect(m_tor_control_center, std::bind(&TorController::connected_cb, this, std::placeholders::_1),
                   #  # ]
     649                 :           0 :          std::bind(&TorController::disconnected_cb, this, std::placeholders::_1) )) {
     650                 :           0 :         LogPrintf("tor: Re-initiating connection to Tor control port %s failed\n", m_tor_control_center);
     651                 :             :     }
     652                 :           0 : }
     653                 :             : 
     654                 :       24618 : fs::path TorController::GetPrivateKeyFile()
     655                 :             : {
     656         [ +  - ]:       73854 :     return gArgs.GetDataDirNet() / "onion_v3_private_key";
     657                 :             : }
     658                 :             : 
     659                 :           0 : void TorController::reconnect_cb(evutil_socket_t fd, short what, void *arg)
     660                 :             : {
     661                 :           0 :     TorController *self = static_cast<TorController*>(arg);
     662                 :           0 :     self->Reconnect();
     663                 :           0 : }
     664                 :             : 
     665                 :             : /****** Thread ********/
     666                 :             : static struct event_base *gBase;
     667                 :             : static std::thread torControlThread;
     668                 :             : 
     669                 :           0 : static void TorControlThread(CService onion_service_target)
     670                 :             : {
     671   [ #  #  #  # ]:           0 :     TorController ctrl(gBase, gArgs.GetArg("-torcontrol", DEFAULT_TOR_CONTROL), onion_service_target);
     672                 :             : 
     673         [ #  # ]:           0 :     event_base_dispatch(gBase);
     674                 :           0 : }
     675                 :             : 
     676                 :           0 : void StartTorControl(CService onion_service_target)
     677                 :             : {
     678         [ #  # ]:           0 :     assert(!gBase);
     679                 :             : #ifdef WIN32
     680                 :             :     evthread_use_windows_threads();
     681                 :             : #else
     682                 :           0 :     evthread_use_pthreads();
     683                 :             : #endif
     684                 :           0 :     gBase = event_base_new();
     685         [ #  # ]:           0 :     if (!gBase) {
     686                 :           0 :         LogPrintf("tor: Unable to create event_base\n");
     687                 :           0 :         return;
     688                 :             :     }
     689                 :             : 
     690         [ #  # ]:           0 :     torControlThread = std::thread(&util::TraceThread, "torcontrol", [onion_service_target] {
     691         [ #  # ]:           0 :         TorControlThread(onion_service_target);
     692         [ #  # ]:           0 :     });
     693                 :             : }
     694                 :             : 
     695                 :           0 : void InterruptTorControl()
     696                 :             : {
     697         [ #  # ]:           0 :     if (gBase) {
     698                 :           0 :         LogPrintf("tor: Thread interrupt\n");
     699                 :           0 :         event_base_once(gBase, -1, EV_TIMEOUT, [](evutil_socket_t, short, void*) {
     700                 :             :             event_base_loopbreak(gBase);
     701                 :             :         }, nullptr, nullptr);
     702                 :             :     }
     703                 :           0 : }
     704                 :             : 
     705                 :           0 : void StopTorControl()
     706                 :             : {
     707         [ #  # ]:           0 :     if (gBase) {
     708                 :           0 :         torControlThread.join();
     709                 :           0 :         event_base_free(gBase);
     710                 :           0 :         gBase = nullptr;
     711                 :             :     }
     712                 :           0 : }
     713                 :             : 
     714                 :           0 : CService DefaultOnionServiceTarget()
     715                 :             : {
     716                 :           0 :     struct in_addr onion_service_target;
     717                 :           0 :     onion_service_target.s_addr = htonl(INADDR_LOOPBACK);
     718                 :           0 :     return {onion_service_target, BaseParams().OnionServiceTargetPort()};
     719                 :             : }
        

Generated by: LCOV version 2.0-1