LCOV - code coverage report
Current view: top level - src - torcontrol.cpp (source / functions) Coverage Total Hit
Test: total_coverage.info Lines: 41.4 % 379 157
Test Date: 2025-03-28 05:06:44 Functions: 60.7 % 28 17
Branches: 20.6 % 650 134

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

Generated by: LCOV version 2.0-1