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