LCOV - code coverage report
Current view: top level - src - torcontrol.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 63 346 18.2 %
Date: 2025-02-23 09:33:43 Functions: 4 27 14.8 %

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

Generated by: LCOV version 1.14