i2pd/SSU.cpp

1238 lines
38 KiB
C++
Raw Normal View History

2014-01-28 21:49:54 +00:00
#include <string.h>
2014-01-23 21:10:33 +00:00
#include <boost/bind.hpp>
2014-01-29 21:49:53 +00:00
#include <cryptopp/dh.h>
#include <cryptopp/sha.h>
2014-01-29 21:49:53 +00:00
#include "CryptoConst.h"
2014-01-23 21:10:33 +00:00
#include "Log.h"
2014-01-29 21:49:53 +00:00
#include "Timestamp.h"
2014-01-28 21:49:54 +00:00
#include "RouterContext.h"
2014-04-04 18:56:46 +00:00
#include "Transports.h"
2014-01-23 21:10:33 +00:00
#include "hmac.h"
#include "SSU.h"
namespace i2p
{
namespace ssu
{
2014-01-24 21:30:07 +00:00
2014-04-02 14:49:16 +00:00
SSUSession::SSUSession (SSUServer& server, boost::asio::ip::udp::endpoint& remoteEndpoint,
2014-04-07 23:28:06 +00:00
const i2p::data::RouterInfo * router, bool peerTest ):
m_Server (server), m_RemoteEndpoint (remoteEndpoint), m_RemoteRouter (router),
2014-09-18 16:43:02 +00:00
m_Timer (m_Server.GetService ()), m_DHKeysPair (nullptr), m_PeerTest (peerTest),
m_State (eSessionStateUnknown), m_IsSessionKey (false), m_RelayTag (0),
m_Data (*this), m_NumSentBytes (0), m_NumReceivedBytes (0)
2014-01-24 21:30:07 +00:00
{
2014-09-09 17:45:12 +00:00
m_CreationTime = i2p::util::GetSecondsSinceEpoch ();
2014-09-04 14:20:44 +00:00
if (!router) // incoming session
ScheduleConnectTimer ();
2014-01-24 21:30:07 +00:00
}
2014-03-31 02:55:03 +00:00
SSUSession::~SSUSession ()
{
2014-04-22 15:39:26 +00:00
delete m_DHKeysPair;
2014-03-31 02:55:03 +00:00
}
2014-05-15 02:49:22 +00:00
void SSUSession::CreateAESandMacKey (const uint8_t * pubKey)
2014-01-29 21:49:53 +00:00
{
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
2014-04-15 21:44:44 +00:00
uint8_t sharedKey[256];
if (!dh.Agree (sharedKey, m_DHKeysPair->privateKey, pubKey))
2014-01-29 21:49:53 +00:00
{
LogPrint ("Couldn't create shared key");
return;
};
if (sharedKey[0] & 0x80)
2014-01-29 21:49:53 +00:00
{
2014-05-15 02:49:22 +00:00
m_SessionKey[0] = 0;
memcpy (m_SessionKey + 1, sharedKey, 31);
memcpy (m_MacKey, sharedKey + 31, 32);
}
else if (sharedKey[0])
{
2014-05-15 02:49:22 +00:00
memcpy (m_SessionKey, sharedKey, 32);
memcpy (m_MacKey, sharedKey + 32, 32);
2014-01-29 21:49:53 +00:00
}
2014-02-03 19:40:38 +00:00
else
{
// find first non-zero byte
uint8_t * nonZero = sharedKey + 1;
while (!*nonZero)
{
nonZero++;
if (nonZero - sharedKey > 32)
{
LogPrint ("First 32 bytes of shared key is all zeros. Ignored");
return;
}
}
2014-05-15 02:49:22 +00:00
memcpy (m_SessionKey, nonZero, 32);
CryptoPP::SHA256().CalculateDigest(m_MacKey, nonZero, 64 - (nonZero - sharedKey));
2014-02-03 19:40:38 +00:00
}
2014-04-13 20:59:54 +00:00
m_IsSessionKey = true;
m_SessionKeyEncryption.SetKey (m_SessionKey);
2014-05-15 02:49:22 +00:00
m_SessionKeyDecryption.SetKey (m_SessionKey);
2014-01-29 21:49:53 +00:00
}
void SSUSession::ProcessNextMessage (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
2014-01-24 21:30:07 +00:00
{
m_NumReceivedBytes += len;
2014-04-13 20:59:54 +00:00
if (m_State == eSessionStateIntroduced)
2014-01-27 21:52:17 +00:00
{
2014-04-13 20:59:54 +00:00
// HolePunch received
LogPrint ("SSU HolePunch of ", len, " bytes received");
2014-04-13 20:59:54 +00:00
m_State = eSessionStateUnknown;
Connect ();
2014-02-05 20:07:47 +00:00
}
else
2014-02-12 21:36:13 +00:00
{
2014-08-19 15:03:08 +00:00
if (!len) return; // ignore zero-length packets
2014-09-07 00:43:20 +00:00
if (m_State == eSessionStateEstablished)
2014-09-05 20:35:02 +00:00
ScheduleTermination ();
2014-04-13 20:59:54 +00:00
if (m_IsSessionKey && Validate (buf, len, m_MacKey)) // try session key first
2014-05-15 02:49:22 +00:00
DecryptSessionKey (buf, len);
2014-04-13 20:59:54 +00:00
else
2014-02-12 21:36:13 +00:00
{
2014-04-13 20:59:54 +00:00
// try intro key depending on side
auto introKey = GetIntroKey ();
if (introKey && Validate (buf, len, introKey))
Decrypt (buf, len, introKey);
else
{
// try own intro key
auto address = i2p::context.GetRouterInfo ().GetSSUAddress ();
if (!address)
{
LogPrint ("SSU is not supported");
return;
}
if (Validate (buf, len, address->key))
Decrypt (buf, len, address->key);
else
{
2014-08-19 01:23:49 +00:00
LogPrint ("MAC verification failed ", len, " bytes from ", senderEndpoint);
2014-04-13 20:59:54 +00:00
m_Server.DeleteSession (this);
return;
}
}
2014-02-12 21:36:13 +00:00
}
2014-04-13 20:59:54 +00:00
// successfully decrypted
ProcessMessage (buf, len, senderEndpoint);
}
2014-02-05 20:07:47 +00:00
}
2014-04-13 20:59:54 +00:00
void SSUSession::ProcessMessage (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
2014-01-29 21:49:53 +00:00
{
2014-04-07 22:54:28 +00:00
SSUHeader * header = (SSUHeader *)buf;
switch (header->GetPayloadType ())
{
2014-04-13 20:59:54 +00:00
case PAYLOAD_TYPE_DATA:
LogPrint ("SSU data received");
ProcessData (buf + sizeof (SSUHeader), len - sizeof (SSUHeader));
break;
2014-04-07 22:54:28 +00:00
case PAYLOAD_TYPE_SESSION_REQUEST:
ProcessSessionRequest (buf, len, senderEndpoint);
break;
case PAYLOAD_TYPE_SESSION_CREATED:
ProcessSessionCreated (buf, len);
break;
2014-04-13 20:59:54 +00:00
case PAYLOAD_TYPE_SESSION_CONFIRMED:
ProcessSessionConfirmed (buf, len);
break;
2014-04-07 22:54:28 +00:00
case PAYLOAD_TYPE_PEER_TEST:
2014-04-07 23:28:06 +00:00
LogPrint ("SSU peer test received");
2014-04-13 20:59:54 +00:00
ProcessPeerTest (buf + sizeof (SSUHeader), len - sizeof (SSUHeader), senderEndpoint);
break;
case PAYLOAD_TYPE_SESSION_DESTROYED:
{
LogPrint ("SSU session destroy received");
m_Server.DeleteSession (this); // delete this
break;
}
case PAYLOAD_TYPE_RELAY_RESPONSE:
ProcessRelayResponse (buf, len);
if (m_State != eSessionStateEstablished)
m_Server.DeleteSession (this);
2014-04-13 20:59:54 +00:00
break;
2014-04-16 20:47:56 +00:00
case PAYLOAD_TYPE_RELAY_REQUEST:
LogPrint ("SSU relay request received");
ProcessRelayRequest (buf + sizeof (SSUHeader), len - sizeof (SSUHeader), senderEndpoint);
2014-04-16 20:47:56 +00:00
break;
2014-04-13 20:59:54 +00:00
case PAYLOAD_TYPE_RELAY_INTRO:
LogPrint ("SSU relay intro received");
ProcessRelayIntro (buf + sizeof (SSUHeader), len - sizeof (SSUHeader));
break;
default:
LogPrint ("Unexpected SSU payload type ", (int)header->GetPayloadType ());
}
2014-04-07 20:41:29 +00:00
}
void SSUSession::ProcessSessionRequest (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
{
LogPrint ("Session request received");
m_RemoteEndpoint = senderEndpoint;
2014-09-18 16:43:02 +00:00
if (!m_DHKeysPair)
m_DHKeysPair = i2p::transports.GetNextDHKeysPair ();
2014-05-15 02:49:22 +00:00
CreateAESandMacKey (buf + sizeof (SSUHeader));
SendSessionCreated (buf + sizeof (SSUHeader));
2014-01-29 21:49:53 +00:00
}
void SSUSession::ProcessSessionCreated (uint8_t * buf, size_t len)
{
2014-09-18 16:43:02 +00:00
if (!m_RemoteRouter || !m_DHKeysPair)
{
LogPrint ("Unsolicited session created message");
return;
}
LogPrint ("Session created received");
m_Timer.cancel (); // connect timer
uint8_t signedData[532]; // x,y, our IP, our port, remote IP, remote port, relayTag, signed on time
uint8_t * payload = buf + sizeof (SSUHeader);
uint8_t * y = payload;
2014-05-15 02:49:22 +00:00
CreateAESandMacKey (y);
memcpy (signedData, m_DHKeysPair->publicKey, 256); // x
memcpy (signedData + 256, y, 256); // y
payload += 256;
payload += 1; // size, assume 4
uint8_t * ourAddress = payload;
boost::asio::ip::address_v4 ourIP (be32toh (*(uint32_t* )ourAddress));
payload += 4; // address
uint16_t ourPort = be16toh (*(uint16_t *)payload);
payload += 2; // port
memcpy (signedData + 512, ourAddress, 6); // our IP and port
LogPrint ("Our external address is ", ourIP.to_string (), ":", ourPort);
i2p::context.UpdateAddress (ourIP.to_string ().c_str ());
*(uint32_t *)(signedData + 518) = htobe32 (m_RemoteEndpoint.address ().to_v4 ().to_ulong ()); // remote IP
*(uint16_t *)(signedData + 522) = htobe16 (m_RemoteEndpoint.port ()); // remote port
memcpy (signedData + 524, payload, 8); // relayTag and signed on time
2014-04-08 19:35:08 +00:00
m_RelayTag = be32toh (*(uint32_t *)payload);
payload += 4; // relayTag
payload += 4; // signed on time
// decrypt DSA signature
2014-06-08 18:43:18 +00:00
m_SessionKeyDecryption.SetIV (((SSUHeader *)buf)->iv);
m_SessionKeyDecryption.Decrypt (payload, 48, payload);
// verify
CryptoPP::DSA::PublicKey pubKey;
pubKey.Initialize (i2p::crypto::dsap, i2p::crypto::dsaq, i2p::crypto::dsag, CryptoPP::Integer (m_RemoteRouter->GetRouterIdentity ().signingKey, 128));
CryptoPP::DSA::Verifier verifier (pubKey);
if (!verifier.VerifyMessage (signedData, 532, payload, 40))
LogPrint ("SSU signature verification failed");
2014-04-08 19:35:08 +00:00
SendSessionConfirmed (y, ourAddress);
2014-01-29 21:49:53 +00:00
}
2014-02-04 19:20:58 +00:00
void SSUSession::ProcessSessionConfirmed (uint8_t * buf, size_t len)
{
LogPrint ("Session confirmed received");
uint8_t * payload = buf + sizeof (SSUHeader);
payload++; // identity fragment info
uint16_t identitySize = be16toh (*(uint16_t *)payload);
payload += 2; // size of identity fragment
if (identitySize == i2p::data::DEFAULT_IDENTITY_SIZE)
{
i2p::data::Identity ident;
ident.FromBuffer (payload, identitySize);
m_RemoteIdent = ident.Hash ();
2014-09-18 18:37:29 +00:00
m_Data.UpdatePacketSize (m_RemoteIdent);
}
else
LogPrint ("SSU unexpected identity size ", identitySize);
payload += identitySize; // identity
// TODO: verify signature
2014-04-13 20:59:54 +00:00
SendI2NPMessage (CreateDeliveryStatusMsg (0));
Established ();
2014-02-04 19:20:58 +00:00
}
2014-01-29 21:49:53 +00:00
void SSUSession::SendSessionRequest ()
{
2014-02-12 21:36:13 +00:00
auto introKey = GetIntroKey ();
if (!introKey)
2014-01-29 21:49:53 +00:00
{
2014-02-12 21:36:13 +00:00
LogPrint ("SSU is not supported");
2014-01-29 21:49:53 +00:00
return;
}
uint8_t buf[304 + 18]; // 304 bytes for ipv4 (320 for ipv6)
uint8_t * payload = buf + sizeof (SSUHeader);
2014-04-04 18:56:46 +00:00
memcpy (payload, m_DHKeysPair->publicKey, 256); // x
2014-01-29 21:49:53 +00:00
payload[256] = 4; // we assume ipv4
2014-02-05 03:51:46 +00:00
*(uint32_t *)(payload + 257) = htobe32 (m_RemoteEndpoint.address ().to_v4 ().to_ulong ());
2014-01-29 21:49:53 +00:00
uint8_t iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
2014-02-12 21:36:13 +00:00
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_REQUEST, buf, 304, introKey, iv, introKey);
2014-04-02 14:49:16 +00:00
m_Server.Send (buf, 304, m_RemoteEndpoint);
2014-01-29 21:49:53 +00:00
}
2014-04-09 15:58:57 +00:00
void SSUSession::SendRelayRequest (uint32_t iTag, const uint8_t * iKey)
2014-02-21 21:13:36 +00:00
{
auto address = i2p::context.GetRouterInfo ().GetSSUAddress ();
if (!address)
{
LogPrint ("SSU is not supported");
return;
}
uint8_t buf[96 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
2014-04-09 15:58:57 +00:00
*(uint32_t *)payload = htobe32 (iTag);
2014-02-21 21:13:36 +00:00
payload += 4;
*payload = 0; // no address
payload++;
*(uint16_t *)payload = 0; // port = 0
payload += 2;
*payload = 0; // challenge
payload++;
2014-09-18 00:43:47 +00:00
memcpy (payload, (const uint8_t *)address->key, 32);
2014-02-21 21:13:36 +00:00
payload += 32;
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
*(uint32_t *)payload = htobe32 (rnd.GenerateWord32 ()); // nonce
uint8_t iv[16];
rnd.GenerateBlock (iv, 16); // random iv
if (m_State == eSessionStateEstablished)
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_REQUEST, buf, 96, m_SessionKey, iv, m_MacKey);
else
2014-06-10 02:56:16 +00:00
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_REQUEST, buf, 96, iKey, iv, iKey);
2014-04-02 14:49:16 +00:00
m_Server.Send (buf, 96, m_RemoteEndpoint);
2014-02-21 21:13:36 +00:00
}
2014-01-30 19:03:11 +00:00
void SSUSession::SendSessionCreated (const uint8_t * x)
2014-01-29 21:49:53 +00:00
{
2014-02-12 21:36:13 +00:00
auto introKey = GetIntroKey ();
2014-02-25 02:43:26 +00:00
auto address = i2p::context.GetRouterInfo ().GetSSUAddress ();
if (!introKey || !address)
2014-01-29 21:49:53 +00:00
{
2014-02-12 21:36:13 +00:00
LogPrint ("SSU is not supported");
2014-01-29 21:49:53 +00:00
return;
}
2014-04-16 19:54:28 +00:00
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
2014-01-30 19:03:11 +00:00
uint8_t signedData[532]; // x,y, remote IP, remote port, our IP, our port, relayTag, signed on time
memcpy (signedData, x, 256); // x
2014-01-29 21:49:53 +00:00
2014-01-30 19:03:11 +00:00
uint8_t buf[368 + 18];
2014-01-29 21:49:53 +00:00
uint8_t * payload = buf + sizeof (SSUHeader);
2014-04-04 18:56:46 +00:00
memcpy (payload, m_DHKeysPair->publicKey, 256);
2014-01-30 19:03:11 +00:00
memcpy (signedData + 256, payload, 256); // y
payload += 256;
*payload = 4; // we assume ipv4
payload++;
*(uint32_t *)(payload) = htobe32 (m_RemoteEndpoint.address ().to_v4 ().to_ulong ());
2014-01-30 19:03:11 +00:00
payload += 4;
*(uint16_t *)(payload) = htobe16 (m_RemoteEndpoint.port ());
payload += 2;
memcpy (signedData + 512, payload - 6, 6); // remote endpoint IP and port
2014-02-25 02:43:26 +00:00
*(uint32_t *)(signedData + 518) = htobe32 (address->host.to_v4 ().to_ulong ()); // our IP
*(uint16_t *)(signedData + 522) = htobe16 (address->port); // our port
2014-04-16 19:54:28 +00:00
uint32_t relayTag = 0;
if (i2p::context.GetRouterInfo ().IsIntroducer ())
{
2014-09-04 20:27:22 +00:00
relayTag = rnd.GenerateWord32 ();
if (!relayTag) relayTag = 1;
2014-04-16 19:54:28 +00:00
m_Server.AddRelay (relayTag, m_RemoteEndpoint);
}
2014-08-18 17:46:11 +00:00
*(uint32_t *)(payload) = htobe32 (relayTag);
2014-04-16 19:54:28 +00:00
payload += 4; // relay tag
2014-01-30 19:03:11 +00:00
*(uint32_t *)(payload) = htobe32 (i2p::util::GetSecondsSinceEpoch ()); // signed on time
payload += 4;
memcpy (signedData + 524, payload - 8, 8); // relayTag and signed on time
i2p::context.Sign (signedData, 532, payload); // DSA signature
// TODO: fill padding with random data
2014-01-29 21:49:53 +00:00
2014-01-30 19:03:11 +00:00
uint8_t iv[16];
rnd.GenerateBlock (iv, 16); // random iv
// encrypt signature and 8 bytes padding with newly created session key
2014-06-08 18:43:18 +00:00
m_SessionKeyEncryption.SetIV (iv);
m_SessionKeyEncryption.Encrypt (payload, 48, payload);
2014-01-30 19:03:11 +00:00
// encrypt message with intro key
2014-06-10 02:56:16 +00:00
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_CREATED, buf, 368, introKey, iv, introKey);
2014-06-10 14:39:29 +00:00
Send (buf, 368);
2014-01-29 21:49:53 +00:00
}
2014-04-08 19:35:08 +00:00
void SSUSession::SendSessionConfirmed (const uint8_t * y, const uint8_t * ourAddress)
2014-02-04 19:20:58 +00:00
{
uint8_t buf[480 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = 1; // 1 fragment
payload++; // info
size_t identLen = sizeof (i2p::context.GetRouterIdentity ()); // 387 bytes
*(uint16_t *)(payload) = htobe16 (identLen);
payload += 2; // cursize
memcpy (payload, (uint8_t *)&i2p::context.GetRouterIdentity (), identLen);
payload += identLen;
uint32_t signedOnTime = i2p::util::GetSecondsSinceEpoch ();
*(uint32_t *)(payload) = htobe32 (signedOnTime); // signed on time
payload += 4;
size_t paddingSize = ((payload - buf) + 40)%16;
if (paddingSize > 0) paddingSize = 16 - paddingSize;
// TODO: fill padding
payload += paddingSize; // padding size
// signature
uint8_t signedData[532]; // x,y, our IP, our port, remote IP, remote port, relayTag, our signed on time
2014-04-04 18:56:46 +00:00
memcpy (signedData, m_DHKeysPair->publicKey, 256); // x
2014-02-04 19:20:58 +00:00
memcpy (signedData + 256, y, 256); // y
memcpy (signedData + 512, ourAddress, 6); // our address/port as seem by party
*(uint32_t *)(signedData + 518) = htobe32 (m_RemoteEndpoint.address ().to_v4 ().to_ulong ()); // remote IP
*(uint16_t *)(signedData + 522) = htobe16 (m_RemoteEndpoint.port ()); // remote port
2014-04-08 19:35:08 +00:00
*(uint32_t *)(signedData + 524) = htobe32 (m_RelayTag); // relay tag
2014-02-04 19:20:58 +00:00
*(uint32_t *)(signedData + 528) = htobe32 (signedOnTime); // signed on time
i2p::context.Sign (signedData, 532, payload); // DSA signature
uint8_t iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
// encrypt message with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_CONFIRMED, buf, 480, m_SessionKey, iv, m_MacKey);
2014-06-10 14:39:29 +00:00
Send (buf, 480);
2014-02-04 19:20:58 +00:00
}
void SSUSession::ProcessRelayRequest (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& from)
2014-04-16 20:47:56 +00:00
{
uint32_t relayTag = be32toh (*(uint32_t *)buf);
auto session = m_Server.FindRelaySession (relayTag);
if (session)
{
buf += 4; // relay tag
uint8_t size = *buf;
2014-09-05 15:58:22 +00:00
buf++; // size
buf += size; // address
buf += 2; // port
uint8_t challengeSize = *buf;
buf++; // challenge size
buf += challengeSize;
uint8_t * introKey = buf;
2014-09-05 15:58:22 +00:00
buf += 32; // introkey
uint32_t nonce = be32toh (*(uint32_t *)buf);
SendRelayResponse (nonce, from, introKey, session->m_RemoteEndpoint);
SendRelayIntro (session, from);
2014-04-16 20:47:56 +00:00
}
}
void SSUSession::SendRelayResponse (uint32_t nonce, const boost::asio::ip::udp::endpoint& from,
const uint8_t * introKey, const boost::asio::ip::udp::endpoint& to)
2014-04-16 20:47:56 +00:00
{
uint8_t buf[64 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
// Charlie
*payload = 4;
payload++; // size
*(uint32_t *)payload = htobe32 (to.address ().to_v4 ().to_ulong ()); // Charlie's IP
payload += 4; // address
*(uint16_t *)payload = htobe16 (to.port ()); // Charlie's port
payload += 2; // port
// Alice
*payload = 4;
payload++; // size
*(uint32_t *)payload = htobe32 (from.address ().to_v4 ().to_ulong ()); // Alice's IP
2014-04-16 20:47:56 +00:00
payload += 4; // address
*(uint16_t *)payload = htobe16 (from.port ()); // Alice's port
2014-04-16 20:47:56 +00:00
payload += 2; // port
*(uint32_t *)payload = htobe32 (nonce);
if (m_State == eSessionStateEstablished)
{
// encrypt with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_RESPONSE, buf, 64);
Send (buf, 64);
}
else
{
// ecrypt with Alice's intro key
uint8_t iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_RESPONSE, buf, 64, introKey, iv, introKey);
m_Server.Send (buf, 64, from);
}
LogPrint ("SSU relay response sent");
2014-04-16 20:47:56 +00:00
}
void SSUSession::SendRelayIntro (SSUSession * session, const boost::asio::ip::udp::endpoint& from)
{
if (!session) return;
uint8_t buf[48 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = 4;
payload++; // size
*(uint32_t *)payload = htobe32 (from.address ().to_v4 ().to_ulong ()); // Alice's IP
payload += 4; // address
*(uint16_t *)payload = htobe16 (from.port ()); // Alice's port
payload += 2; // port
*payload = 0; // challenge size
uint8_t iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_INTRO, buf, 48, session->m_SessionKey, iv, session->m_MacKey);
m_Server.Send (buf, 48, session->m_RemoteEndpoint);
LogPrint ("SSU relay intro sent");
2014-04-16 20:47:56 +00:00
}
2014-02-21 21:13:36 +00:00
void SSUSession::ProcessRelayResponse (uint8_t * buf, size_t len)
{
2014-04-13 20:59:54 +00:00
LogPrint ("Relay response received");
uint8_t * payload = buf + sizeof (SSUHeader);
payload++; // remote size
//boost::asio::ip::address_v4 remoteIP (be32toh (*(uint32_t* )(payload)));
payload += 4; // remote address
//uint16_t remotePort = be16toh (*(uint16_t *)(payload));
payload += 2; // remote port
payload++; // our size
boost::asio::ip::address_v4 ourIP (be32toh (*(uint32_t* )(payload)));
payload += 4; // our address
uint16_t ourPort = be16toh (*(uint16_t *)(payload));
payload += 2; // our port
LogPrint ("Our external address is ", ourIP.to_string (), ":", ourPort);
i2p::context.UpdateAddress (ourIP.to_string ().c_str ());
2014-02-21 21:13:36 +00:00
}
2014-04-08 18:03:15 +00:00
void SSUSession::ProcessRelayIntro (uint8_t * buf, size_t len)
{
uint8_t size = *buf;
if (size == 4)
{
buf++; // size
boost::asio::ip::address_v4 address (be32toh (*(uint32_t* )buf));
buf += 4; // address
uint16_t port = be16toh (*(uint16_t *)buf);
// send hole punch of 1 byte
2014-09-13 23:43:25 +00:00
m_Server.Send (buf, 0, boost::asio::ip::udp::endpoint (address, port));
2014-04-08 18:03:15 +00:00
}
else
LogPrint ("Address size ", size, " is not supported");
}
2014-02-09 13:52:56 +00:00
void SSUSession::FillHeaderAndEncrypt (uint8_t payloadType, uint8_t * buf, size_t len,
const uint8_t * aesKey, const uint8_t * iv, const uint8_t * macKey)
2014-01-27 21:52:17 +00:00
{
2014-01-28 21:49:54 +00:00
if (len < sizeof (SSUHeader))
{
LogPrint ("Unexpected SSU packet length ", len);
return;
}
SSUHeader * header = (SSUHeader *)buf;
memcpy (header->iv, iv, 16);
2014-01-29 21:49:53 +00:00
header->flag = payloadType << 4; // MSB is 0
header->time = htobe32 (i2p::util::GetSecondsSinceEpoch ());
2014-01-28 21:49:54 +00:00
uint8_t * encrypted = &header->flag;
uint16_t encryptedLen = len - (encrypted - buf);
2014-06-08 18:43:18 +00:00
i2p::crypto::CBCEncryption encryption;
encryption.SetKey (aesKey);
encryption.SetIV (iv);
encryption.Encrypt (encrypted, encryptedLen, encrypted);
2014-01-28 21:49:54 +00:00
// assume actual buffer size is 18 (16 + 2) bytes more
memcpy (buf + len, iv, 16);
*(uint16_t *)(buf + len + 16) = htobe16 (encryptedLen);
i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, macKey, header->mac);
}
void SSUSession::FillHeaderAndEncrypt (uint8_t payloadType, uint8_t * buf, size_t len)
{
if (len < sizeof (SSUHeader))
{
LogPrint ("Unexpected SSU packet length ", len);
return;
}
SSUHeader * header = (SSUHeader *)buf;
i2p::context.GetRandomNumberGenerator ().GenerateBlock (header->iv, 16); // random iv
m_SessionKeyEncryption.SetIV (header->iv);
header->flag = payloadType << 4; // MSB is 0
header->time = htobe32 (i2p::util::GetSecondsSinceEpoch ());
uint8_t * encrypted = &header->flag;
uint16_t encryptedLen = len - (encrypted - buf);
m_SessionKeyEncryption.Encrypt (encrypted, encryptedLen, encrypted);
// assume actual buffer size is 18 (16 + 2) bytes more
memcpy (buf + len, header->iv, 16);
*(uint16_t *)(buf + len + 16) = htobe16 (encryptedLen);
i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, m_MacKey, header->mac);
}
2014-02-09 13:52:56 +00:00
void SSUSession::Decrypt (uint8_t * buf, size_t len, const uint8_t * aesKey)
2014-01-28 21:49:54 +00:00
{
if (len < sizeof (SSUHeader))
{
LogPrint ("Unexpected SSU packet length ", len);
return;
}
SSUHeader * header = (SSUHeader *)buf;
uint8_t * encrypted = &header->flag;
uint16_t encryptedLen = len - (encrypted - buf);
2014-06-08 18:43:18 +00:00
i2p::crypto::CBCDecryption decryption;
decryption.SetKey (aesKey);
decryption.SetIV (header->iv);
decryption.Decrypt (encrypted, encryptedLen, encrypted);
2014-01-28 21:49:54 +00:00
}
2014-05-15 02:49:22 +00:00
void SSUSession::DecryptSessionKey (uint8_t * buf, size_t len)
{
if (len < sizeof (SSUHeader))
{
LogPrint ("Unexpected SSU packet length ", len);
return;
}
SSUHeader * header = (SSUHeader *)buf;
uint8_t * encrypted = &header->flag;
uint16_t encryptedLen = len - (encrypted - buf);
if (encryptedLen > 0)
{
m_SessionKeyDecryption.SetIV (header->iv);
m_SessionKeyDecryption.Decrypt (encrypted, encryptedLen, encrypted);
}
}
2014-02-09 13:52:56 +00:00
bool SSUSession::Validate (uint8_t * buf, size_t len, const uint8_t * macKey)
2014-01-28 21:49:54 +00:00
{
if (len < sizeof (SSUHeader))
{
LogPrint ("Unexpected SSU packet length ", len);
return false;
}
SSUHeader * header = (SSUHeader *)buf;
uint8_t * encrypted = &header->flag;
uint16_t encryptedLen = len - (encrypted - buf);
// assume actual buffer size is 18 (16 + 2) bytes more
memcpy (buf + len, header->iv, 16);
*(uint16_t *)(buf + len + 16) = htobe16 (encryptedLen);
uint8_t digest[16];
i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, macKey, digest);
return !memcmp (header->mac, digest, 16);
2014-01-24 21:30:07 +00:00
}
2014-01-29 21:49:53 +00:00
void SSUSession::Connect ()
{
2014-03-31 11:51:18 +00:00
if (m_State == eSessionStateUnknown)
2014-03-31 02:55:03 +00:00
{
2014-04-02 14:49:16 +00:00
// set connect timer
2014-09-04 14:20:44 +00:00
ScheduleConnectTimer ();
2014-09-18 16:43:02 +00:00
m_DHKeysPair = i2p::transports.GetNextDHKeysPair ();
2014-03-31 11:51:18 +00:00
SendSessionRequest ();
}
2014-01-29 21:49:53 +00:00
}
2014-09-04 14:20:44 +00:00
void SSUSession::ScheduleConnectTimer ()
{
m_Timer.cancel ();
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
m_Timer.async_wait (boost::bind (&SSUSession::HandleConnectTimer,
this, boost::asio::placeholders::error));
}
2014-03-31 02:55:03 +00:00
void SSUSession::HandleConnectTimer (const boost::system::error_code& ecode)
{
if (!ecode)
{
// timeout expired
LogPrint ("SSU session was not established after ", SSU_CONNECT_TIMEOUT, " second");
Failed ();
}
}
2014-04-09 15:58:57 +00:00
void SSUSession::Introduce (uint32_t iTag, const uint8_t * iKey)
2014-04-02 14:49:16 +00:00
{
if (m_State == eSessionStateUnknown)
{
// set connect timer
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
m_Timer.async_wait (boost::bind (&SSUSession::HandleConnectTimer,
2014-04-09 22:17:13 +00:00
this, boost::asio::placeholders::error));
}
SendRelayRequest (iTag, iKey);
2014-02-21 21:13:36 +00:00
}
2014-04-09 15:58:57 +00:00
void SSUSession::WaitForIntroduction ()
{
m_State = eSessionStateIntroduced;
2014-04-09 15:58:57 +00:00
// set connect timer
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
m_Timer.async_wait (boost::bind (&SSUSession::HandleConnectTimer,
this, boost::asio::placeholders::error));
}
2014-02-09 02:06:40 +00:00
void SSUSession::Close ()
{
SendSesionDestroyed ();
2014-02-09 23:28:34 +00:00
if (!m_DelayedMessages.empty ())
{
for (auto it :m_DelayedMessages)
2014-07-06 21:48:16 +00:00
DeleteI2NPMessage (it);
2014-02-09 23:28:34 +00:00
m_DelayedMessages.clear ();
}
}
void SSUSession::Established ()
{
2014-04-22 15:39:26 +00:00
m_State = eSessionStateEstablished;
2014-09-18 16:43:02 +00:00
if (m_DHKeysPair)
{
delete m_DHKeysPair;
m_DHKeysPair = nullptr;
}
2014-02-10 20:13:16 +00:00
SendI2NPMessage (CreateDatabaseStoreMsg ());
2014-02-09 23:28:34 +00:00
if (!m_DelayedMessages.empty ())
{
for (auto it :m_DelayedMessages)
2014-06-10 14:39:29 +00:00
m_Data.Send (it);
2014-02-09 23:28:34 +00:00
m_DelayedMessages.clear ();
2014-04-07 23:28:06 +00:00
}
if (m_PeerTest && (m_RemoteRouter && m_RemoteRouter->IsPeerTesting ()))
2014-04-07 23:28:06 +00:00
SendPeerTest ();
2014-04-08 01:40:28 +00:00
ScheduleTermination ();
2014-02-09 02:06:40 +00:00
}
void SSUSession::Failed ()
{
2014-03-31 02:55:03 +00:00
if (m_State != eSessionStateFailed)
{
m_State = eSessionStateFailed;
2014-04-02 14:49:16 +00:00
m_Server.DeleteSession (this); // delete this
2014-03-31 02:55:03 +00:00
}
}
2014-04-08 01:40:28 +00:00
void SSUSession::ScheduleTermination ()
{
m_Timer.cancel ();
m_Timer.expires_from_now (boost::posix_time::seconds(SSU_TERMINATION_TIMEOUT));
m_Timer.async_wait (boost::bind (&SSUSession::HandleTerminationTimer,
this, boost::asio::placeholders::error));
}
void SSUSession::HandleTerminationTimer (const boost::system::error_code& ecode)
{
if (ecode != boost::asio::error::operation_aborted)
{
LogPrint ("SSU no activity fo ", SSU_TERMINATION_TIMEOUT, " seconds");
2014-04-08 02:26:18 +00:00
Failed ();
2014-04-08 01:40:28 +00:00
}
}
2014-09-05 20:35:02 +00:00
2014-02-12 21:36:13 +00:00
const uint8_t * SSUSession::GetIntroKey () const
{
if (m_RemoteRouter)
{
// we are client
auto address = m_RemoteRouter->GetSSUAddress ();
2014-09-18 00:43:47 +00:00
return address ? (const uint8_t *)address->key : nullptr;
2014-02-12 21:36:13 +00:00
}
else
{
// we are server
auto address = i2p::context.GetRouterInfo ().GetSSUAddress ();
2014-09-18 00:43:47 +00:00
return address ? (const uint8_t *)address->key : nullptr;
2014-02-12 21:36:13 +00:00
}
}
2014-01-29 21:49:53 +00:00
void SSUSession::SendI2NPMessage (I2NPMessage * msg)
2014-08-30 20:30:53 +00:00
{
m_Server.GetService ().post (boost::bind (&SSUSession::PostI2NPMessage, this, msg));
}
void SSUSession::PostI2NPMessage (I2NPMessage * msg)
2014-01-29 21:49:53 +00:00
{
2014-02-09 23:28:34 +00:00
if (msg)
{
if (m_State == eSessionStateEstablished)
2014-06-10 14:39:29 +00:00
m_Data.Send (msg);
2014-02-09 23:28:34 +00:00
else
m_DelayedMessages.push_back (msg);
}
2014-08-30 20:30:53 +00:00
}
2014-02-05 20:07:47 +00:00
void SSUSession::ProcessData (uint8_t * buf, size_t len)
{
2014-04-22 15:39:26 +00:00
m_Data.ProcessMessage (buf, len);
2014-02-05 20:07:47 +00:00
}
2014-04-07 19:31:38 +00:00
void SSUSession::ProcessPeerTest (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
{
uint8_t * buf1 = buf;
uint32_t nonce = be32toh (*(uint32_t *)buf);
buf += 4; // nonce
uint8_t size = *buf;
buf++; // size
uint32_t address = (size == 4) ? *(uint32_t *)buf : 0; // use it as is
2014-04-07 19:31:38 +00:00
buf += size; // address
uint16_t port = *(uint16_t *)buf; // use it as is
buf += 2; // port
uint8_t * introKey = buf;
2014-04-09 18:58:30 +00:00
if (port && !address)
2014-04-07 19:31:38 +00:00
{
2014-04-09 18:58:30 +00:00
LogPrint ("Address of ", size, " bytes not supported");
return;
}
if (m_PeerTestNonces.count (nonce) > 0)
{
// existing test
if (m_PeerTest)
{
LogPrint ("SSU peer test from Bob. We are Alice");
m_PeerTestNonces.erase (nonce);
m_PeerTest = false;
}
else if (port)
2014-04-09 18:58:30 +00:00
{
LogPrint ("SSU peer test from Charlie. We are Bob");
boost::asio::ip::udp::endpoint ep (boost::asio::ip::address_v4 (be32toh (address)), be16toh (port)); // Alice's address/port
2014-09-04 20:27:22 +00:00
auto session = m_Server.FindSession (ep); // find session with Alice
if (session)
session->Send (PAYLOAD_TYPE_PEER_TEST, buf1, len); // back to Alice
2014-04-09 18:58:30 +00:00
}
2014-04-07 19:31:38 +00:00
else
2014-04-09 18:58:30 +00:00
{
LogPrint ("SSU peer test from Alice. We are Charlie");
2014-09-04 20:27:22 +00:00
SendPeerTest (nonce, senderEndpoint.address ().to_v4 ().to_ulong (),
senderEndpoint.port (), introKey); // to Alice
2014-04-09 18:58:30 +00:00
}
2014-04-07 19:31:38 +00:00
}
else
{
2014-09-22 23:03:46 +00:00
if (m_State == eSessionStateEstablished)
2014-04-09 18:58:30 +00:00
{
2014-09-22 23:03:46 +00:00
// new test
m_PeerTestNonces.insert (nonce);
if (port)
{
LogPrint ("SSU peer test from Bob. We are Charlie");
Send (PAYLOAD_TYPE_PEER_TEST, buf1, len); // back to Bob
SendPeerTest (nonce, be32toh (address), be16toh (port), introKey); // to Alice
}
else
{
LogPrint ("SSU peer test from Alice. We are Bob");
auto session = m_Server.GetRandomEstablishedSession (this); // charlie
if (session)
session->SendPeerTest (nonce, senderEndpoint.address ().to_v4 ().to_ulong (),
senderEndpoint.port (), introKey, false);
}
2014-04-09 18:58:30 +00:00
}
else
2014-09-22 23:03:46 +00:00
LogPrint ("SSU peer test from Charlie. We are Alice");
2014-04-07 19:31:38 +00:00
}
}
2014-09-03 23:31:43 +00:00
void SSUSession::SendPeerTest (uint32_t nonce, uint32_t address, uint16_t port,
2014-09-04 20:27:22 +00:00
const uint8_t * introKey, bool toAddress)
2014-04-07 19:31:38 +00:00
{
uint8_t buf[80 + 18];
uint8_t iv[16];
uint8_t * payload = buf + sizeof (SSUHeader);
*(uint32_t *)payload = htobe32 (nonce);
payload += 4; // nonce
if (address)
{
*payload = 4;
payload++; // size
*(uint32_t *)payload = htobe32 (address);
payload += 4; // address
}
else
{
*payload = 0;
payload++; //size
}
2014-09-03 23:31:43 +00:00
*(uint16_t *)payload = htobe16 (port);
2014-04-07 19:31:38 +00:00
payload += 2; // port
memcpy (payload, introKey, 32); // intro key
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
2014-09-03 23:31:43 +00:00
if (toAddress)
{
// encrypt message with specified intro key
FillHeaderAndEncrypt (PAYLOAD_TYPE_PEER_TEST, buf, 80, introKey, iv, introKey);
boost::asio::ip::udp::endpoint e (boost::asio::ip::address_v4 (address), port);
m_Server.Send (buf, 80, e);
}
else
{
// encrypt message with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_PEER_TEST, buf, 80);
Send (buf, 80);
}
2014-04-07 19:31:38 +00:00
}
2014-04-07 20:19:33 +00:00
void SSUSession::SendPeerTest ()
{
2014-04-07 23:28:06 +00:00
LogPrint ("SSU sending peer test");
2014-04-07 22:54:28 +00:00
auto address = i2p::context.GetRouterInfo ().GetSSUAddress ();
if (!address)
2014-04-07 20:19:33 +00:00
{
LogPrint ("SSU is not supported. Can't send peer test");
return;
}
2014-09-04 20:27:22 +00:00
uint32_t nonce = i2p::context.GetRandomNumberGenerator ().GenerateWord32 ();
if (!nonce) nonce = 1;
m_PeerTestNonces.insert (nonce);
2014-09-04 23:46:35 +00:00
SendPeerTest (nonce, 0, 0, address->key, false); // address and port always zero for Alice
2014-04-07 20:19:33 +00:00
}
2014-09-05 20:35:02 +00:00
void SSUSession::SendKeepAlive ()
{
2014-09-07 00:43:20 +00:00
if (m_State == eSessionStateEstablished)
{
uint8_t buf[48 + 18];
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = 0; // flags
payload++;
*payload = 0; // num fragments
// encrypt message with session key
2014-09-12 15:41:29 +00:00
FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, 48);
2014-09-07 00:43:20 +00:00
Send (buf, 48);
LogPrint ("SSU keep-alive sent");
ScheduleTermination ();
}
2014-09-05 20:35:02 +00:00
}
2014-02-07 20:47:10 +00:00
2014-02-09 02:06:40 +00:00
void SSUSession::SendSesionDestroyed ()
{
2014-04-13 20:59:54 +00:00
if (m_IsSessionKey)
{
uint8_t buf[48 + 18];
2014-02-12 21:36:13 +00:00
// encrypt message with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_DESTROYED, buf, 48);
2014-06-10 14:39:29 +00:00
Send (buf, 48);
2014-08-19 15:03:08 +00:00
LogPrint ("SSU session destroyed sent");
2014-02-12 21:36:13 +00:00
}
2014-02-09 02:06:40 +00:00
}
2014-02-09 23:28:34 +00:00
2014-04-07 19:31:38 +00:00
void SSUSession::Send (uint8_t type, const uint8_t * payload, size_t len)
{
uint8_t buf[SSU_MTU + 18];
size_t msgSize = len + sizeof (SSUHeader);
if (msgSize > SSU_MTU)
{
LogPrint ("SSU payload size ", msgSize, " exceeds MTU");
return;
}
memcpy (buf + sizeof (SSUHeader), payload, len);
// encrypt message with session key
FillHeaderAndEncrypt (type, buf, msgSize);
2014-06-10 14:39:29 +00:00
Send (buf, msgSize);
2014-04-07 19:31:38 +00:00
}
2014-06-10 14:39:29 +00:00
void SSUSession::Send (const uint8_t * buf, size_t size)
{
m_NumSentBytes += size;
2014-06-10 14:39:29 +00:00
m_Server.Send (buf, size, m_RemoteEndpoint);
}
2014-09-05 20:35:02 +00:00
2014-04-20 00:45:41 +00:00
SSUServer::SSUServer (int port): m_Thread (nullptr), m_Work (m_Service),
2014-09-07 00:43:20 +00:00
m_Endpoint (boost::asio::ip::udp::v4 (), port), m_Socket (m_Service, m_Endpoint),
m_IntroducersUpdateTimer (m_Service)
2014-01-23 21:10:33 +00:00
{
2014-02-07 20:47:10 +00:00
m_Socket.set_option (boost::asio::socket_base::receive_buffer_size (65535));
m_Socket.set_option (boost::asio::socket_base::send_buffer_size (65535));
2014-01-23 21:10:33 +00:00
}
2014-01-24 21:30:07 +00:00
SSUServer::~SSUServer ()
{
for (auto it: m_Sessions)
delete it.second;
}
2014-01-23 21:10:33 +00:00
void SSUServer::Start ()
{
2014-04-20 00:45:41 +00:00
m_IsRunning = true;
m_Thread = new std::thread (std::bind (&SSUServer::Run, this));
m_Service.post (boost::bind (&SSUServer::Receive, this));
2014-09-08 20:43:20 +00:00
if (i2p::context.IsUnreachable ())
ScheduleIntroducersUpdateTimer ();
2014-01-23 21:10:33 +00:00
}
void SSUServer::Stop ()
{
2014-02-11 00:27:55 +00:00
DeleteAllSessions ();
2014-04-20 00:45:41 +00:00
m_IsRunning = false;
m_Service.stop ();
2014-01-23 21:10:33 +00:00
m_Socket.close ();
2014-04-20 00:45:41 +00:00
if (m_Thread)
{
m_Thread->join ();
delete m_Thread;
m_Thread = 0;
}
2014-01-23 21:10:33 +00:00
}
2014-04-20 00:45:41 +00:00
void SSUServer::Run ()
{
while (m_IsRunning)
{
try
{
m_Service.run ();
}
catch (std::exception& ex)
{
LogPrint ("SSU server: ", ex.what ());
}
}
}
2014-04-16 19:54:28 +00:00
void SSUServer::AddRelay (uint32_t tag, const boost::asio::ip::udp::endpoint& relay)
{
m_Relays[tag] = relay;
}
SSUSession * SSUServer::FindRelaySession (uint32_t tag)
{
auto it = m_Relays.find (tag);
if (it != m_Relays.end ())
return FindSession (it->second);
return nullptr;
}
2014-06-10 14:39:29 +00:00
void SSUServer::Send (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& to)
2014-01-28 21:49:54 +00:00
{
m_Socket.send_to (boost::asio::buffer (buf, len), to);
}
2014-01-23 21:10:33 +00:00
void SSUServer::Receive ()
{
m_Socket.async_receive_from (boost::asio::buffer (m_ReceiveBuffer, SSU_MTU), m_SenderEndpoint,
boost::bind (&SSUServer::HandleReceivedFrom, this, boost::asio::placeholders::error, boost::asio::placeholders::bytes_transferred));
}
void SSUServer::HandleReceivedFrom (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{
if (!ecode)
{
2014-01-24 21:30:07 +00:00
SSUSession * session = nullptr;
auto it = m_Sessions.find (m_SenderEndpoint);
if (it != m_Sessions.end ())
session = it->second;
2014-01-28 21:49:54 +00:00
if (!session)
2014-01-24 21:30:07 +00:00
{
2014-04-02 14:49:16 +00:00
session = new SSUSession (*this, m_SenderEndpoint);
2014-01-24 21:30:07 +00:00
m_Sessions[m_SenderEndpoint] = session;
LogPrint ("New SSU session from ", m_SenderEndpoint.address ().to_string (), ":", m_SenderEndpoint.port (), " created");
}
2014-01-29 21:49:53 +00:00
session->ProcessNextMessage (m_ReceiveBuffer, bytes_transferred, m_SenderEndpoint);
2014-01-23 21:10:33 +00:00
Receive ();
}
else
LogPrint ("SSU receive error: ", ecode.message ());
}
2014-01-28 21:49:54 +00:00
2014-03-26 01:17:03 +00:00
SSUSession * SSUServer::FindSession (const i2p::data::RouterInfo * router)
{
if (!router) return nullptr;
auto address = router->GetSSUAddress ();
if (!address) return nullptr;
2014-04-16 19:54:28 +00:00
return FindSession (boost::asio::ip::udp::endpoint (address->host, address->port));
}
SSUSession * SSUServer::FindSession (const boost::asio::ip::udp::endpoint& e)
{
auto it = m_Sessions.find (e);
2014-03-26 01:17:03 +00:00
if (it != m_Sessions.end ())
return it->second;
else
return nullptr;
2014-04-16 19:54:28 +00:00
}
2014-03-26 01:17:03 +00:00
2014-04-07 23:28:06 +00:00
SSUSession * SSUServer::GetSession (const i2p::data::RouterInfo * router, bool peerTest)
2014-01-28 21:49:54 +00:00
{
SSUSession * session = nullptr;
if (router)
{
auto address = router->GetSSUAddress ();
if (address)
{
boost::asio::ip::udp::endpoint remoteEndpoint (address->host, address->port);
auto it = m_Sessions.find (remoteEndpoint);
if (it != m_Sessions.end ())
session = it->second;
else
{
2014-02-21 21:13:36 +00:00
// otherwise create new session
2014-04-09 15:58:57 +00:00
session = new SSUSession (*this, remoteEndpoint, router, peerTest);
m_Sessions[remoteEndpoint] = session;
2014-02-21 21:13:36 +00:00
if (!router->UsesIntroducer ())
{
2014-04-09 15:58:57 +00:00
// connect directly
2014-04-07 23:28:06 +00:00
LogPrint ("Creating new SSU session to [", router->GetIdentHashAbbreviation (), "] ",
remoteEndpoint.address ().to_string (), ":", remoteEndpoint.port ());
2014-02-21 21:13:36 +00:00
session->Connect ();
}
else
{
2014-03-19 16:02:51 +00:00
// connect through introducer
int numIntroducers = address->introducers.size ();
2014-09-13 23:43:25 +00:00
if (numIntroducers > 0)
2014-03-19 16:02:51 +00:00
{
2014-04-09 15:58:57 +00:00
SSUSession * introducerSession = nullptr;
const i2p::data::RouterInfo::Introducer * introducer = nullptr;
// we might have a session to introducer already
for (int i = 0; i < numIntroducers; i++)
2014-04-08 19:35:08 +00:00
{
introducer = &(address->introducers[i]);
it = m_Sessions.find (boost::asio::ip::udp::endpoint (introducer->iHost, introducer->iPort));
if (it != m_Sessions.end ())
{
introducerSession = it->second;
break;
}
}
if (introducerSession) // session found
2014-04-08 19:35:08 +00:00
LogPrint ("Session to introducer already exists");
else // create new
2014-04-09 15:58:57 +00:00
{
LogPrint ("Creating new session to introducer");
introducer = &(address->introducers[0]); // TODO:
boost::asio::ip::udp::endpoint introducerEndpoint (introducer->iHost, introducer->iPort);
2014-04-09 15:58:57 +00:00
introducerSession = new SSUSession (*this, introducerEndpoint, router);
m_Sessions[introducerEndpoint] = introducerSession;
}
// introduce
LogPrint ("Introduce new SSU session to [", router->GetIdentHashAbbreviation (),
"] through introducer ", introducer->iHost, ":", introducer->iPort);
session->WaitForIntroduction ();
2014-09-13 23:43:25 +00:00
if (i2p::context.GetRouterInfo ().UsesIntroducer ()) // if we are unreachable
Send (m_ReceiveBuffer, 0, remoteEndpoint); // send HolePunch
introducerSession->Introduce (introducer->iTag, introducer->iKey);
2014-03-19 16:02:51 +00:00
}
else
2014-07-20 22:16:55 +00:00
{
2014-09-13 23:43:25 +00:00
LogPrint ("Can't connect to unreachable router. No introducers presented");
2014-07-20 22:16:55 +00:00
m_Sessions.erase (remoteEndpoint);
delete session;
session = nullptr;
}
2014-02-21 21:13:36 +00:00
}
2014-01-28 21:49:54 +00:00
}
}
else
LogPrint ("Router ", router->GetIdentHashAbbreviation (), " doesn't have SSU address");
}
return session;
}
2014-02-09 02:06:40 +00:00
void SSUServer::DeleteSession (SSUSession * session)
{
if (session)
{
session->Close ();
m_Sessions.erase (session->GetRemoteEndpoint ());
delete session;
}
}
void SSUServer::DeleteAllSessions ()
{
for (auto it: m_Sessions)
{
it.second->Close ();
delete it.second;
}
m_Sessions.clear ();
2014-02-21 21:13:36 +00:00
}
2014-09-03 20:49:48 +00:00
template<typename Filter>
SSUSession * SSUServer::GetRandomSession (Filter filter)
{
std::vector<SSUSession *> filteredSessions;
for (auto s :m_Sessions)
if (filter (s.second)) filteredSessions.push_back (s.second);
if (filteredSessions.size () > 0)
{
auto ind = i2p::context.GetRandomNumberGenerator ().GenerateWord32 (0, filteredSessions.size ()-1);
return filteredSessions[ind];
}
return nullptr;
}
2014-09-05 20:35:02 +00:00
SSUSession * SSUServer::GetRandomEstablishedSession (const SSUSession * excluded)
2014-09-03 20:49:48 +00:00
{
return GetRandomSession (
2014-09-05 20:35:02 +00:00
[excluded](SSUSession * session)->bool
{
return session->GetState () == eSessionStateEstablished &&
session != excluded;
}
);
}
2014-09-07 00:43:20 +00:00
std::set<SSUSession *> SSUServer::FindIntroducers (int maxNumIntroducers)
2014-09-05 20:35:02 +00:00
{
2014-09-09 17:45:12 +00:00
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
2014-09-05 20:35:02 +00:00
std::set<SSUSession *> ret;
for (int i = 0; i < maxNumIntroducers; i++)
{
auto session = GetRandomSession (
2014-09-09 17:45:12 +00:00
[&ret, ts](SSUSession * session)->bool
2014-09-03 20:49:48 +00:00
{
2014-09-05 20:35:02 +00:00
return session->GetRelayTag () && !ret.count (session) &&
2014-09-09 17:45:12 +00:00
session->GetState () == eSessionStateEstablished &&
ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION;
2014-09-03 20:49:48 +00:00
}
2014-09-05 20:35:02 +00:00
);
if (session)
{
ret.insert (session);
break;
}
}
return ret;
2014-09-03 20:49:48 +00:00
}
2014-09-07 00:43:20 +00:00
void SSUServer::ScheduleIntroducersUpdateTimer ()
{
m_IntroducersUpdateTimer.expires_from_now (boost::posix_time::seconds(SSU_KEEP_ALIVE_INTERVAL));
m_IntroducersUpdateTimer.async_wait (boost::bind (&SSUServer::HandleIntroducersUpdateTimer,
this, boost::asio::placeholders::error));
}
void SSUServer::HandleIntroducersUpdateTimer (const boost::system::error_code& ecode)
{
if (!ecode)
{
// timeout expired
std::list<boost::asio::ip::udp::endpoint> newList;
2014-09-09 12:03:05 +00:00
size_t numIntroducers = 0;
2014-09-09 17:45:12 +00:00
uint32_t ts = i2p::util::GetSecondsSinceEpoch ();
2014-09-07 00:43:20 +00:00
for (auto it :m_Introducers)
{
auto session = FindSession (it);
2014-09-09 17:45:12 +00:00
if (session && ts < session->GetCreationTime () + SSU_TO_INTRODUCER_SESSION_DURATION)
2014-09-07 00:43:20 +00:00
{
session->SendKeepAlive ();
newList.push_back (it);
numIntroducers++;
}
else
i2p::context.RemoveIntroducer (it);
}
2014-09-09 01:53:55 +00:00
if (numIntroducers < SSU_MAX_NUM_INTRODUCERS)
2014-09-07 00:43:20 +00:00
{
// create new
2014-09-09 12:03:05 +00:00
auto introducers = FindIntroducers (SSU_MAX_NUM_INTRODUCERS);
2014-09-07 00:43:20 +00:00
if (introducers.size () > 0)
{
for (auto it1: introducers)
{
auto router = it1->GetRemoteRouter ();
if (router && i2p::context.AddIntroducer (*router, it1->GetRelayTag ()))
2014-09-09 12:03:05 +00:00
{
newList.push_back (it1->GetRemoteEndpoint ());
if (newList.size () >= SSU_MAX_NUM_INTRODUCERS) break;
}
2014-09-07 00:43:20 +00:00
}
}
}
m_Introducers = newList;
ScheduleIntroducersUpdateTimer ();
}
}
2014-01-23 21:10:33 +00:00
}
}