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