i2pd/SSU.cpp

716 lines
21 KiB
C++
Raw Normal View History

2014-01-29 01:49:54 +04:00
#include <string.h>
2014-01-24 01:10:33 +04:00
#include <boost/bind.hpp>
2014-01-30 01:49:53 +04:00
#include <cryptopp/dh.h>
#include <cryptopp/secblock.h>
#include "CryptoConst.h"
2014-01-24 01:10:33 +04:00
#include "Log.h"
2014-01-30 01:49:53 +04:00
#include "Timestamp.h"
2014-01-29 01:49:54 +04:00
#include "RouterContext.h"
2014-01-24 01:10:33 +04:00
#include "hmac.h"
#include "SSU.h"
namespace i2p
{
namespace ssu
{
2014-01-25 01:30:07 +04:00
2014-02-09 17:52:56 +04:00
SSUSession::SSUSession (SSUServer * server, boost::asio::ip::udp::endpoint& remoteEndpoint,
const i2p::data::RouterInfo * router): m_Server (server), m_RemoteEndpoint (remoteEndpoint),
2014-01-30 01:49:53 +04:00
m_RemoteRouter (router), m_State (eSessionStateUnknown)
2014-01-25 01:30:07 +04:00
{
}
2014-02-03 23:40:38 +04:00
void SSUSession::CreateAESandMacKey (uint8_t * pubKey, uint8_t * aesKey, uint8_t * macKey)
2014-01-30 01:49:53 +04:00
{
CryptoPP::DH dh (i2p::crypto::elgp, i2p::crypto::elgg);
CryptoPP::SecByteBlock secretKey(dh.AgreedValueLength());
if (!dh.Agree (secretKey, i2p::context.GetPrivateKey (), pubKey))
{
LogPrint ("Couldn't create shared key");
return;
};
if (secretKey[0] & 0x80)
{
aesKey[0] = 0;
memcpy (aesKey + 1, secretKey, 31);
2014-02-03 23:40:38 +04:00
memcpy (macKey, secretKey + 31, 32);
2014-01-30 01:49:53 +04:00
}
2014-02-03 23:40:38 +04:00
else
{
2014-01-30 01:49:53 +04:00
memcpy (aesKey, secretKey, 32);
2014-02-03 23:40:38 +04:00
memcpy (macKey, secretKey + 32, 32);
}
2014-01-30 01:49:53 +04:00
}
void SSUSession::ProcessNextMessage (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
2014-01-25 01:30:07 +04:00
{
2014-01-28 01:52:17 +04:00
switch (m_State)
{
2014-02-11 00:13:16 +04:00
case eSessionStateConfirmedSent:
2014-02-08 06:42:35 +04:00
case eSessionStateEstablished:
2014-02-06 00:07:47 +04:00
// most common case
ProcessMessage (buf, len);
break;
// establishing
2014-01-29 01:49:54 +04:00
case eSessionStateUnknown:
2014-01-30 01:49:53 +04:00
// session request
ProcessSessionRequest (buf, len, senderEndpoint);
break;
case eSessionStateRequestSent:
// session created
ProcessSessionCreated (buf, len);
2014-01-29 01:49:54 +04:00
break;
2014-02-04 23:20:58 +04:00
case eSessionStateCreatedSent:
// session confirmed
ProcessSessionConfirmed (buf, len);
break;
2014-01-28 01:52:17 +04:00
default:
LogPrint ("SSU state not implemented yet");
}
}
2014-02-06 00:07:47 +04:00
void SSUSession::ProcessMessage (uint8_t * buf, size_t len)
{
if (Validate (buf, len, m_MacKey))
{
Decrypt (buf, len, m_SessionKey);
SSUHeader * header = (SSUHeader *)buf;
uint8_t payloadType = header->flag >> 4;
switch (payloadType)
{
case PAYLOAD_TYPE_DATA:
LogPrint ("SSU data received");
ProcessData (buf + sizeof (SSUHeader), len - sizeof (SSUHeader));
break;
case PAYLOAD_TYPE_TEST:
LogPrint ("SSU test received");
break;
2014-02-09 06:06:40 +04:00
case PAYLOAD_TYPE_SESSION_DESTROYED:
2014-02-12 00:51:32 +04:00
{
2014-02-06 00:07:47 +04:00
LogPrint ("SSU session destroy received");
2014-02-12 00:51:32 +04:00
if (m_Server)
m_Server->DeleteSession (this); // delete this
}
2014-02-06 00:07:47 +04:00
break;
default:
LogPrint ("Unexpected SSU payload type ", (int)payloadType);
}
}
else
2014-02-13 01:36:13 +04:00
{
LogPrint ("MAC key failed. Trying intro key");
auto introKey = GetIntroKey ();
if (introKey && Validate (buf, len, introKey))
{
Decrypt (buf, len, introKey);
SSUHeader * header = (SSUHeader *)buf;
LogPrint ("Unexpected SSU payload type ", (int)(header->flag >> 4));
// TODO:
}
else
LogPrint ("MAC verifcation failed");
2014-02-12 00:51:32 +04:00
m_State = eSessionStateUnknown;
}
2014-02-06 00:07:47 +04:00
}
2014-01-30 01:49:53 +04:00
void SSUSession::ProcessSessionRequest (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
{
LogPrint ("Process session request");
// use our intro key
2014-02-13 01:36:13 +04:00
if (ProcessIntroKeyEncryptedMessage (PAYLOAD_TYPE_SESSION_REQUEST, buf, len))
2014-01-30 01:49:53 +04:00
{
m_State = eSessionStateRequestReceived;
LogPrint ("Session request received");
2014-01-30 23:03:11 +04:00
m_RemoteEndpoint = senderEndpoint;
SendSessionCreated (buf + sizeof (SSUHeader));
2014-01-30 01:49:53 +04:00
}
}
void SSUSession::ProcessSessionCreated (uint8_t * buf, size_t len)
{
LogPrint ("Process session created");
if (!m_RemoteRouter)
{
LogPrint ("Unsolicited session created message");
return;
}
// use remote intro key
2014-02-13 01:36:13 +04:00
if (ProcessIntroKeyEncryptedMessage (PAYLOAD_TYPE_SESSION_CREATED, buf, len))
2014-01-30 01:49:53 +04:00
{
m_State = eSessionStateCreatedReceived;
LogPrint ("Session created received");
2014-02-04 23:20:58 +04:00
uint8_t * ourAddress = buf + sizeof (SSUHeader) + 257;
boost::asio::ip::address_v4 ourIP (be32toh (*(uint32_t* )(ourAddress)));
uint16_t ourPort = be16toh (*(uint16_t *)(ourAddress + 4));
LogPrint ("Our external address is ", ourIP.to_string (), ":", ourPort);
2014-02-09 06:06:40 +04:00
i2p::context.UpdateAddress (ourIP.to_string ().c_str ());
2014-02-04 23:20:58 +04:00
uint32_t relayTag = be32toh (*(uint32_t *)(buf + sizeof (SSUHeader) + 263));
SendSessionConfirmed (buf + sizeof (SSUHeader), ourAddress, relayTag);
2014-01-30 01:49:53 +04:00
}
}
2014-02-04 23:20:58 +04:00
void SSUSession::ProcessSessionConfirmed (uint8_t * buf, size_t len)
{
LogPrint ("Process session confirmed");
if (Validate (buf, len, m_MacKey))
{
Decrypt (buf, len, m_SessionKey);
SSUHeader * header = (SSUHeader *)buf;
if ((header->flag >> 4) == PAYLOAD_TYPE_SESSION_CONFIRMED)
{
m_State = eSessionStateConfirmedReceived;
2014-02-11 00:13:16 +04:00
LogPrint ("Session confirmed received");
2014-02-08 06:42:35 +04:00
m_State = eSessionStateEstablished;
2014-02-11 00:13:16 +04:00
// TODO: send DeliverStatus
2014-02-10 03:28:34 +04:00
Established ();
2014-02-04 23:20:58 +04:00
}
else
LogPrint ("Unexpected payload type ", (int)(header->flag >> 4));
}
else
LogPrint ("MAC verifcation failed");
}
2014-01-30 01:49:53 +04:00
void SSUSession::SendSessionRequest ()
{
2014-02-13 01:36:13 +04:00
auto introKey = GetIntroKey ();
if (!introKey)
2014-01-30 01:49:53 +04:00
{
2014-02-13 01:36:13 +04:00
LogPrint ("SSU is not supported");
2014-01-30 01:49:53 +04:00
return;
}
uint8_t buf[304 + 18]; // 304 bytes for ipv4 (320 for ipv6)
uint8_t * payload = buf + sizeof (SSUHeader);
memcpy (payload, i2p::context.GetRouterIdentity ().publicKey, 256);
payload[256] = 4; // we assume ipv4
2014-02-05 07:51:46 +04:00
*(uint32_t *)(payload + 257) = htobe32 (m_RemoteEndpoint.address ().to_v4 ().to_ulong ());
2014-01-30 01:49:53 +04:00
uint8_t iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
2014-02-13 01:36:13 +04:00
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_REQUEST, buf, 304, introKey, iv, introKey);
2014-01-30 01:49:53 +04:00
m_State = eSessionStateRequestSent;
m_Server->Send (buf, 304, m_RemoteEndpoint);
}
2014-01-30 23:03:11 +04:00
void SSUSession::SendSessionCreated (const uint8_t * x)
2014-01-30 01:49:53 +04:00
{
2014-02-13 01:36:13 +04:00
auto introKey = GetIntroKey ();
if (!introKey)
2014-01-30 01:49:53 +04:00
{
2014-02-13 01:36:13 +04:00
LogPrint ("SSU is not supported");
2014-01-30 01:49:53 +04:00
return;
}
2014-01-30 23:03:11 +04: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-30 01:49:53 +04:00
2014-01-30 23:03:11 +04:00
uint8_t buf[368 + 18];
2014-01-30 01:49:53 +04:00
uint8_t * payload = buf + sizeof (SSUHeader);
memcpy (payload, i2p::context.GetRouterIdentity ().publicKey, 256);
2014-01-30 23:03:11 +04: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 23:03:11 +04: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-04 23:20:58 +04:00
*(uint32_t *)(signedData + 518) = htobe32 (m_Server->GetEndpoint ().address ().to_v4 ().to_ulong ()); // our IP
2014-01-30 23:03:11 +04:00
*(uint16_t *)(signedData + 522) = htobe16 (m_Server->GetEndpoint ().port ()); // our port
*(uint32_t *)(payload) = 0; // relay tag, always 0 for now
payload += 4;
*(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-30 01:49:53 +04:00
2014-01-30 23:03:11 +04:00
uint8_t iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
// encrypt signature and 8 bytes padding with newly created session key
m_Encryption.SetKeyWithIV (m_SessionKey, 32, iv);
m_Encryption.ProcessData (payload, payload, 48);
// encrypt message with intro key
2014-02-13 01:36:13 +04:00
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_CREATED, buf, 368, introKey, iv, introKey);
2014-01-30 01:49:53 +04:00
m_State = eSessionStateRequestSent;
m_Server->Send (buf, 368, m_RemoteEndpoint);
}
2014-02-04 23:20:58 +04:00
void SSUSession::SendSessionConfirmed (const uint8_t * y, const uint8_t * ourAddress, uint32_t relayTag)
{
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
memcpy (signedData, i2p::context.GetRouterIdentity ().publicKey, 256); // x
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
*(uint32_t *)(signedData + 524) = htobe32 (relayTag); // relay tag
*(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);
m_State = eSessionStateConfirmedSent;
m_Server->Send (buf, 480, m_RemoteEndpoint);
}
2014-02-13 01:36:13 +04:00
bool SSUSession::ProcessIntroKeyEncryptedMessage (uint8_t expectedPayloadType, uint8_t * buf, size_t len)
2014-01-29 01:49:54 +04:00
{
2014-02-13 01:36:13 +04:00
auto introKey = GetIntroKey ();
if (introKey)
2014-01-29 01:49:54 +04:00
{
// use intro key for verification and decryption
2014-02-13 01:36:13 +04:00
if (Validate (buf, len, introKey))
2014-01-29 01:49:54 +04:00
{
2014-02-13 01:36:13 +04:00
Decrypt (buf, len, introKey);
2014-01-30 01:49:53 +04:00
SSUHeader * header = (SSUHeader *)buf;
if ((header->flag >> 4) == expectedPayloadType)
{
2014-02-03 23:40:38 +04:00
CreateAESandMacKey (buf + sizeof (SSUHeader), m_SessionKey, m_MacKey);
2014-01-30 01:49:53 +04:00
return true;
}
else
LogPrint ("Unexpected payload type ", (int)(header->flag >> 4));
2014-01-29 01:49:54 +04:00
}
else
LogPrint ("MAC verifcation failed");
}
else
2014-02-13 01:36:13 +04:00
LogPrint ("SSU is not supported");
2014-01-30 01:49:53 +04:00
return false;
}
2014-01-29 01:49:54 +04:00
2014-02-09 17:52:56 +04: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-28 01:52:17 +04:00
{
2014-01-29 01:49:54 +04:00
if (len < sizeof (SSUHeader))
{
LogPrint ("Unexpected SSU packet length ", len);
return;
}
SSUHeader * header = (SSUHeader *)buf;
memcpy (header->iv, iv, 16);
2014-01-30 01:49:53 +04:00
header->flag = payloadType << 4; // MSB is 0
header->time = htobe32 (i2p::util::GetSecondsSinceEpoch ());
2014-01-29 01:49:54 +04:00
uint8_t * encrypted = &header->flag;
uint16_t encryptedLen = len - (encrypted - buf);
2014-01-28 01:52:17 +04:00
m_Encryption.SetKeyWithIV (aesKey, 32, iv);
2014-01-29 01:49:54 +04:00
m_Encryption.ProcessData (encrypted, encrypted, encryptedLen);
// 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);
}
2014-02-09 17:52:56 +04:00
void SSUSession::Decrypt (uint8_t * buf, size_t len, const uint8_t * aesKey)
2014-01-29 01:49:54 +04: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);
m_Decryption.SetKeyWithIV (aesKey, 32, header->iv);
encryptedLen = (encryptedLen/16)*16; // make sure 16 bytes boundary
2014-01-29 01:49:54 +04:00
m_Decryption.ProcessData (encrypted, encrypted, encryptedLen);
}
2014-02-09 17:52:56 +04:00
bool SSUSession::Validate (uint8_t * buf, size_t len, const uint8_t * macKey)
2014-01-29 01:49:54 +04: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-25 01:30:07 +04:00
}
2014-01-30 01:49:53 +04:00
void SSUSession::Connect ()
{
SendSessionRequest ();
}
2014-02-09 06:06:40 +04:00
void SSUSession::Close ()
{
SendSesionDestroyed ();
2014-02-10 03:28:34 +04:00
if (!m_DelayedMessages.empty ())
{
for (auto it :m_DelayedMessages)
delete it;
m_DelayedMessages.clear ();
}
}
void SSUSession::Established ()
{
2014-02-11 00:13:16 +04:00
SendI2NPMessage (CreateDatabaseStoreMsg ());
2014-02-10 03:28:34 +04:00
if (!m_DelayedMessages.empty ())
{
for (auto it :m_DelayedMessages)
Send (it);
m_DelayedMessages.clear ();
}
2014-02-09 06:06:40 +04:00
}
2014-02-13 01:36:13 +04:00
const uint8_t * SSUSession::GetIntroKey () const
{
if (m_RemoteRouter)
{
// we are client
auto address = m_RemoteRouter->GetSSUAddress ();
return address ? address->key : nullptr;
}
else
{
// we are server
auto address = i2p::context.GetRouterInfo ().GetSSUAddress ();
return address ? address->key : nullptr;
}
}
2014-01-30 01:49:53 +04:00
void SSUSession::SendI2NPMessage (I2NPMessage * msg)
{
2014-02-10 03:28:34 +04:00
if (msg)
{
if (m_State == eSessionStateEstablished)
Send (msg);
else
m_DelayedMessages.push_back (msg);
}
2014-01-30 01:49:53 +04:00
}
2014-02-10 03:28:34 +04:00
2014-02-06 00:07:47 +04:00
void SSUSession::ProcessData (uint8_t * buf, size_t len)
{
//uint8_t * start = buf;
uint8_t flag = *buf;
buf++;
LogPrint ("Process SSU data flags=", (int)flag);
2014-02-08 06:42:35 +04:00
if (flag & DATA_FLAG_EXPLICIT_ACKS_INCLUDED)
{
// explicit ACKs
uint8_t numAcks =*buf;
buf++;
// TODO: process ACKs
buf += numAcks*4;
}
if (flag & DATA_FLAG_ACK_BITFIELDS_INCLUDED)
{
// explicit ACK bitfields
uint8_t numBitfields =*buf;
buf++;
for (int i = 0; i < numBitfields; i++)
{
buf += 4; // msgID
// TODO: process ACH bitfields
while (*buf & 0x80) // not last
buf++;
buf++; // last byte
}
}
2014-02-06 00:07:47 +04:00
uint8_t numFragments = *buf; // number of fragments
buf++;
for (int i = 0; i < numFragments; i++)
{
uint32_t msgID = be32toh (*(uint32_t *)buf); // message ID
buf += 4;
uint8_t frag[4];
frag[0] = 0;
memcpy (frag + 1, buf, 3);
buf += 3;
uint32_t fragmentInfo = be32toh (*(uint32_t *)frag); // fragment info
uint16_t fragmentSize = fragmentInfo & 0x1FFF; // bits 0 - 13
bool isLast = fragmentInfo & 0x010000; // bit 16
uint8_t fragmentNum = fragmentInfo >> 17; // bits 23 - 17
2014-02-08 00:47:10 +04:00
LogPrint ("SSU data fragment ", (int)fragmentNum, " of message ", msgID, " size=", (int)fragmentSize, isLast ? " last" : " non-last");
2014-02-06 19:16:50 +04:00
I2NPMessage * msg = nullptr;
if (fragmentNum > 0) // follow-up fragment
{
auto it = m_IncomleteMessages.find (msgID);
if (it != m_IncomleteMessages.end ())
2014-02-07 20:26:00 +04:00
{
2014-02-06 19:16:50 +04:00
msg = it->second;
2014-02-07 20:26:00 +04:00
memcpy (msg->buf + msg->len, buf, fragmentSize);
msg->len += fragmentSize;
}
2014-02-06 19:16:50 +04:00
else
// TODO:
LogPrint ("Unexpected follow-on fragment ", fragmentNum, " of message ", msgID);
}
else // first fragment
2014-02-07 20:26:00 +04:00
{
2014-02-06 19:16:50 +04:00
msg = NewI2NPMessage ();
2014-02-07 20:26:00 +04:00
memcpy (msg->GetSSUHeader (), buf, fragmentSize);
msg->len += fragmentSize - sizeof (I2NPHeaderShort);
}
2014-02-06 19:16:50 +04:00
if (msg)
2014-02-07 20:26:00 +04:00
{
2014-02-06 19:16:50 +04:00
if (!fragmentNum && !isLast)
m_IncomleteMessages[msgID] = msg;
if (isLast)
{
2014-02-11 00:13:16 +04:00
SendMsgAck (msgID);
2014-02-06 19:16:50 +04:00
if (fragmentNum > 0)
m_IncomleteMessages.erase (msgID);
2014-02-07 20:26:00 +04:00
msg->FromSSU (msgID);
2014-02-11 00:13:16 +04:00
if (m_State == eSessionStateEstablished)
i2p::HandleI2NPMessage (msg, false);
else
{
// we expect DeliveryStatus
if (msg->GetHeader ()->typeID == eI2NPDeliveryStatus)
{
LogPrint ("SSU session established");
m_State = eSessionStateEstablished;
Established ();
}
else
LogPrint ("SSU unexpected message ", (int)msg->GetHeader ()->typeID);
DeleteI2NPMessage (msg);
}
2014-02-06 19:16:50 +04:00
}
}
buf += fragmentSize;
}
2014-02-06 00:07:47 +04:00
}
2014-02-08 00:47:10 +04:00
void SSUSession::SendMsgAck (uint32_t msgID)
{
2014-02-09 06:06:40 +04:00
uint8_t buf[48 + 18]; // actual length is 44 = 37 + 7 but pad it to multiple of 16
2014-02-08 00:47:10 +04:00
uint8_t iv[16];
2014-02-08 06:42:35 +04:00
uint8_t * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_EXPLICIT_ACKS_INCLUDED; // flag
payload++;
*payload = 1; // number of ACKs
payload++;
*(uint32_t *)(payload) = htobe32 (msgID); // msgID
payload += 4;
*payload = 0; // number of fragments
2014-02-08 00:47:10 +04:00
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
// encrypt message with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, 48, m_SessionKey, iv, m_MacKey);
m_Server->Send (buf, 48, m_RemoteEndpoint);
}
2014-02-09 06:06:40 +04:00
void SSUSession::SendSesionDestroyed ()
{
uint8_t buf[48 + 18], iv[16];
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
2014-02-13 01:36:13 +04:00
if (m_State == eSessionStateEstablished)
// encrypt message with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_DESTROYED, buf, 48, m_SessionKey, iv, m_MacKey);
else
{
auto introKey = GetIntroKey ();
if (introKey)
// encrypt message with intro key
FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_DESTROYED, buf, 48, introKey, iv, introKey);
else
{
LogPrint ("SSU: can't send SessionDestroyed message");
return;
}
}
2014-02-09 06:06:40 +04:00
m_Server->Send (buf, 48, m_RemoteEndpoint);
}
2014-02-10 03:28:34 +04:00
void SSUSession::Send (i2p::I2NPMessage * msg)
{
uint32_t msgID = htobe32 (msg->ToSSU ());
size_t payloadSize = SSU_MTU - sizeof (SSUHeader) - 9; // 9 = flag + #frg(1) + messageID(4) + frag info (3)
size_t len = msg->GetLength ();
uint8_t * msgBuf = msg->GetSSUHeader ();
uint32_t fragmentNum = 0;
while (len > 0)
{
2014-02-11 04:27:55 +04:00
uint8_t buf[SSU_MTU + 18], iv[16], * payload = buf + sizeof (SSUHeader);
*payload = DATA_FLAG_WANT_REPLY; // for compatibility
payload++;
*payload = 1; // always 1 message fragment per message
payload++;
*(uint32_t *)payload = msgID;
payload += 4;
2014-02-10 03:28:34 +04:00
bool isLast = (len <= payloadSize);
size_t size = isLast ? len : payloadSize;
uint32_t fragmentInfo = (fragmentNum << 17);
if (isLast)
fragmentInfo |= 0x010000;
fragmentInfo |= size;
fragmentInfo = htobe32 (fragmentInfo);
2014-02-11 04:27:55 +04:00
memcpy (payload, (uint8_t *)(&fragmentInfo) + 1, 3);
payload += 3;
memcpy (payload, msgBuf, size);
2014-02-10 03:28:34 +04:00
2014-02-11 04:27:55 +04:00
size += payload - buf;
2014-02-10 03:28:34 +04:00
if (size % 16) // make sure 16 bytes boundary
size = (size/16 + 1)*16;
CryptoPP::RandomNumberGenerator& rnd = i2p::context.GetRandomNumberGenerator ();
rnd.GenerateBlock (iv, 16); // random iv
// encrypt message with session key
FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, size, m_SessionKey, iv, m_MacKey);
m_Server->Send (buf, size, m_RemoteEndpoint);
if (!isLast)
{
len -= payloadSize;
msgBuf += payloadSize;
}
else
len = 0;
fragmentNum++;
}
}
2014-02-09 06:06:40 +04:00
2014-01-24 01:10:33 +04:00
SSUServer::SSUServer (boost::asio::io_service& service, int port):
2014-01-30 23:03:11 +04:00
m_Endpoint (boost::asio::ip::udp::v4 (), port), m_Socket (service, m_Endpoint)
2014-01-24 01:10:33 +04:00
{
2014-02-08 00:47:10 +04: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-24 01:10:33 +04:00
}
2014-01-25 01:30:07 +04:00
SSUServer::~SSUServer ()
{
for (auto it: m_Sessions)
delete it.second;
}
2014-01-24 01:10:33 +04:00
void SSUServer::Start ()
{
Receive ();
}
void SSUServer::Stop ()
{
2014-02-11 04:27:55 +04:00
DeleteAllSessions ();
2014-01-24 01:10:33 +04:00
m_Socket.close ();
}
2014-01-29 01:49:54 +04:00
void SSUServer::Send (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& to)
{
m_Socket.send_to (boost::asio::buffer (buf, len), to);
2014-02-10 03:28:34 +04:00
LogPrint ("SSU sent ", len, " bytes");
2014-01-29 01:49:54 +04:00
}
2014-01-24 01:10:33 +04: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)
{
LogPrint ("SSU received ", bytes_transferred, " bytes");
2014-01-25 01:30:07 +04:00
SSUSession * session = nullptr;
auto it = m_Sessions.find (m_SenderEndpoint);
if (it != m_Sessions.end ())
session = it->second;
2014-01-29 01:49:54 +04:00
if (!session)
2014-01-25 01:30:07 +04:00
{
2014-01-29 01:49:54 +04:00
session = new SSUSession (this, m_SenderEndpoint);
2014-01-25 01:30:07 +04:00
m_Sessions[m_SenderEndpoint] = session;
LogPrint ("New SSU session from ", m_SenderEndpoint.address ().to_string (), ":", m_SenderEndpoint.port (), " created");
}
2014-01-30 01:49:53 +04:00
session->ProcessNextMessage (m_ReceiveBuffer, bytes_transferred, m_SenderEndpoint);
2014-01-24 01:10:33 +04:00
Receive ();
}
else
LogPrint ("SSU receive error: ", ecode.message ());
}
2014-01-29 01:49:54 +04:00
2014-02-09 17:52:56 +04:00
SSUSession * SSUServer::GetSession (const i2p::data::RouterInfo * router)
2014-01-29 01:49:54 +04: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
{
// otherwise create new session
session = new SSUSession (this, remoteEndpoint, router);
m_Sessions[remoteEndpoint] = session;
LogPrint ("New SSU session to [", router->GetIdentHashAbbreviation (), "] ",
remoteEndpoint.address ().to_string (), ":", remoteEndpoint.port (), " created");
2014-01-30 01:49:53 +04:00
session->Connect ();
2014-01-29 01:49:54 +04:00
}
}
else
LogPrint ("Router ", router->GetIdentHashAbbreviation (), " doesn't have SSU address");
}
return session;
}
2014-02-09 06:06:40 +04: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-01-24 01:10:33 +04:00
}
}