Branch data Line data Source code
1 : : // Copyright (c) 2020-2022 The Bitcoin Core developers
2 : : // Distributed under the MIT software license, see the accompanying
3 : : // file COPYING or http://www.opensource.org/licenses/mit-license.php.
4 : :
5 : : #include <chainparams.h>
6 : : #include <common/args.h>
7 : : #include <compat/compat.h>
8 : : #include <compat/endian.h>
9 : : #include <crypto/sha256.h>
10 : : #include <i2p.h>
11 : : #include <logging.h>
12 : : #include <netaddress.h>
13 : : #include <netbase.h>
14 : : #include <random.h>
15 : : #include <sync.h>
16 : : #include <tinyformat.h>
17 : : #include <util/fs.h>
18 : : #include <util/readwritefile.h>
19 : : #include <util/sock.h>
20 : : #include <util/spanparsing.h>
21 : : #include <util/strencodings.h>
22 : : #include <util/threadinterrupt.h>
23 : :
24 : : #include <chrono>
25 : : #include <memory>
26 : : #include <stdexcept>
27 : : #include <string>
28 : :
29 : : namespace i2p {
30 : :
31 : : /**
32 : : * Swap Standard Base64 <-> I2P Base64.
33 : : * Standard Base64 uses `+` and `/` as last two characters of its alphabet.
34 : : * I2P Base64 uses `-` and `~` respectively.
35 : : * So it is easy to detect in which one is the input and convert to the other.
36 : : * @param[in] from Input to convert.
37 : : * @return converted `from`
38 : : */
39 : 0 : static std::string SwapBase64(const std::string& from)
40 : : {
41 : 0 : std::string to;
42 [ # # ]: 0 : to.resize(from.size());
43 [ # # ]: 0 : for (size_t i = 0; i < from.size(); ++i) {
44 [ # # # # : 0 : switch (from[i]) {
# ]
45 : : case '-':
46 [ # # ]: 0 : to[i] = '+';
47 : 0 : break;
48 : : case '~':
49 [ # # ]: 0 : to[i] = '/';
50 : 0 : break;
51 : : case '+':
52 [ # # ]: 0 : to[i] = '-';
53 : 0 : break;
54 : : case '/':
55 [ # # ]: 0 : to[i] = '~';
56 : 0 : break;
57 : : default:
58 [ # # ]: 0 : to[i] = from[i];
59 : 0 : break;
60 : : }
61 : 0 : }
62 : 0 : return to;
63 [ # # ]: 0 : }
64 : :
65 : : /**
66 : : * Decode an I2P-style Base64 string.
67 : : * @param[in] i2p_b64 I2P-style Base64 string.
68 : : * @return decoded `i2p_b64`
69 : : * @throw std::runtime_error if decoding fails
70 : : */
71 : 0 : static Binary DecodeI2PBase64(const std::string& i2p_b64)
72 : : {
73 : 0 : const std::string& std_b64 = SwapBase64(i2p_b64);
74 [ # # ]: 1 : auto decoded = DecodeBase64(std_b64);
75 [ # # ]: 0 : if (!decoded) {
76 [ # # # # : 0 : throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
# # # # ]
77 : : }
78 : 0 : return std::move(*decoded);
79 : 0 : }
80 : :
81 : : /**
82 : : * Derive the .b32.i2p address of an I2P destination (binary).
83 : : * @param[in] dest I2P destination.
84 : : * @return the address that corresponds to `dest`
85 : : * @throw std::runtime_error if conversion fails
86 : : */
87 : 0 : static CNetAddr DestBinToAddr(const Binary& dest)
88 : : {
89 : 0 : CSHA256 hasher;
90 : 0 : hasher.Write(dest.data(), dest.size());
91 : 0 : unsigned char hash[CSHA256::OUTPUT_SIZE];
92 : 0 : hasher.Finalize(hash);
93 : :
94 : 0 : CNetAddr addr;
95 [ # # # # ]: 0 : const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p";
96 [ # # # # ]: 0 : if (!addr.SetSpecial(addr_str)) {
97 [ # # # # : 0 : throw std::runtime_error(strprintf("Cannot parse I2P address: \"%s\"", addr_str));
# # # # ]
98 : : }
99 : :
100 : 0 : return addr;
101 [ # # ]: 0 : }
102 : :
103 : : /**
104 : : * Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
105 : : * @param[in] dest I2P destination.
106 : : * @return the address that corresponds to `dest`
107 : : * @throw std::runtime_error if conversion fails
108 : : */
109 : 0 : static CNetAddr DestB64ToAddr(const std::string& dest)
110 : : {
111 : 0 : const Binary& decoded = DecodeI2PBase64(dest);
112 [ # # ]: 0 : return DestBinToAddr(decoded);
113 : 0 : }
114 : :
115 : : namespace sam {
116 : :
117 [ # # ]: 0 : Session::Session(const fs::path& private_key_file,
118 : : const Proxy& control_host,
119 : : CThreadInterrupt* interrupt)
120 : 0 : : m_private_key_file{private_key_file},
121 [ # # ]: 0 : m_control_host{control_host},
122 : 0 : m_interrupt{interrupt},
123 : 0 : m_transient{false}
124 : : {
125 : 0 : }
126 : :
127 [ # # ]: 0 : Session::Session(const Proxy& control_host, CThreadInterrupt* interrupt)
128 [ # # ]: 0 : : m_control_host{control_host},
129 : 0 : m_interrupt{interrupt},
130 : 0 : m_transient{true}
131 : : {
132 : 0 : }
133 : :
134 : 0 : Session::~Session()
135 : : {
136 [ # # # # ]: 0 : LOCK(m_mutex);
137 [ # # ]: 0 : Disconnect();
138 : 0 : }
139 : :
140 : 0 : bool Session::Listen(Connection& conn)
141 : : {
142 : : try {
143 [ # # # # ]: 0 : LOCK(m_mutex);
144 [ # # ]: 0 : CreateIfNotCreatedAlready();
145 [ # # ]: 0 : conn.me = m_my_addr;
146 [ # # ]: 0 : conn.sock = StreamAccept();
147 : 0 : return true;
148 [ # # ]: 0 : } catch (const std::runtime_error& e) {
149 [ # # # # ]: 0 : Log("Error listening: %s", e.what());
150 [ # # ]: 0 : CheckControlSock();
151 [ # # ]: 0 : }
152 : 0 : return false;
153 : 0 : }
154 : :
155 : 0 : bool Session::Accept(Connection& conn)
156 : : {
157 : 0 : AssertLockNotHeld(m_mutex);
158 : :
159 : 0 : std::string errmsg;
160 : 0 : bool disconnect{false};
161 : :
162 [ # # # # ]: 0 : while (!*m_interrupt) {
163 : 0 : Sock::Event occurred;
164 [ # # # # : 0 : if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
# # ]
165 [ # # ]: 0 : errmsg = "wait on socket failed";
166 : 0 : break;
167 : : }
168 : :
169 [ # # ]: 0 : if (occurred == 0) {
170 : : // Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
171 : 0 : continue;
172 : : }
173 : :
174 : 0 : std::string peer_dest;
175 : : try {
176 [ # # # # ]: 0 : peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
177 [ # # ]: 0 : } catch (const std::runtime_error& e) {
178 [ # # ]: 0 : errmsg = e.what();
179 : : break;
180 [ # # # # ]: 0 : }
181 : :
182 [ # # ]: 0 : CNetAddr peer_addr;
183 : : try {
184 [ # # ]: 0 : peer_addr = DestB64ToAddr(peer_dest);
185 [ # # ]: 0 : } catch (const std::runtime_error& e) {
186 : : // The I2P router is expected to send the Base64 of the connecting peer,
187 : : // but it may happen that something like this is sent instead:
188 : : // STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"
189 : : // In that case consider the session damaged and close it right away,
190 : : // even if the control socket is alive.
191 [ # # ]: 0 : if (peer_dest.find("RESULT=I2P_ERROR") != std::string::npos) {
192 [ # # ]: 0 : errmsg = strprintf("unexpected reply that hints the session is unusable: %s", peer_dest);
193 : 0 : disconnect = true;
194 : 0 : } else {
195 [ # # ]: 0 : errmsg = e.what();
196 : : }
197 : : break;
198 [ # # # # ]: 0 : }
199 : :
200 [ # # ]: 0 : conn.peer = CService(peer_addr, I2P_SAM31_PORT);
201 : :
202 : 0 : return true;
203 [ # # # ]: 0 : }
204 : :
205 [ # # # # ]: 0 : Log("Error accepting%s: %s", disconnect ? " (will close the session)" : "", errmsg);
206 [ # # ]: 0 : if (disconnect) {
207 [ # # # # ]: 0 : LOCK(m_mutex);
208 [ # # ]: 0 : Disconnect();
209 : 0 : } else {
210 [ # # ]: 0 : CheckControlSock();
211 : : }
212 : 0 : return false;
213 : 0 : }
214 : :
215 : 0 : bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)
216 : : {
217 : : // Refuse connecting to arbitrary ports. We don't specify any destination port to the SAM proxy
218 : : // when connecting (SAM 3.1 does not use ports) and it forces/defaults it to I2P_SAM31_PORT.
219 [ # # ]: 0 : if (to.GetPort() != I2P_SAM31_PORT) {
220 [ # # # # : 0 : Log("Error connecting to %s, connection refused due to arbitrary port %s", to.ToStringAddrPort(), to.GetPort());
# # # # ]
221 : 0 : proxy_error = false;
222 : 0 : return false;
223 : : }
224 : :
225 : 0 : proxy_error = true;
226 : :
227 : 0 : std::string session_id;
228 : 0 : std::unique_ptr<Sock> sock;
229 [ # # ]: 0 : conn.peer = to;
230 : :
231 : : try {
232 : : {
233 [ # # # # ]: 0 : LOCK(m_mutex);
234 [ # # ]: 0 : CreateIfNotCreatedAlready();
235 [ # # ]: 0 : session_id = m_session_id;
236 [ # # ]: 0 : conn.me = m_my_addr;
237 [ # # ]: 0 : sock = Hello();
238 : 0 : }
239 : :
240 : 0 : const Reply& lookup_reply =
241 [ # # # # : 0 : SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringAddr()));
# # ]
242 : :
243 [ # # # # ]: 0 : const std::string& dest = lookup_reply.Get("VALUE");
244 : :
245 [ # # ]: 0 : const Reply& connect_reply = SendRequestAndGetReply(
246 [ # # ]: 0 : *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest),
247 : : false);
248 : :
249 [ # # # # ]: 0 : const std::string& result = connect_reply.Get("RESULT");
250 : :
251 [ # # # # ]: 0 : if (result == "OK") {
252 : 0 : conn.sock = std::move(sock);
253 : 0 : return true;
254 : : }
255 : :
256 [ # # # # ]: 0 : if (result == "INVALID_ID") {
257 [ # # # # ]: 0 : LOCK(m_mutex);
258 [ # # ]: 0 : Disconnect();
259 [ # # ]: 0 : throw std::runtime_error("Invalid session id");
260 : 0 : }
261 : :
262 [ # # # # : 0 : if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
# # # # ]
263 : 0 : proxy_error = false;
264 : 0 : }
265 : :
266 [ # # # # : 0 : throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
# # ]
267 [ # # ]: 0 : } catch (const std::runtime_error& e) {
268 [ # # # # : 0 : Log("Error connecting to %s: %s", to.ToStringAddrPort(), e.what());
# # ]
269 [ # # ]: 0 : CheckControlSock();
270 : 0 : return false;
271 [ # # # # ]: 0 : }
272 : 0 : }
273 : :
274 : : // Private methods
275 : :
276 : 0 : std::string Session::Reply::Get(const std::string& key) const
277 : : {
278 : 0 : const auto& pos = keys.find(key);
279 [ # # # # ]: 0 : if (pos == keys.end() || !pos->second.has_value()) {
280 [ # # # # : 0 : throw std::runtime_error(
# # ]
281 [ # # ]: 0 : strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full));
282 : : }
283 : 0 : return pos->second.value();
284 : 0 : }
285 : :
286 : : template <typename... Args>
287 : 0 : void Session::Log(const std::string& fmt, const Args&... args) const
288 : : {
289 [ # # # # : 0 : LogPrint(BCLog::I2P, "%s\n", tfm::format(fmt, args...));
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# ]
290 : 0 : }
291 : :
292 : 0 : Session::Reply Session::SendRequestAndGetReply(const Sock& sock,
293 : : const std::string& request,
294 : : bool check_result_ok) const
295 : : {
296 [ # # # # : 0 : sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
# # ]
297 : :
298 : 0 : Reply reply;
299 : :
300 : : // Don't log the full "SESSION CREATE ..." because it contains our private key.
301 [ # # # # : 0 : reply.request = request.substr(0, 14) == "SESSION CREATE" ? "SESSION CREATE ..." : request;
# # # # #
# # # # #
# # # # #
# ]
302 : :
303 : : // It could take a few minutes for the I2P router to reply as it is querying the I2P network
304 : : // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking
305 : : // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is
306 : : // signaled.
307 : : static constexpr auto recv_timeout = 3min;
308 : :
309 [ # # # # ]: 0 : reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);
310 : :
311 [ # # # # : 0 : for (const auto& kv : spanparsing::Split(reply.full, ' ')) {
# # ]
312 [ # # ]: 0 : const auto& pos = std::find(kv.begin(), kv.end(), '=');
313 [ # # ]: 0 : if (pos != kv.end()) {
314 [ # # # # : 0 : reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});
# # ]
315 : 0 : } else {
316 [ # # # # ]: 0 : reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);
317 : : }
318 : 0 : }
319 : :
320 [ # # # # : 0 : if (check_result_ok && reply.Get("RESULT") != "OK") {
# # # # #
# # # # #
# # # # #
# # # # #
# # # # #
# # # #
# ]
321 [ # # # # : 0 : throw std::runtime_error(
# # ]
322 [ # # ]: 0 : strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full));
323 : : }
324 : :
325 : 0 : return reply;
326 [ # # ]: 0 : }
327 : :
328 : 0 : std::unique_ptr<Sock> Session::Hello() const
329 : : {
330 : 0 : auto sock = m_control_host.Connect();
331 : :
332 [ # # ]: 0 : if (!sock) {
333 [ # # # # : 0 : throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToString()));
# # # # #
# ]
334 : : }
335 : :
336 [ # # # # ]: 0 : SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1");
337 : :
338 : 0 : return sock;
339 [ # # ]: 0 : }
340 : :
341 : 0 : void Session::CheckControlSock()
342 : : {
343 : 0 : LOCK(m_mutex);
344 : :
345 : 0 : std::string errmsg;
346 [ # # # # : 0 : if (m_control_sock && !m_control_sock->IsConnected(errmsg)) {
# # ]
347 [ # # # # ]: 0 : Log("Control socket error: %s", errmsg);
348 [ # # ]: 0 : Disconnect();
349 : 0 : }
350 : 0 : }
351 : :
352 : 0 : void Session::DestGenerate(const Sock& sock)
353 : : {
354 : : // https://geti2p.net/spec/common-structures#key-certificates
355 : : // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations".
356 : : // Use "7" because i2pd <2.24.0 does not recognize the textual form.
357 : : // If SIGNATURE_TYPE is not specified, then the default one is DSA_SHA1.
358 [ # # # # ]: 0 : const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
359 : :
360 [ # # # # : 0 : m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
# # ]
361 : 0 : }
362 : :
363 : 0 : void Session::GenerateAndSavePrivateKey(const Sock& sock)
364 : : {
365 : 0 : DestGenerate(sock);
366 : :
367 : : // umask is set to 0077 in common/system.cpp, which is ok.
368 [ # # # # ]: 0 : if (!WriteBinaryFile(m_private_key_file,
369 [ # # ]: 0 : std::string(m_private_key.begin(), m_private_key.end()))) {
370 [ # # # # : 0 : throw std::runtime_error(
# # ]
371 [ # # # # : 0 : strprintf("Cannot save I2P private key to %s", fs::quoted(fs::PathToString(m_private_key_file))));
# # ]
372 : : }
373 : 0 : }
374 : :
375 : 0 : Binary Session::MyDestination() const
376 : : {
377 : : // From https://geti2p.net/spec/common-structures#destination:
378 : : // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be
379 : : // non-zero"
380 : : static constexpr size_t DEST_LEN_BASE = 387;
381 : : static constexpr size_t CERT_LEN_POS = 385;
382 : :
383 : 0 : uint16_t cert_len;
384 : :
385 [ # # ]: 0 : if (m_private_key.size() < CERT_LEN_POS + sizeof(cert_len)) {
386 [ # # # # : 0 : throw std::runtime_error(strprintf("The private key is too short (%d < %d)",
# # # # ]
387 : 0 : m_private_key.size(),
388 : 0 : CERT_LEN_POS + sizeof(cert_len)));
389 : : }
390 : :
391 : 0 : memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
392 : 0 : cert_len = be16toh_internal(cert_len);
393 : :
394 : 0 : const size_t dest_len = DEST_LEN_BASE + cert_len;
395 : :
396 [ # # ]: 0 : if (dest_len > m_private_key.size()) {
397 [ # # # # : 0 : throw std::runtime_error(strprintf("Certificate length (%d) designates that the private key should "
# # # # ]
398 : : "be %d bytes, but it is only %d bytes",
399 : : cert_len,
400 : : dest_len,
401 : 0 : m_private_key.size()));
402 : : }
403 : :
404 [ # # ]: 0 : return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
405 : 0 : }
406 : :
407 : 0 : void Session::CreateIfNotCreatedAlready()
408 : : {
409 : 0 : std::string errmsg;
410 [ # # # # : 0 : if (m_control_sock && m_control_sock->IsConnected(errmsg)) {
# # ]
411 : 0 : return;
412 : : }
413 : :
414 : 0 : const auto session_type = m_transient ? "transient" : "persistent";
415 [ # # # # ]: 0 : const auto session_id = GetRandHash().GetHex().substr(0, 10); // full is overkill, too verbose in the logs
416 : :
417 [ # # # # : 0 : Log("Creating %s SAM session %s with %s", session_type, session_id, m_control_host.ToString());
# # ]
418 : :
419 [ # # ]: 0 : auto sock = Hello();
420 : :
421 [ # # ]: 0 : if (m_transient) {
422 : : // The destination (private key) is generated upon session creation and returned
423 : : // in the reply in DESTINATION=.
424 [ # # ]: 0 : const Reply& reply = SendRequestAndGetReply(
425 : 0 : *sock,
426 [ # # ]: 0 : strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=TRANSIENT SIGNATURE_TYPE=7 "
427 : : "i2cp.leaseSetEncType=4,0 inbound.quantity=1 outbound.quantity=1",
428 : : session_id));
429 : :
430 [ # # # # : 0 : m_private_key = DecodeI2PBase64(reply.Get("DESTINATION"));
# # ]
431 : 0 : } else {
432 : : // Read our persistent destination (private key) from disk or generate
433 : : // one and save it to disk. Then use it when creating the session.
434 [ # # ]: 0 : const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);
435 [ # # ]: 0 : if (read_ok) {
436 [ # # # # : 0 : m_private_key.assign(data.begin(), data.end());
# # ]
437 : 0 : } else {
438 [ # # ]: 0 : GenerateAndSavePrivateKey(*sock);
439 : : }
440 : :
441 [ # # # # : 0 : const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));
# # ]
442 : :
443 [ # # ]: 0 : SendRequestAndGetReply(*sock,
444 [ # # # # ]: 0 : strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s "
445 : : "i2cp.leaseSetEncType=4,0 inbound.quantity=3 outbound.quantity=3",
446 : : session_id,
447 : 0 : private_key_b64));
448 : 0 : }
449 : :
450 [ # # # # : 0 : m_my_addr = CService(DestBinToAddr(MyDestination()), I2P_SAM31_PORT);
# # ]
451 [ # # ]: 0 : m_session_id = session_id;
452 : 0 : m_control_sock = std::move(sock);
453 : :
454 [ # # # # ]: 0 : Log("%s SAM session %s created, my address=%s",
455 [ # # # # ]: 0 : Capitalize(session_type),
456 : 0 : m_session_id,
457 [ # # ]: 0 : m_my_addr.ToStringAddrPort());
458 [ # # ]: 0 : }
459 : :
460 : 0 : std::unique_ptr<Sock> Session::StreamAccept()
461 : : {
462 : 0 : auto sock = Hello();
463 : :
464 [ # # ]: 0 : const Reply& reply = SendRequestAndGetReply(
465 [ # # ]: 0 : *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false);
466 : :
467 [ # # # # ]: 0 : const std::string& result = reply.Get("RESULT");
468 : :
469 [ # # # # ]: 0 : if (result == "OK") {
470 : 0 : return sock;
471 : : }
472 : :
473 [ # # # # ]: 0 : if (result == "INVALID_ID") {
474 : : // If our session id is invalid, then force session re-creation on next usage.
475 [ # # ]: 0 : Disconnect();
476 : 0 : }
477 : :
478 [ # # # # : 0 : throw std::runtime_error(strprintf("\"%s\"", reply.full));
# # # # ]
479 [ # # ]: 0 : }
480 : :
481 : 0 : void Session::Disconnect()
482 : : {
483 [ # # ]: 0 : if (m_control_sock) {
484 [ # # ]: 0 : if (m_session_id.empty()) {
485 [ # # # # ]: 0 : Log("Destroying incomplete SAM session");
486 : 0 : } else {
487 [ # # # # ]: 0 : Log("Destroying SAM session %s", m_session_id);
488 : : }
489 : 0 : m_control_sock.reset();
490 : 0 : }
491 : 0 : m_session_id.clear();
492 : 0 : }
493 : : } // namespace sam
494 : : } // namespace i2p
|