Skip to content

Commit 5c8e15c

Browse files
committed
i2p: destroy the session if we get an unexpected error from the I2P router
From https://geti2p.net/en/docs/api/samv3: If SILENT=false was passed, which is the default value, the SAM bridge sends the client a ASCII line containing the base64 public destination key of the requesting peer So, `Accept()` is supposed to receive a Base64 encoded destination of the connecting peer, but if it receives something like this instead: STREAM STATUS RESULT=I2P_ERROR MESSAGE="Session was closed" then destroy the session.
1 parent 762404a commit 5c8e15c

File tree

3 files changed

+137
-24
lines changed

3 files changed

+137
-24
lines changed

src/i2p.cpp

Lines changed: 49 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
#include <netaddress.h>
1313
#include <netbase.h>
1414
#include <random.h>
15+
#include <sync.h>
1516
#include <tinyformat.h>
1617
#include <util/fs.h>
1718
#include <util/readwritefile.h>
@@ -153,27 +154,59 @@ bool Session::Listen(Connection& conn)
153154

154155
bool Session::Accept(Connection& conn)
155156
{
156-
try {
157-
while (!*m_interrupt) {
158-
Sock::Event occurred;
159-
if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
160-
throw std::runtime_error("wait on socket failed");
161-
}
157+
AssertLockNotHeld(m_mutex);
162158

163-
if (occurred == 0) {
164-
// Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
165-
continue;
166-
}
159+
std::string errmsg;
160+
bool disconnect{false};
167161

168-
const std::string& peer_dest =
169-
conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
162+
while (!*m_interrupt) {
163+
Sock::Event occurred;
164+
if (!conn.sock->Wait(MAX_WAIT_FOR_IO, Sock::RECV, &occurred)) {
165+
errmsg = "wait on socket failed";
166+
break;
167+
}
170168

171-
conn.peer = CService(DestB64ToAddr(peer_dest), I2P_SAM31_PORT);
169+
if (occurred == 0) {
170+
// Timeout, no incoming connections or errors within MAX_WAIT_FOR_IO.
171+
continue;
172+
}
172173

173-
return true;
174+
std::string peer_dest;
175+
try {
176+
peer_dest = conn.sock->RecvUntilTerminator('\n', MAX_WAIT_FOR_IO, *m_interrupt, MAX_MSG_SIZE);
177+
} catch (const std::runtime_error& e) {
178+
errmsg = e.what();
179+
break;
174180
}
175-
} catch (const std::runtime_error& e) {
176-
Log("Error accepting: %s", e.what());
181+
182+
CNetAddr peer_addr;
183+
try {
184+
peer_addr = DestB64ToAddr(peer_dest);
185+
} 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+
if (peer_dest.find("RESULT=I2P_ERROR") != std::string::npos) {
192+
errmsg = strprintf("unexpected reply that hints the session is unusable: %s", peer_dest);
193+
disconnect = true;
194+
} else {
195+
errmsg = e.what();
196+
}
197+
break;
198+
}
199+
200+
conn.peer = CService(peer_addr, I2P_SAM31_PORT);
201+
202+
return true;
203+
}
204+
205+
Log("Error accepting%s: %s", disconnect ? " (will close the session)" : "", errmsg);
206+
if (disconnect) {
207+
LOCK(m_mutex);
208+
Disconnect();
209+
} else {
177210
CheckControlSock();
178211
}
179212
return false;

src/i2p.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -105,7 +105,7 @@ class Session
105105
* completion the `peer` member will be set to the address of the incoming peer.
106106
* @return true on success
107107
*/
108-
bool Accept(Connection& conn);
108+
bool Accept(Connection& conn) EXCLUSIVE_LOCKS_REQUIRED(!m_mutex);
109109

110110
/**
111111
* Connect to an I2P peer.

src/test/i2p_tests.cpp

Lines changed: 87 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,34 @@
1616
#include <memory>
1717
#include <string>
1818

19-
BOOST_FIXTURE_TEST_SUITE(i2p_tests, BasicTestingSetup)
19+
/// Save the log level and the value of CreateSock and restore them when the test ends.
20+
class EnvTestingSetup : public BasicTestingSetup
21+
{
22+
public:
23+
explicit EnvTestingSetup(const ChainType chainType = ChainType::MAIN,
24+
const std::vector<const char*>& extra_args = {})
25+
: BasicTestingSetup{chainType, extra_args},
26+
m_prev_log_level{LogInstance().LogLevel()},
27+
m_create_sock_orig{CreateSock}
28+
{
29+
LogInstance().SetLogLevel(BCLog::Level::Trace);
30+
}
31+
32+
~EnvTestingSetup()
33+
{
34+
CreateSock = m_create_sock_orig;
35+
LogInstance().SetLogLevel(m_prev_log_level);
36+
}
37+
38+
private:
39+
const BCLog::Level m_prev_log_level;
40+
const std::function<std::unique_ptr<Sock>(const CService&)> m_create_sock_orig;
41+
};
42+
43+
BOOST_FIXTURE_TEST_SUITE(i2p_tests, EnvTestingSetup)
2044

2145
BOOST_AUTO_TEST_CASE(unlimited_recv)
2246
{
23-
const auto prev_log_level{LogInstance().LogLevel()};
24-
LogInstance().SetLogLevel(BCLog::Level::Trace);
25-
auto CreateSockOrig = CreateSock;
26-
2747
// Mock CreateSock() to create MockSock.
2848
CreateSock = [](const CService&) {
2949
return std::make_unique<StaticContentsSock>(std::string(i2p::sam::MAX_MSG_SIZE + 1, 'a'));
@@ -40,9 +60,69 @@ BOOST_AUTO_TEST_CASE(unlimited_recv)
4060
bool proxy_error;
4161
BOOST_REQUIRE(!session.Connect(CService{}, conn, proxy_error));
4262
}
63+
}
64+
65+
BOOST_AUTO_TEST_CASE(listen_ok_accept_fail)
66+
{
67+
size_t num_sockets{0};
68+
CreateSock = [&num_sockets](const CService&) {
69+
// clang-format off
70+
++num_sockets;
71+
// First socket is the control socket for creating the session.
72+
if (num_sockets == 1) {
73+
return std::make_unique<StaticContentsSock>(
74+
// reply to HELLO
75+
"HELLO REPLY RESULT=OK VERSION=3.1\n"
76+
// reply to DEST GENERATE
77+
"DEST REPLY PUB=WnGOLXRBqHQhdVjFlWqRxJwz9hxx~2~wGc2Vplta1KhacY4tdEGodCF1WMWVapHEnDP2HHH~b~AZzZWmW1rUqFpxji10Qah0IXVYxZVqkcScM~Yccf9v8B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~1MzF9P93pQWI3Do52EeNAayz4HbpPjNhVBzG1hUEFwznfPmUZBPuaOR4-uBm1NEWEuONlNOCctE4-U0Ukh94z-Qb55U5vXjR5G4apmBblr68t6Wm1TKlzpgFHzSqLryh3stWqrOKY1H0z9eZ2z1EkHFOpD5LyF6nf51e-lV7HLMl44TYzoEHK8RRVodtLcW9lacVdBpv~tOzlZERIiDziZODPETENZMz5oy9DQ7UUw==\n"
78+
// reply to SESSION CREATE
79+
"SESSION STATUS RESULT=OK\n"
80+
// dummy to avoid reporting EOF on the socket
81+
"a"
82+
);
83+
}
84+
// Subsequent sockets are for recreating the session or for listening and accepting incoming connections.
85+
if (num_sockets % 2 == 0) {
86+
// Replies to Listen() and Accept()
87+
return std::make_unique<StaticContentsSock>(
88+
// reply to HELLO
89+
"HELLO REPLY RESULT=OK VERSION=3.1\n"
90+
// reply to STREAM ACCEPT
91+
"STREAM STATUS RESULT=OK\n"
92+
// continued reply to STREAM ACCEPT, violating the protocol described at
93+
// https://geti2p.net/en/docs/api/samv3#Accept%20Response
94+
// should be base64, something like
95+
// "IchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLiHIVetPG2g6F26s0CkqhQ5k1z1YKA2zwIWSbzUV18YuIchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLiHIVetPG2g6F26s0CkqhQ5k1z1YKA2zwIWSbzUV18YuIchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLiHIVetPG2g6F26s0CkqhQ5k1z1YKA2zwIWSbzUV18YuIchV608baDoXbqzQKSqFDmTXPVgoDbPAhZJvNRXXxi4hyFXrTxtoOhdurNApKoUOZNc9WCgNs8CFkm81FdfGLlSreVaCuCS5sdb-8ToWULWP7kt~lRPDeUNxQMq3cRSBBQAEAAcAAA==\n"
96+
"STREAM STATUS RESULT=I2P_ERROR MESSAGE=\"Session was closed\"\n"
97+
);
98+
} else {
99+
// Another control socket, but without creating a destination (it is cached in the session).
100+
return std::make_unique<StaticContentsSock>(
101+
// reply to HELLO
102+
"HELLO REPLY RESULT=OK VERSION=3.1\n"
103+
// reply to SESSION CREATE
104+
"SESSION STATUS RESULT=OK\n"
105+
// dummy to avoid reporting EOF on the socket
106+
"a"
107+
);
108+
}
109+
// clang-format on
110+
};
43111

44-
CreateSock = CreateSockOrig;
45-
LogInstance().SetLogLevel(prev_log_level);
112+
CThreadInterrupt interrupt;
113+
i2p::sam::Session session(gArgs.GetDataDirNet() / "test_i2p_private_key",
114+
CService{in6_addr(IN6ADDR_LOOPBACK_INIT), /*port=*/7656},
115+
&interrupt);
116+
117+
i2p::Connection conn;
118+
for (size_t i = 0; i < 5; ++i) {
119+
ASSERT_DEBUG_LOG("Creating persistent SAM session");
120+
ASSERT_DEBUG_LOG("Persistent SAM session" /* ... created */);
121+
ASSERT_DEBUG_LOG("Error accepting");
122+
ASSERT_DEBUG_LOG("Destroying SAM session");
123+
BOOST_REQUIRE(session.Listen(conn));
124+
BOOST_REQUIRE(!session.Accept(conn));
125+
}
46126
}
47127

48128
BOOST_AUTO_TEST_SUITE_END()

0 commit comments

Comments
 (0)