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