LCOV - code coverage report
Current view: top level - src - i2p.cpp (source / functions) Hit Total Coverage
Test: test_dash_coverage.info Lines: 190 259 73.4 %
Date: 2026-06-25 07:23:51 Functions: 21 23 91.3 %

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

Generated by: LCOV version 1.16