Bitcoin Core  31.0.0
P2P Digital Currency
i2p.cpp
Go to the documentation of this file.
1 // Copyright (c) 2020-present 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 <script/parsing.h>
16 #include <sync.h>
17 #include <tinyformat.h>
18 #include <util/fs.h>
19 #include <util/readwritefile.h>
20 #include <util/sock.h>
21 #include <util/strencodings.h>
22 #include <util/threadinterrupt.h>
23 
24 #include <chrono>
25 #include <memory>
26 #include <ranges>
27 #include <stdexcept>
28 #include <string>
29 
30 using util::Split;
31 
32 namespace i2p {
33 
42 static std::string SwapBase64(const std::string& from)
43 {
44  std::string to;
45  to.resize(from.size());
46  for (size_t i = 0; i < from.size(); ++i) {
47  switch (from[i]) {
48  case '-':
49  to[i] = '+';
50  break;
51  case '~':
52  to[i] = '/';
53  break;
54  case '+':
55  to[i] = '-';
56  break;
57  case '/':
58  to[i] = '~';
59  break;
60  default:
61  to[i] = from[i];
62  break;
63  }
64  }
65  return to;
66 }
67 
74 static Binary DecodeI2PBase64(const std::string& i2p_b64)
75 {
76  const std::string& std_b64 = SwapBase64(i2p_b64);
77  auto decoded = DecodeBase64(std_b64);
78  if (!decoded) {
79  throw std::runtime_error(strprintf("Cannot decode Base64: \"%s\"", i2p_b64));
80  }
81  return std::move(*decoded);
82 }
83 
90 static CNetAddr DestBinToAddr(const Binary& dest)
91 {
92  CSHA256 hasher;
93  hasher.Write(dest.data(), dest.size());
94  unsigned char hash[CSHA256::OUTPUT_SIZE];
95  hasher.Finalize(hash);
96 
97  CNetAddr addr;
98  const std::string addr_str = EncodeBase32(hash, false) + ".b32.i2p";
99  if (!addr.SetSpecial(addr_str)) {
100  throw std::runtime_error(strprintf("Cannot parse I2P address: \"%s\"", addr_str));
101  }
102 
103  return addr;
104 }
105 
112 static CNetAddr DestB64ToAddr(const std::string& dest)
113 {
114  const Binary& decoded = DecodeI2PBase64(dest);
115  return DestBinToAddr(decoded);
116 }
117 
118 namespace sam {
119 
120 Session::Session(const fs::path& private_key_file,
121  const Proxy& control_host,
122  std::shared_ptr<CThreadInterrupt> interrupt)
123  : m_private_key_file{private_key_file},
124  m_control_host{control_host},
125  m_interrupt{interrupt},
126  m_transient{false}
127 {
128 }
129 
130 Session::Session(const Proxy& control_host, std::shared_ptr<CThreadInterrupt> interrupt)
131  : m_control_host{control_host},
132  m_interrupt{interrupt},
133  m_transient{true}
134 {
135 }
136 
138 {
139  LOCK(m_mutex);
140  Disconnect();
141 }
142 
144 {
145  try {
146  LOCK(m_mutex);
148  conn.me = m_my_addr;
149  conn.sock = StreamAccept();
150  return true;
151  } catch (const std::runtime_error& e) {
152  LogError("Couldn't listen: %s\n", e.what());
154  }
155  return false;
156 }
157 
159 {
161 
162  std::string errmsg;
163  bool disconnect{false};
164 
165  while (!m_interrupt->interrupted()) {
166  Sock::Event occurred;
167  if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
168  errmsg = "wait on socket failed";
169  break;
170  }
171 
172  if (occurred == 0) {
173  // Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
174  continue;
175  }
176 
177  std::string peer_dest;
178  try {
179  peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
180  } catch (const std::runtime_error& e) {
181  errmsg = e.what();
182  break;
183  }
184 
185  CNetAddr peer_addr;
186  try {
187  peer_addr = DestB64ToAddr(peer_dest);
188  } catch (const std::runtime_error& e) {
189  // The I2P router is expected to send the Base64 of the connecting peer,
190  // but it may happen that something like this is sent instead:
191  // STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed"
192  // In that case consider the session damaged and close it right away,
193  // even if the control socket is alive.
194  if (peer_dest.find("RESULT=I2P_ERROR") != std::string::npos) {
195  errmsg = strprintf("unexpected reply that hints the session is unusable: %s", peer_dest);
196  disconnect = true;
197  } else {
198  errmsg = e.what();
199  }
200  break;
201  }
202 
203  conn.peer = CService(peer_addr, I2P_SAM31_PORT);
204 
205  return true;
206  }
207 
208  if (m_interrupt->interrupted()) {
209  LogDebug(BCLog::I2P, "Accept was interrupted\n");
210  } else {
211  LogDebug(BCLog::I2P, "Error accepting%s: %s\n", disconnect ? " (will close the session)" : "", errmsg);
212  }
213  if (disconnect) {
214  LOCK(m_mutex);
215  Disconnect();
216  } else {
218  }
219  return false;
220 }
221 
222 bool Session::Connect(const CService& to, Connection& conn, bool& proxy_error)
223 {
224  // Refuse connecting to arbitrary ports. We don't specify any destination port to the SAM proxy
225  // when connecting (SAM 3.1 does not use ports) and it forces/defaults it to I2P_SAM31_PORT.
226  if (to.GetPort() != I2P_SAM31_PORT) {
227  LogDebug(BCLog::I2P, "Error connecting to %s, connection refused due to arbitrary port %s\n", to.ToStringAddrPort(), to.GetPort());
228  proxy_error = false;
229  return false;
230  }
231 
232  proxy_error = true;
233 
234  std::string session_id;
235  std::unique_ptr<Sock> sock;
236  conn.peer = to;
237 
238  try {
239  {
240  LOCK(m_mutex);
242  session_id = m_session_id;
243  conn.me = m_my_addr;
244  sock = Hello();
245  }
246 
247  const Reply& lookup_reply =
248  SendRequestAndGetReply(*sock, strprintf("NAMING LOOKUP NAME=%s", to.ToStringAddr()));
249 
250  const std::string& dest = lookup_reply.Get("VALUE");
251 
252  const Reply& connect_reply = SendRequestAndGetReply(
253  *sock, strprintf("STREAM CONNECT ID=%s DESTINATION=%s SILENT=false", session_id, dest),
254  false);
255 
256  const std::string& result = connect_reply.Get("RESULT");
257 
258  if (result == "OK") {
259  conn.sock = std::move(sock);
260  return true;
261  }
262 
263  if (result == "INVALID_ID") {
264  LOCK(m_mutex);
265  Disconnect();
266  throw std::runtime_error("Invalid session id");
267  }
268 
269  if (result == "CANT_REACH_PEER" || result == "TIMEOUT") {
270  proxy_error = false;
271  }
272 
273  throw std::runtime_error(strprintf("\"%s\"", connect_reply.full));
274  } catch (const std::runtime_error& e) {
275  LogDebug(BCLog::I2P, "Error connecting to %s: %s\n", to.ToStringAddrPort(), e.what());
277  return false;
278  }
279 }
280 
281 // Private methods
282 
283 std::string Session::Reply::Get(const std::string& key) const
284 {
285  const auto& pos = keys.find(key);
286  if (pos == keys.end() || !pos->second.has_value()) {
287  throw std::runtime_error(
288  strprintf("Missing %s= in the reply to \"%s\": \"%s\"", key, request, full));
289  }
290  return pos->second.value();
291 }
292 
294  const std::string& request,
295  bool check_result_ok) const
296 {
297  sock.SendComplete(request + "\n", MAX_WAIT_FOR_IO, *m_interrupt);
298 
299  Reply reply;
300 
301  // Don't log the full "SESSION CREATE ..." because it contains our private key.
302  reply.request = request.starts_with("SESSION CREATE") ? "SESSION CREATE ..." : request;
303 
304  // It could take a few minutes for the I2P router to reply as it is querying the I2P network
305  // (when doing name lookup, for example). Notice: `RecvUntilTerminator()` is checking
306  // `m_interrupt` more often, so we would not be stuck here for long if `m_interrupt` is
307  // signaled.
308  static constexpr auto recv_timeout = 3min;
309 
310  reply.full = sock.RecvUntilTerminator('\n', recv_timeout, *m_interrupt, MAX_MSG_SIZE);
311 
312  for (const auto& kv : Split(reply.full, ' ')) {
313  const auto pos{std::ranges::find(kv, '=')};
314  if (pos != kv.end()) {
315  reply.keys.emplace(std::string{kv.begin(), pos}, std::string{pos + 1, kv.end()});
316  } else {
317  reply.keys.emplace(std::string{kv.begin(), kv.end()}, std::nullopt);
318  }
319  }
320 
321  if (check_result_ok && reply.Get("RESULT") != "OK") {
322  throw std::runtime_error(
323  strprintf("Unexpected reply to \"%s\": \"%s\"", request, reply.full));
324  }
325 
326  return reply;
327 }
328 
329 std::unique_ptr<Sock> Session::Hello() const
330 {
331  auto sock = m_control_host.Connect();
332 
333  if (!sock) {
334  throw std::runtime_error(strprintf("Cannot connect to %s", m_control_host.ToString()));
335  }
336 
337  SendRequestAndGetReply(*sock, "HELLO VERSION MIN=3.1 MAX=3.1");
338 
339  return sock;
340 }
341 
343 {
344  LOCK(m_mutex);
345 
346  std::string errmsg;
347  if (m_control_sock && !m_control_sock->IsConnected(errmsg)) {
348  LogDebug(BCLog::I2P, "Control socket error: %s\n", errmsg);
349  Disconnect();
350  }
351 }
352 
353 void Session::DestGenerate(const Sock& sock)
354 {
355  // https://geti2p.net/spec/common-structures#key-certificates
356  // "7" or "EdDSA_SHA512_Ed25519" - "Recent Router Identities and Destinations".
357  // Use "7" because i2pd <2.24.0 does not recognize the textual form.
358  // If SIGNATURE_TYPE is not specified, then the default one is DSA_SHA1.
359  const Reply& reply = SendRequestAndGetReply(sock, "DEST GENERATE SIGNATURE_TYPE=7", false);
360 
361  m_private_key = DecodeI2PBase64(reply.Get("PRIV"));
362 }
363 
365 {
366  DestGenerate(sock);
367 
368  // umask is set to 0077 in common/system.cpp, which is ok.
370  std::string(m_private_key.begin(), m_private_key.end()))) {
371  throw std::runtime_error(
372  strprintf("Cannot save I2P private key to %s", fs::quoted(fs::PathToString(m_private_key_file))));
373  }
374 }
375 
377 {
378  // From https://geti2p.net/spec/common-structures#destination:
379  // "They are 387 bytes plus the certificate length specified at bytes 385-386, which may be
380  // non-zero"
381  static constexpr size_t DEST_LEN_BASE = 387;
382  static constexpr size_t CERT_LEN_POS = 385;
383 
384  uint16_t cert_len;
385 
386  if (m_private_key.size() < CERT_LEN_POS + sizeof(cert_len)) {
387  throw std::runtime_error(strprintf("The private key is too short (%d < %d)",
388  m_private_key.size(),
389  CERT_LEN_POS + sizeof(cert_len)));
390  }
391 
392  memcpy(&cert_len, &m_private_key.at(CERT_LEN_POS), sizeof(cert_len));
393  cert_len = be16toh_internal(cert_len);
394 
395  const size_t dest_len = DEST_LEN_BASE + cert_len;
396 
397  if (dest_len > m_private_key.size()) {
398  throw std::runtime_error(strprintf("Certificate length (%d) designates that the private key should "
399  "be %d bytes, but it is only %d bytes",
400  cert_len,
401  dest_len,
402  m_private_key.size()));
403  }
404 
405  return Binary{m_private_key.begin(), m_private_key.begin() + dest_len};
406 }
407 
409 {
410  std::string errmsg;
411  if (m_control_sock && m_control_sock->IsConnected(errmsg)) {
412  return;
413  }
414 
415  const auto session_type = m_transient ? "transient" : "persistent";
416  const auto session_id = GetRandHash().GetHex().substr(0, 10); // full is overkill, too verbose in the logs
417 
418  LogDebug(BCLog::I2P, "Creating %s I2P SAM session %s with %s\n", session_type, session_id, m_control_host.ToString());
419 
420  auto sock = Hello();
421 
422  if (m_transient) {
423  // The destination (private key) is generated upon session creation and returned
424  // in the reply in DESTINATION=.
425  const Reply& reply = SendRequestAndGetReply(
426  *sock,
427  strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=TRANSIENT SIGNATURE_TYPE=7 "
428  "i2cp.leaseSetEncType=4,0 inbound.quantity=1 outbound.quantity=1",
429  session_id));
430 
431  m_private_key = DecodeI2PBase64(reply.Get("DESTINATION"));
432  } else {
433  // Read our persistent destination (private key) from disk or generate
434  // one and save it to disk. Then use it when creating the session.
435  const auto& [read_ok, data] = ReadBinaryFile(m_private_key_file);
436  if (read_ok) {
437  m_private_key.assign(data.begin(), data.end());
438  } else {
440  }
441 
442  const std::string& private_key_b64 = SwapBase64(EncodeBase64(m_private_key));
443 
445  strprintf("SESSION CREATE STYLE=STREAM ID=%s DESTINATION=%s "
446  "i2cp.leaseSetEncType=4,0 inbound.quantity=3 outbound.quantity=3",
447  session_id,
448  private_key_b64));
449  }
450 
452  m_session_id = session_id;
453  m_control_sock = std::move(sock);
454 
455  LogInfo("%s I2P SAM session %s created, my address=%s",
456  Capitalize(session_type),
457  m_session_id,
458  m_my_addr.ToStringAddrPort());
459 }
460 
461 std::unique_ptr<Sock> Session::StreamAccept()
462 {
463  auto sock = Hello();
464 
465  const Reply& reply = SendRequestAndGetReply(
466  *sock, strprintf("STREAM ACCEPT ID=%s SILENT=false", m_session_id), false);
467 
468  const std::string& result = reply.Get("RESULT");
469 
470  if (result == "OK") {
471  return sock;
472  }
473 
474  if (result == "INVALID_ID") {
475  // If our session id is invalid, then force session re-creation on next usage.
476  Disconnect();
477  }
478 
479  throw std::runtime_error(strprintf("\"%s\"", reply.full));
480 }
481 
483 {
484  if (m_control_sock) {
485  if (m_session_id.empty()) {
486  LogInfo("Destroying incomplete I2P SAM session");
487  } else {
488  LogInfo("Destroying I2P SAM session %s", m_session_id);
489  }
490  m_control_sock.reset();
491  }
492  m_session_id.clear();
493 }
494 } // namespace sam
495 } // namespace i2p
CSHA256 & Write(const unsigned char *data, size_t len)
Definition: sha256.cpp:699
std::string full
Full, unparsed reply.
Definition: i2p.h:126
std::unique_ptr< Sock > Connect() const
Definition: netbase.cpp:668
void CheckControlSock() EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Check the control socket for errors and possibly disconnect.
Definition: i2p.cpp:342
void DestGenerate(const Sock &sock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Generate a new destination with the SAM proxy and set m_private_key to it.
Definition: i2p.cpp:353
uint16_t GetPort() const
Definition: netaddress.cpp:835
Binary MyDestination() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Derive own destination from m_private_key.
Definition: i2p.cpp:376
BSWAP_CONSTEXPR uint16_t be16toh_internal(uint16_t big_endian_16bits)
Definition: endian.h:23
void CreateIfNotCreatedAlready() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Create the session if not already created.
Definition: i2p.cpp:408
#define strprintf
Format arguments and return the string or write to given std::ostream (see tinyformat::format doc for...
Definition: tinyformat.h:1172
std::unique_ptr< Sock > StreamAccept() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy and issue "STREAM ACCEPT" request using the existing session i...
Definition: i2p.cpp:461
Mutex m_mutex
Mutex protecting the members that can be concurrently accessed.
Definition: i2p.h:239
static Binary DecodeI2PBase64(const std::string &i2p_b64)
Decode an I2P-style Base64 string.
Definition: i2p.cpp:74
std::string EncodeBase32(std::span< const unsigned char > input, bool pad)
Base32 encode.
Reply SendRequestAndGetReply(const Sock &sock, const std::string &request, bool check_result_ok=true) const
Send request and get a reply from the SAM proxy.
Definition: i2p.cpp:293
CService me
Our I2P address.
Definition: i2p.h:37
memcpy(result.begin(), stream.data(), stream.size())
An established connection with another peer.
Definition: i2p.h:32
std::string EncodeBase64(std::span< const unsigned char > input)
virtual std::string RecvUntilTerminator(uint8_t terminator, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt, size_t max_data) const
Read from socket until a terminator character is encountered.
Definition: sock.cpp:297
A reply from the SAM proxy.
Definition: i2p.h:122
const fs::path m_private_key_file
The name of the file where this peer&#39;s private key is stored (in binary).
Definition: i2p.h:224
std::string ToStringAddrPort() const
Definition: netaddress.cpp:903
bool WriteBinaryFile(const fs::path &filename, const std::string &data)
Write contents of std::string to a file.
std::string Get(const std::string &key) const
Get the value of a given key.
Definition: i2p.cpp:283
std::string ToStringAddr() const
Definition: netaddress.cpp:580
std::string ToString() const
Definition: netbase.h:83
const bool m_transient
Whether this is a transient session (the I2P private key will not be read or written to disk)...
Definition: i2p.h:273
static CNetAddr DestB64ToAddr(const std::string &dest)
Derive the .b32.i2p address of an I2P destination (I2P-style Base64).
Definition: i2p.cpp:112
static constexpr uint16_t I2P_SAM31_PORT
SAM 3.1 and earlier do not support specifying ports and force the port to 0.
Definition: netaddress.h:105
#define LOCK(cs)
Definition: sync.h:258
std::optional< std::vector< unsigned char > > DecodeBase64(std::string_view str)
#define LogInfo(...)
Definition: log.h:95
static CNetAddr DestBinToAddr(const Binary &dest)
Derive the .b32.i2p address of an I2P destination (binary).
Definition: i2p.cpp:90
A combination of a network address (CNetAddr) and a (TCP) port.
Definition: netaddress.h:529
bool SetSpecial(std::string_view addr)
Parse a Tor or I2P address and set this object to it.
Definition: netaddress.cpp:212
void Finalize(unsigned char hash[OUTPUT_SIZE])
Definition: sha256.cpp:725
uint8_t Event
Definition: sock.h:139
std::unique_ptr< Sock > Hello() const EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Open a new connection to the SAM proxy.
Definition: i2p.cpp:329
std::string request
Request, used for detailed error reporting.
Definition: i2p.h:131
const std::shared_ptr< CThreadInterrupt > m_interrupt
Cease network activity when this is signaled.
Definition: i2p.h:234
static constexpr size_t MAX_MSG_SIZE
The maximum size of an incoming message from the I2P SAM proxy (in bytes).
Definition: i2p.h:51
void GenerateAndSavePrivateKey(const Sock &sock) EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Generate a new destination with the SAM proxy, set m_private_key to it and save it on disk to m_priva...
Definition: i2p.cpp:364
Definition: netbase.h:58
Network address.
Definition: netaddress.h:112
Definition: i2p.cpp:32
bool Connect(const CService &to, Connection &conn, bool &proxy_error) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Connect to an I2P peer.
Definition: i2p.cpp:222
#define LogDebug(category,...)
Definition: log.h:115
static constexpr Event RECV
If passed to Wait(), then it will wait for readiness to read from the socket.
Definition: sock.h:144
auto result
Definition: common-types.h:74
void Disconnect() EXCLUSIVE_LOCKS_REQUIRED(m_mutex)
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:482
static auto quoted(const std::string &s)
Definition: fs.h:101
Session(const fs::path &private_key_file, const Proxy &control_host, std::shared_ptr< CThreadInterrupt > interrupt)
Construct a session.
Definition: i2p.cpp:120
uint256 GetRandHash() noexcept
Generate a random uint256.
Definition: random.h:463
std::string GetHex() const
Definition: uint256.cpp:11
static std::string SwapBase64(const std::string &from)
Swap Standard Base64 <-> I2P Base64.
Definition: i2p.cpp:42
static std::string PathToString(const path &path)
Convert path object to a byte string.
Definition: fs.h:157
std::unordered_map< std::string, std::optional< std::string > > keys
A map of keywords from the parsed reply.
Definition: i2p.h:140
static const size_t OUTPUT_SIZE
Definition: sha256.h:21
#define AssertLockNotHeld(cs)
Definition: sync.h:141
~Session()
Destroy the session, closing the internally used sockets.
Definition: i2p.cpp:137
std::vector< uint8_t > Binary
Binary data.
Definition: i2p.h:27
const Proxy m_control_host
The SAM control service proxy.
Definition: i2p.h:229
bool Accept(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Wait for and accept a new incoming connection.
Definition: i2p.cpp:158
virtual void SendComplete(std::span< const unsigned char > data, std::chrono::milliseconds timeout, CThreadInterrupt &interrupt) const
Send the given data, retrying on transient errors.
Definition: sock.cpp:249
RAII helper class that manages a socket and closes it automatically when it goes out of scope...
Definition: sock.h:27
bool Listen(Connection &conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex)
Start listening for an incoming connection.
Definition: i2p.cpp:143
A hasher class for SHA-256.
Definition: sha256.h:13
std::unique_ptr< Sock > sock
Connected socket.
Definition: i2p.h:34
Path class wrapper to block calls to the fs::path(std::string) implicit constructor and the fs::path:...
Definition: fs.h:33
CService peer
The peer&#39;s I2P address.
Definition: i2p.h:40
static constexpr auto MAX_WAIT_FOR_IO
Maximum time to wait for I/O readiness.
Definition: sock.h:22
#define LogError(...)
Definition: log.h:97
std::string Capitalize(std::string str)
Capitalizes the first character of the given string.
std::vector< T > Split(const std::span< const char > &sp, std::string_view separators, bool include_sep=false)
Split a string on any char found in separators, returning a vector.
Definition: string.h:116
std::pair< bool, std::string > ReadBinaryFile(const fs::path &filename, size_t maxsize)
Read full contents of a file and return them in a std::string.