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