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