LCOV - code coverage report
Current view: top level - src - torcontrol.cpp (source / functions) Hit Total Coverage
Test: total_coverage.info Lines: 72 392 18.4 %
Date: 2020-09-26 01:30:44 Functions: 8 43 18.6 %

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

Generated by: LCOV version 1.15