Coverage Report

Created: 2026-11-13 17:38

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