Coverage Report

Created: 2025-02-21 14:36

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