fuzz coverage

Coverage Report

Created: 2026-04-24 13:48

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