Coverage Report

Created: 2026-10-07 20:26

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