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