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