#1251 - add ipv6 address preference for NTCP/2, NTCP2 code clean

This commit is contained in:
R4SAS 2019-05-20 16:04:21 +03:00
parent 7c7742a175
commit 7ab29950a4
3 changed files with 170 additions and 153 deletions

View file

@ -1,5 +1,5 @@
/* /*
* Copyright (c) 2013-2018, The PurpleI2P Project * Copyright (c) 2013-2019, The PurpleI2P Project
* *
* This file is part of Purple i2pd project and licensed under BSD3 * This file is part of Purple i2pd project and licensed under BSD3
* *
@ -23,18 +23,22 @@
#include "NetDb.hpp" #include "NetDb.hpp"
#include "NTCP2.h" #include "NTCP2.h"
#ifndef WIN32
#include <linux/in6.h>
#endif
namespace i2p namespace i2p
{ {
namespace transport namespace transport
{ {
NTCP2Establisher::NTCP2Establisher (): NTCP2Establisher::NTCP2Establisher ():
m_SessionRequestBuffer (nullptr), m_SessionCreatedBuffer (nullptr), m_SessionConfirmedBuffer (nullptr) m_SessionRequestBuffer (nullptr), m_SessionCreatedBuffer (nullptr), m_SessionConfirmedBuffer (nullptr)
{ {
} }
NTCP2Establisher::~NTCP2Establisher () NTCP2Establisher::~NTCP2Establisher ()
{ {
delete[] m_SessionRequestBuffer; delete[] m_SessionRequestBuffer;
delete[] m_SessionCreatedBuffer; delete[] m_SessionCreatedBuffer;
delete[] m_SessionConfirmedBuffer; delete[] m_SessionConfirmedBuffer;
} }
@ -43,13 +47,13 @@ namespace transport
{ {
// temp_key = HMAC-SHA256(ck, input_key_material) // temp_key = HMAC-SHA256(ck, input_key_material)
uint8_t tempKey[32]; unsigned int len; uint8_t tempKey[32]; unsigned int len;
HMAC(EVP_sha256(), m_CK, 32, inputKeyMaterial, 32, tempKey, &len); HMAC(EVP_sha256(), m_CK, 32, inputKeyMaterial, 32, tempKey, &len);
// ck = HMAC-SHA256(temp_key, byte(0x01)) // ck = HMAC-SHA256(temp_key, byte(0x01))
static uint8_t one[1] = { 1 }; static uint8_t one[1] = { 1 };
HMAC(EVP_sha256(), tempKey, 32, one, 1, m_CK, &len); HMAC(EVP_sha256(), tempKey, 32, one, 1, m_CK, &len);
// derived = HMAC-SHA256(temp_key, ck || byte(0x02)) // derived = HMAC-SHA256(temp_key, ck || byte(0x02))
m_CK[32] = 2; m_CK[32] = 2;
HMAC(EVP_sha256(), tempKey, 32, m_CK, 33, m_K, &len); HMAC(EVP_sha256(), tempKey, 32, m_CK, 33, m_K, &len);
} }
void NTCP2Establisher::MixHash (const uint8_t * buf, size_t len) void NTCP2Establisher::MixHash (const uint8_t * buf, size_t len)
@ -63,22 +67,22 @@ namespace transport
void NTCP2Establisher::KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub) void NTCP2Establisher::KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub)
{ {
static const uint8_t protocolNameHash[] = static const uint8_t protocolNameHash[] =
{ {
0x72, 0xe8, 0x42, 0xc5, 0x45, 0xe1, 0x80, 0x80, 0xd3, 0x9c, 0x44, 0x93, 0xbb, 0x91, 0xd7, 0xed, 0x72, 0xe8, 0x42, 0xc5, 0x45, 0xe1, 0x80, 0x80, 0xd3, 0x9c, 0x44, 0x93, 0xbb, 0x91, 0xd7, 0xed,
0xf2, 0x28, 0x98, 0x17, 0x71, 0x21, 0x8c, 0x1f, 0x62, 0x4e, 0x20, 0x6f, 0x28, 0xd3, 0x2f, 0x71 0xf2, 0x28, 0x98, 0x17, 0x71, 0x21, 0x8c, 0x1f, 0x62, 0x4e, 0x20, 0x6f, 0x28, 0xd3, 0x2f, 0x71
}; // SHA256 ("Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256") }; // SHA256 ("Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256")
static const uint8_t hh[32] = static const uint8_t hh[32] =
{ {
0x49, 0xff, 0x48, 0x3f, 0xc4, 0x04, 0xb9, 0xb2, 0x6b, 0x11, 0x94, 0x36, 0x72, 0xff, 0x05, 0xb5, 0x49, 0xff, 0x48, 0x3f, 0xc4, 0x04, 0xb9, 0xb2, 0x6b, 0x11, 0x94, 0x36, 0x72, 0xff, 0x05, 0xb5,
0x61, 0x27, 0x03, 0x31, 0xba, 0x89, 0xb8, 0xfc, 0x33, 0x15, 0x93, 0x87, 0x57, 0xdd, 0x3d, 0x1e 0x61, 0x27, 0x03, 0x31, 0xba, 0x89, 0xb8, 0xfc, 0x33, 0x15, 0x93, 0x87, 0x57, 0xdd, 0x3d, 0x1e
}; // SHA256 (protocolNameHash) }; // SHA256 (protocolNameHash)
memcpy (m_CK, protocolNameHash, 32); memcpy (m_CK, protocolNameHash, 32);
// h = SHA256(hh || rs) // h = SHA256(hh || rs)
SHA256_CTX ctx; SHA256_CTX ctx;
SHA256_Init (&ctx); SHA256_Init (&ctx);
SHA256_Update (&ctx, hh, 32); SHA256_Update (&ctx, hh, 32);
SHA256_Update (&ctx, rs, 32); SHA256_Update (&ctx, rs, 32);
SHA256_Final (m_H, &ctx); SHA256_Final (m_H, &ctx);
// h = SHA256(h || epub) // h = SHA256(h || epub)
MixHash (epub, 32); MixHash (epub, 32);
@ -92,25 +96,25 @@ namespace transport
{ {
KeyDerivationFunction1 (m_RemoteStaticKey, m_EphemeralKeys, m_RemoteStaticKey, GetPub ()); KeyDerivationFunction1 (m_RemoteStaticKey, m_EphemeralKeys, m_RemoteStaticKey, GetPub ());
} }
void NTCP2Establisher::KDF1Bob () void NTCP2Establisher::KDF1Bob ()
{ {
KeyDerivationFunction1 (GetRemotePub (), i2p::context.GetStaticKeys (), i2p::context.GetNTCP2StaticPublicKey (), GetRemotePub ()); KeyDerivationFunction1 (GetRemotePub (), i2p::context.GetStaticKeys (), i2p::context.GetNTCP2StaticPublicKey (), GetRemotePub ());
} }
void NTCP2Establisher::KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub) void NTCP2Establisher::KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub)
{ {
MixHash (sessionRequest + 32, 32); // encrypted payload MixHash (sessionRequest + 32, 32); // encrypted payload
int paddingLength = sessionRequestLen - 64; int paddingLength = sessionRequestLen - 64;
if (paddingLength > 0) if (paddingLength > 0)
MixHash (sessionRequest + 64, paddingLength); MixHash (sessionRequest + 64, paddingLength);
MixHash (epub, 32); MixHash (epub, 32);
// x25519 between remote pub and ephemaral priv // x25519 between remote pub and ephemaral priv
uint8_t inputKeyMaterial[32]; uint8_t inputKeyMaterial[32];
m_EphemeralKeys.Agree (GetRemotePub (), inputKeyMaterial); m_EphemeralKeys.Agree (GetRemotePub (), inputKeyMaterial);
MixKey (inputKeyMaterial); MixKey (inputKeyMaterial);
} }
@ -118,7 +122,7 @@ namespace transport
{ {
KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetRemotePub ()); KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetRemotePub ());
} }
void NTCP2Establisher::KDF2Bob () void NTCP2Establisher::KDF2Bob ()
{ {
KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetPub ()); KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetPub ());
@ -127,14 +131,14 @@ namespace transport
void NTCP2Establisher::KDF3Alice () void NTCP2Establisher::KDF3Alice ()
{ {
uint8_t inputKeyMaterial[32]; uint8_t inputKeyMaterial[32];
i2p::context.GetStaticKeys ().Agree (GetRemotePub (), inputKeyMaterial); i2p::context.GetStaticKeys ().Agree (GetRemotePub (), inputKeyMaterial);
MixKey (inputKeyMaterial); MixKey (inputKeyMaterial);
} }
void NTCP2Establisher::KDF3Bob () void NTCP2Establisher::KDF3Bob ()
{ {
uint8_t inputKeyMaterial[32]; uint8_t inputKeyMaterial[32];
m_EphemeralKeys.Agree (m_RemoteStaticKey, inputKeyMaterial); m_EphemeralKeys.Agree (m_RemoteStaticKey, inputKeyMaterial);
MixKey (inputKeyMaterial); MixKey (inputKeyMaterial);
} }
@ -155,29 +159,29 @@ namespace transport
encryption.SetKey (m_RemoteIdentHash); encryption.SetKey (m_RemoteIdentHash);
encryption.SetIV (m_IV); encryption.SetIV (m_IV);
encryption.Encrypt (GetPub (), 32, m_SessionRequestBuffer); // X encryption.Encrypt (GetPub (), 32, m_SessionRequestBuffer); // X
encryption.GetIV (m_IV); // save IV for SessionCreated encryption.GetIV (m_IV); // save IV for SessionCreated
// encryption key for next block // encryption key for next block
KDF1Alice (); KDF1Alice ();
// fill options // fill options
uint8_t options[32]; // actual options size is 16 bytes uint8_t options[32]; // actual options size is 16 bytes
memset (options, 0, 16); memset (options, 0, 16);
options[1] = 2; // ver options[1] = 2; // ver
htobe16buf (options + 2, paddingLength); // padLen htobe16buf (options + 2, paddingLength); // padLen
// m3p2Len // m3p2Len
auto bufLen = i2p::context.GetRouterInfo ().GetBufferLen (); auto bufLen = i2p::context.GetRouterInfo ().GetBufferLen ();
m3p2Len = bufLen + 4 + 16; // (RI header + RI + MAC for now) TODO: implement options m3p2Len = bufLen + 4 + 16; // (RI header + RI + MAC for now) TODO: implement options
htobe16buf (options + 4, m3p2Len); htobe16buf (options + 4, m3p2Len);
// fill m3p2 payload (RouterInfo block) // fill m3p2 payload (RouterInfo block)
m_SessionConfirmedBuffer = new uint8_t[m3p2Len + 48]; // m3p1 is 48 bytes m_SessionConfirmedBuffer = new uint8_t[m3p2Len + 48]; // m3p1 is 48 bytes
uint8_t * m3p2 = m_SessionConfirmedBuffer + 48; uint8_t * m3p2 = m_SessionConfirmedBuffer + 48;
m3p2[0] = eNTCP2BlkRouterInfo; // block m3p2[0] = eNTCP2BlkRouterInfo; // block
htobe16buf (m3p2 + 1, bufLen + 1); // flag + RI htobe16buf (m3p2 + 1, bufLen + 1); // flag + RI
m3p2[3] = 0; // flag m3p2[3] = 0; // flag
memcpy (m3p2 + 4, i2p::context.GetRouterInfo ().GetBuffer (), bufLen); // TODO: own RI should be protected by mutex memcpy (m3p2 + 4, i2p::context.GetRouterInfo ().GetBuffer (), bufLen); // TODO: own RI should be protected by mutex
// 2 bytes reserved // 2 bytes reserved
htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsA htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsA
// 4 bytes reserved // 4 bytes reserved
// sign and encrypt options, use m_H as AD // sign and encrypt options, use m_H as AD
uint8_t nonce[12]; uint8_t nonce[12];
memset (nonce, 0, 12); // set nonce to zero memset (nonce, 0, 12); // set nonce to zero
i2p::crypto::AEADChaCha20Poly1305 (options, 16, m_H, 32, m_K, nonce, m_SessionRequestBuffer + 32, 32, true); // encrypt i2p::crypto::AEADChaCha20Poly1305 (options, 16, m_H, 32, m_K, nonce, m_SessionRequestBuffer + 32, 32, true); // encrypt
@ -187,7 +191,7 @@ namespace transport
{ {
auto paddingLen = rand () % (287 - 64); auto paddingLen = rand () % (287 - 64);
m_SessionCreatedBufferLen = paddingLen + 64; m_SessionCreatedBufferLen = paddingLen + 64;
m_SessionCreatedBuffer = new uint8_t[m_SessionCreatedBufferLen]; m_SessionCreatedBuffer = new uint8_t[m_SessionCreatedBufferLen];
RAND_bytes (m_SessionCreatedBuffer + 64, paddingLen); RAND_bytes (m_SessionCreatedBuffer + 64, paddingLen);
// encrypt Y // encrypt Y
i2p::crypto::CBCEncryption encryption; i2p::crypto::CBCEncryption encryption;
@ -195,12 +199,12 @@ namespace transport
encryption.SetIV (m_IV); encryption.SetIV (m_IV);
encryption.Encrypt (GetPub (), 32, m_SessionCreatedBuffer); // Y encryption.Encrypt (GetPub (), 32, m_SessionCreatedBuffer); // Y
// encryption key for next block (m_K) // encryption key for next block (m_K)
KDF2Bob (); KDF2Bob ();
uint8_t options[16]; uint8_t options[16];
memset (options, 0, 16); memset (options, 0, 16);
htobe16buf (options + 2, paddingLen); // padLen htobe16buf (options + 2, paddingLen); // padLen
htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsB htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsB
// sign and encrypt options, use m_H as AD // sign and encrypt options, use m_H as AD
uint8_t nonce[12]; uint8_t nonce[12];
memset (nonce, 0, 12); // set nonce to zero memset (nonce, 0, 12); // set nonce to zero
i2p::crypto::AEADChaCha20Poly1305 (options, 16, m_H, 32, m_K, nonce, m_SessionCreatedBuffer + 32, 32, true); // encrypt i2p::crypto::AEADChaCha20Poly1305 (options, 16, m_H, 32, m_K, nonce, m_SessionCreatedBuffer + 32, 32, true); // encrypt
@ -213,9 +217,9 @@ namespace transport
MixHash (m_SessionCreatedBuffer + 32, 32); // encrypted payload MixHash (m_SessionCreatedBuffer + 32, 32); // encrypted payload
int paddingLength = m_SessionCreatedBufferLen - 64; int paddingLength = m_SessionCreatedBufferLen - 64;
if (paddingLength > 0) if (paddingLength > 0)
MixHash (m_SessionCreatedBuffer + 64, paddingLength); MixHash (m_SessionCreatedBuffer + 64, paddingLength);
// part1 48 bytes // part1 48 bytes
i2p::crypto::AEADChaCha20Poly1305 (i2p::context.GetNTCP2StaticPublicKey (), 32, m_H, 32, m_K, nonce, m_SessionConfirmedBuffer, 48, true); // encrypt i2p::crypto::AEADChaCha20Poly1305 (i2p::context.GetNTCP2StaticPublicKey (), 32, m_H, 32, m_K, nonce, m_SessionConfirmedBuffer, 48, true); // encrypt
} }
@ -223,14 +227,14 @@ namespace transport
{ {
// part 2 // part 2
// update AD again // update AD again
MixHash (m_SessionConfirmedBuffer, 48); MixHash (m_SessionConfirmedBuffer, 48);
// encrypt m3p2, it must be filled in SessionRequest // encrypt m3p2, it must be filled in SessionRequest
KDF3Alice (); KDF3Alice ();
uint8_t * m3p2 = m_SessionConfirmedBuffer + 48; uint8_t * m3p2 = m_SessionConfirmedBuffer + 48;
i2p::crypto::AEADChaCha20Poly1305 (m3p2, m3p2Len - 16, m_H, 32, m_K, nonce, m3p2, m3p2Len, true); // encrypt i2p::crypto::AEADChaCha20Poly1305 (m3p2, m3p2Len - 16, m_H, 32, m_K, nonce, m3p2, m3p2Len, true); // encrypt
// update h again // update h again
MixHash (m3p2, m3p2Len); //h = SHA256(h || ciphertext) MixHash (m3p2, m3p2Len); //h = SHA256(h || ciphertext)
} }
bool NTCP2Establisher::ProcessSessionRequestMessage (uint16_t& paddingLen) bool NTCP2Establisher::ProcessSessionRequestMessage (uint16_t& paddingLen)
{ {
@ -239,7 +243,7 @@ namespace transport
decryption.SetKey (i2p::context.GetIdentHash ()); decryption.SetKey (i2p::context.GetIdentHash ());
decryption.SetIV (i2p::context.GetNTCP2IV ()); decryption.SetIV (i2p::context.GetNTCP2IV ());
decryption.Decrypt (m_SessionRequestBuffer, 32, GetRemotePub ()); decryption.Decrypt (m_SessionRequestBuffer, 32, GetRemotePub ());
decryption.GetIV (m_IV); // save IV for SessionCreated decryption.GetIV (m_IV); // save IV for SessionCreated
// decryption key for next block // decryption key for next block
KDF1Bob (); KDF1Bob ();
// verify MAC and decrypt options block (32 bytes), use m_H as AD // verify MAC and decrypt options block (32 bytes), use m_H as AD
@ -248,7 +252,7 @@ namespace transport
if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionRequestBuffer + 32, 16, m_H, 32, m_K, nonce, options, 16, false)) // decrypt if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionRequestBuffer + 32, 16, m_H, 32, m_K, nonce, options, 16, false)) // decrypt
{ {
// options // options
if (options[1] == 2) // ver is always 2 if (options[1] == 2) // ver is always 2
{ {
paddingLen = bufbe16toh (options + 2); paddingLen = bufbe16toh (options + 2);
m_SessionRequestBufferLen = paddingLen + 64; m_SessionRequestBufferLen = paddingLen + 64;
@ -256,11 +260,11 @@ namespace transport
if (m3p2Len < 16) if (m3p2Len < 16)
{ {
LogPrint (eLogWarning, "NTCP2: SessionRequest m3p2len=", m3p2Len, " is too short"); LogPrint (eLogWarning, "NTCP2: SessionRequest m3p2len=", m3p2Len, " is too short");
return false; return false;
} }
// check timestamp // check timestamp
auto ts = i2p::util::GetSecondsSinceEpoch (); auto ts = i2p::util::GetSecondsSinceEpoch ();
uint32_t tsA = bufbe32toh (options + 8); uint32_t tsA = bufbe32toh (options + 8);
if (tsA < ts - NTCP2_CLOCK_SKEW || tsA > ts + NTCP2_CLOCK_SKEW) if (tsA < ts - NTCP2_CLOCK_SKEW || tsA > ts + NTCP2_CLOCK_SKEW)
{ {
LogPrint (eLogWarning, "NTCP2: SessionRequest time difference ", (int)(ts - tsA), " exceeds clock skew"); LogPrint (eLogWarning, "NTCP2: SessionRequest time difference ", (int)(ts - tsA), " exceeds clock skew");
@ -277,8 +281,8 @@ namespace transport
{ {
LogPrint (eLogWarning, "NTCP2: SessionRequest AEAD verification failed "); LogPrint (eLogWarning, "NTCP2: SessionRequest AEAD verification failed ");
return false; return false;
} }
return true; return true;
} }
bool NTCP2Establisher::ProcessSessionCreatedMessage (uint16_t& paddingLen) bool NTCP2Establisher::ProcessSessionCreatedMessage (uint16_t& paddingLen)
@ -297,11 +301,11 @@ namespace transport
memset (nonce, 0, 12); // set nonce to zero memset (nonce, 0, 12); // set nonce to zero
if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionCreatedBuffer + 32, 16, m_H, 32, m_K, nonce, payload, 16, false)) // decrypt if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionCreatedBuffer + 32, 16, m_H, 32, m_K, nonce, payload, 16, false)) // decrypt
{ {
// options // options
paddingLen = bufbe16toh(payload + 2); paddingLen = bufbe16toh(payload + 2);
// check timestamp // check timestamp
auto ts = i2p::util::GetSecondsSinceEpoch (); auto ts = i2p::util::GetSecondsSinceEpoch ();
uint32_t tsB = bufbe32toh (payload + 8); uint32_t tsB = bufbe32toh (payload + 8);
if (tsB < ts - NTCP2_CLOCK_SKEW || tsB > ts + NTCP2_CLOCK_SKEW) if (tsB < ts - NTCP2_CLOCK_SKEW || tsB > ts + NTCP2_CLOCK_SKEW)
{ {
LogPrint (eLogWarning, "NTCP2: SessionCreated time difference ", (int)(ts - tsB), " exceeds clock skew"); LogPrint (eLogWarning, "NTCP2: SessionCreated time difference ", (int)(ts - tsB), " exceeds clock skew");
@ -309,10 +313,10 @@ namespace transport
} }
} }
else else
{ {
LogPrint (eLogWarning, "NTCP2: SessionCreated AEAD verification failed "); LogPrint (eLogWarning, "NTCP2: SessionCreated AEAD verification failed ");
return false; return false;
} }
return true; return true;
} }
@ -323,7 +327,7 @@ namespace transport
int paddingLength = m_SessionCreatedBufferLen - 64; int paddingLength = m_SessionCreatedBufferLen - 64;
if (paddingLength > 0) if (paddingLength > 0)
MixHash (m_SessionCreatedBuffer + 64, paddingLength); MixHash (m_SessionCreatedBuffer + 64, paddingLength);
if (!i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer, 32, m_H, 32, m_K, nonce, m_RemoteStaticKey, 32, false)) // decrypt S if (!i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer, 32, m_H, 32, m_K, nonce, m_RemoteStaticKey, 32, false)) // decrypt S
{ {
LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part1 AEAD verification failed "); LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part1 AEAD verification failed ");
@ -335,9 +339,9 @@ namespace transport
bool NTCP2Establisher::ProcessSessionConfirmedMessagePart2 (const uint8_t * nonce, uint8_t * m3p2Buf) bool NTCP2Establisher::ProcessSessionConfirmedMessagePart2 (const uint8_t * nonce, uint8_t * m3p2Buf)
{ {
// update AD again // update AD again
MixHash (m_SessionConfirmedBuffer, 48); MixHash (m_SessionConfirmedBuffer, 48);
KDF3Bob (); KDF3Bob ();
if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer + 48, m3p2Len - 16, m_H, 32, m_K, nonce, m3p2Buf, m3p2Len - 16, false)) // decrypt if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer + 48, m3p2Len - 16, m_H, 32, m_K, nonce, m3p2Buf, m3p2Len - 16, false)) // decrypt
{ {
// caclulate new h again for KDF data // caclulate new h again for KDF data
@ -353,8 +357,8 @@ namespace transport
} }
NTCP2Session::NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter): NTCP2Session::NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter):
TransportSession (in_RemoteRouter, NTCP2_ESTABLISH_TIMEOUT), TransportSession (in_RemoteRouter, NTCP2_ESTABLISH_TIMEOUT),
m_Server (server), m_Socket (m_Server.GetService ()), m_Server (server), m_Socket (m_Server.GetService ()),
m_IsEstablished (false), m_IsTerminated (false), m_IsEstablished (false), m_IsTerminated (false),
m_Establisher (new NTCP2Establisher), m_Establisher (new NTCP2Establisher),
m_SendSipKey (nullptr), m_ReceiveSipKey (nullptr), m_SendSipKey (nullptr), m_ReceiveSipKey (nullptr),
@ -374,7 +378,7 @@ namespace transport
memcpy (m_Establisher->m_IV, addr->ntcp2->iv, 16); memcpy (m_Establisher->m_IV, addr->ntcp2->iv, 16);
} }
else else
LogPrint (eLogWarning, "NTCP2: Missing NTCP2 parameters"); LogPrint (eLogWarning, "NTCP2: Missing NTCP2 parameters");
} }
} }
@ -424,8 +428,8 @@ namespace transport
void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce) void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce)
{ {
memset (nonce, 0, 4); memset (nonce, 0, 4);
htole64buf (nonce + 4, seqn); htole64buf (nonce + 4, seqn);
} }
@ -443,11 +447,11 @@ namespace transport
memcpy (h, m_Establisher->GetH (), 32); memcpy (h, m_Establisher->GetH (), 32);
memcpy (h + 32, "siphash", 7); memcpy (h + 32, "siphash", 7);
HMAC(EVP_sha256(), master, 32, h, 39, tempKey, &len); // temp_key = HMAC-SHA256(ask_master, h || "siphash") HMAC(EVP_sha256(), master, 32, h, 39, tempKey, &len); // temp_key = HMAC-SHA256(ask_master, h || "siphash")
HMAC(EVP_sha256(), tempKey, 32, one, 1, master, &len); // sip_master = HMAC-SHA256(temp_key, byte(0x01)) HMAC(EVP_sha256(), tempKey, 32, one, 1, master, &len); // sip_master = HMAC-SHA256(temp_key, byte(0x01))
HMAC(EVP_sha256(), master, 32, nullptr, 0, tempKey, &len); // temp_key = HMAC-SHA256(sip_master, zerolen) HMAC(EVP_sha256(), master, 32, nullptr, 0, tempKey, &len); // temp_key = HMAC-SHA256(sip_master, zerolen)
HMAC(EVP_sha256(), tempKey, 32, one, 1, m_Sipkeysab, &len); // sipkeys_ab = HMAC-SHA256(temp_key, byte(0x01)). HMAC(EVP_sha256(), tempKey, 32, one, 1, m_Sipkeysab, &len); // sipkeys_ab = HMAC-SHA256(temp_key, byte(0x01)).
m_Sipkeysab[32] = 2; m_Sipkeysab[32] = 2;
HMAC(EVP_sha256(), tempKey, 32, m_Sipkeysab, 33, m_Sipkeysba, &len); // sipkeys_ba = HMAC-SHA256(temp_key, sipkeys_ab || byte(0x02)) HMAC(EVP_sha256(), tempKey, 32, m_Sipkeysab, 33, m_Sipkeysba, &len); // sipkeys_ba = HMAC-SHA256(temp_key, sipkeys_ab || byte(0x02))
} }
@ -456,8 +460,8 @@ namespace transport
m_Establisher->CreateSessionRequestMessage (); m_Establisher->CreateSessionRequestMessage ();
// send message // send message
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionRequestBuffer, m_Establisher->m_SessionRequestBufferLen), boost::asio::transfer_all (), boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionRequestBuffer, m_Establisher->m_SessionRequestBufferLen), boost::asio::transfer_all (),
std::bind(&NTCP2Session::HandleSessionRequestSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); std::bind(&NTCP2Session::HandleSessionRequestSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
} }
void NTCP2Session::HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred) void NTCP2Session::HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
{ {
@ -505,7 +509,7 @@ namespace transport
} }
else else
SendSessionCreated (); SendSessionCreated ();
} }
else else
Terminate (); Terminate ();
} }
@ -525,9 +529,9 @@ namespace transport
void NTCP2Session::SendSessionCreated () void NTCP2Session::SendSessionCreated ()
{ {
m_Establisher->CreateSessionCreatedMessage (); m_Establisher->CreateSessionCreatedMessage ();
// send message // send message
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionCreatedBuffer, m_Establisher->m_SessionCreatedBufferLen), boost::asio::transfer_all (), boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionCreatedBuffer, m_Establisher->m_SessionCreatedBufferLen), boost::asio::transfer_all (),
std::bind(&NTCP2Session::HandleSessionCreatedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); std::bind(&NTCP2Session::HandleSessionCreatedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
} }
void NTCP2Session::HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred) void NTCP2Session::HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
@ -582,9 +586,9 @@ namespace transport
{ {
uint8_t nonce[12]; uint8_t nonce[12];
CreateNonce (1, nonce); // set nonce to 1 CreateNonce (1, nonce); // set nonce to 1
m_Establisher->CreateSessionConfirmedMessagePart1 (nonce); m_Establisher->CreateSessionConfirmedMessagePart1 (nonce);
memset (nonce, 0, 12); // set nonce back to 0 memset (nonce, 0, 12); // set nonce back to 0
m_Establisher->CreateSessionConfirmedMessagePart2 (nonce); m_Establisher->CreateSessionConfirmedMessagePart2 (nonce);
// send message // send message
boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (), boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (),
std::bind(&NTCP2Session::HandleSessionConfirmedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); std::bind(&NTCP2Session::HandleSessionConfirmedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
@ -596,7 +600,7 @@ namespace transport
KeyDerivationFunctionDataPhase (); KeyDerivationFunctionDataPhase ();
// Alice data phase keys // Alice data phase keys
m_SendKey = m_Kab; m_SendKey = m_Kab;
m_ReceiveKey = m_Kba; m_ReceiveKey = m_Kba;
SetSipKeys (m_Sipkeysab, m_Sipkeysba); SetSipKeys (m_Sipkeysab, m_Sipkeysba);
memcpy (m_ReceiveIV.buf, m_Sipkeysba + 16, 8); memcpy (m_ReceiveIV.buf, m_Sipkeysba + 16, 8);
memcpy (m_SendIV.buf, m_Sipkeysab + 16, 8); memcpy (m_SendIV.buf, m_Sipkeysab + 16, 8);
@ -619,7 +623,7 @@ namespace transport
else else
{ {
LogPrint (eLogDebug, "NTCP2: SessionCreated sent"); LogPrint (eLogDebug, "NTCP2: SessionCreated sent");
m_Establisher->m_SessionConfirmedBuffer = new uint8_t[m_Establisher->m3p2Len + 48]; m_Establisher->m_SessionConfirmedBuffer = new uint8_t[m_Establisher->m3p2Len + 48];
boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (), boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (),
std::bind(&NTCP2Session::HandleSessionConfirmedReceived , shared_from_this (), std::placeholders::_1, std::placeholders::_2)); std::bind(&NTCP2Session::HandleSessionConfirmedReceived , shared_from_this (), std::placeholders::_1, std::placeholders::_2));
} }
@ -648,7 +652,7 @@ namespace transport
KeyDerivationFunctionDataPhase (); KeyDerivationFunctionDataPhase ();
// Bob data phase keys // Bob data phase keys
m_SendKey = m_Kba; m_SendKey = m_Kba;
m_ReceiveKey = m_Kab; m_ReceiveKey = m_Kab;
SetSipKeys (m_Sipkeysba, m_Sipkeysab); SetSipKeys (m_Sipkeysba, m_Sipkeysab);
memcpy (m_ReceiveIV.buf, m_Sipkeysab + 16, 8); memcpy (m_ReceiveIV.buf, m_Sipkeysab + 16, 8);
memcpy (m_SendIV.buf, m_Sipkeysba + 16, 8); memcpy (m_SendIV.buf, m_Sipkeysba + 16, 8);
@ -656,8 +660,8 @@ namespace transport
// process RI // process RI
if (buf[0] != eNTCP2BlkRouterInfo) if (buf[0] != eNTCP2BlkRouterInfo)
{ {
LogPrint (eLogWarning, "NTCP2: unexpected block ", (int)buf[0], " in SessionConfirmed"); LogPrint (eLogWarning, "NTCP2: unexpected block ", (int)buf[0], " in SessionConfirmed");
Terminate (); Terminate ();
return; return;
} }
auto size = bufbe16toh (buf.data () + 1); auto size = bufbe16toh (buf.data () + 1);
@ -671,33 +675,33 @@ namespace transport
i2p::data::RouterInfo ri (buf.data () + 4, size - 1); // 1 byte block type + 2 bytes size + 1 byte flag i2p::data::RouterInfo ri (buf.data () + 4, size - 1); // 1 byte block type + 2 bytes size + 1 byte flag
if (ri.IsUnreachable ()) if (ri.IsUnreachable ())
{ {
LogPrint (eLogError, "NTCP2: Signature verification failed in SessionConfirmed"); LogPrint (eLogError, "NTCP2: Signature verification failed in SessionConfirmed");
SendTerminationAndTerminate (eNTCP2RouterInfoSignatureVerificationFail); SendTerminationAndTerminate (eNTCP2RouterInfoSignatureVerificationFail);
return; return;
} }
if (i2p::util::GetMillisecondsSinceEpoch () > ri.GetTimestamp () + i2p::data::NETDB_MIN_EXPIRATION_TIMEOUT*1000LL) // 90 minutes if (i2p::util::GetMillisecondsSinceEpoch () > ri.GetTimestamp () + i2p::data::NETDB_MIN_EXPIRATION_TIMEOUT*1000LL) // 90 minutes
{ {
LogPrint (eLogError, "NTCP2: RouterInfo is too old in SessionConfirmed"); LogPrint (eLogError, "NTCP2: RouterInfo is too old in SessionConfirmed");
SendTerminationAndTerminate (eNTCP2Message3Error); SendTerminationAndTerminate (eNTCP2Message3Error);
return; return;
} }
auto addr = ri.GetNTCP2Address (false); // any NTCP2 address auto addr = ri.GetNTCP2Address (false); // any NTCP2 address
if (!addr) if (!addr)
{ {
LogPrint (eLogError, "NTCP2: No NTCP2 address found in SessionConfirmed"); LogPrint (eLogError, "NTCP2: No NTCP2 address found in SessionConfirmed");
Terminate (); Terminate ();
return; return;
} }
if (memcmp (addr->ntcp2->staticKey, m_Establisher->m_RemoteStaticKey, 32)) if (memcmp (addr->ntcp2->staticKey, m_Establisher->m_RemoteStaticKey, 32))
{ {
LogPrint (eLogError, "NTCP2: Static key mismatch in SessionConfirmed"); LogPrint (eLogError, "NTCP2: Static key mismatch in SessionConfirmed");
SendTerminationAndTerminate (eNTCP2IncorrectSParameter); SendTerminationAndTerminate (eNTCP2IncorrectSParameter);
return; return;
} }
i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, buf.data () + 3, size)); // TODO: should insert ri and not parse it twice i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, buf.data () + 3, size)); // TODO: should insert ri and not parse it twice
// TODO: process options // TODO: process options
// ready to communicate // ready to communicate
auto existing = i2p::data::netdb.FindRouter (ri.GetRouterIdentity ()->GetIdentHash ()); // check if exists already auto existing = i2p::data::netdb.FindRouter (ri.GetRouterIdentity ()->GetIdentHash ()); // check if exists already
SetRemoteIdentity (existing ? existing->GetRouterIdentity () : ri.GetRouterIdentity ()); SetRemoteIdentity (existing ? existing->GetRouterIdentity () : ri.GetRouterIdentity ());
m_Server.AddNTCP2Session (shared_from_this ()); m_Server.AddNTCP2Session (shared_from_this ());
@ -716,13 +720,13 @@ namespace transport
{ {
#if OPENSSL_SIPHASH #if OPENSSL_SIPHASH
m_SendSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, sendSipKey, 16); m_SendSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, sendSipKey, 16);
m_SendMDCtx = EVP_MD_CTX_create (); m_SendMDCtx = EVP_MD_CTX_create ();
EVP_PKEY_CTX *ctx = nullptr; EVP_PKEY_CTX *ctx = nullptr;
EVP_DigestSignInit (m_SendMDCtx, &ctx, nullptr, nullptr, m_SendSipKey); EVP_DigestSignInit (m_SendMDCtx, &ctx, nullptr, nullptr, m_SendSipKey);
EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr); EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr);
m_ReceiveSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, receiveSipKey, 16); m_ReceiveSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, receiveSipKey, 16);
m_ReceiveMDCtx = EVP_MD_CTX_create (); m_ReceiveMDCtx = EVP_MD_CTX_create ();
ctx = nullptr; ctx = nullptr;
EVP_DigestSignInit (m_ReceiveMDCtx, &ctx, NULL, NULL, m_ReceiveSipKey); EVP_DigestSignInit (m_ReceiveMDCtx, &ctx, NULL, NULL, m_ReceiveSipKey);
EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr); EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr);
@ -766,9 +770,9 @@ namespace transport
{ {
#if OPENSSL_SIPHASH #if OPENSSL_SIPHASH
EVP_DigestSignInit (m_ReceiveMDCtx, nullptr, nullptr, nullptr, nullptr); EVP_DigestSignInit (m_ReceiveMDCtx, nullptr, nullptr, nullptr, nullptr);
EVP_DigestSignUpdate (m_ReceiveMDCtx, m_ReceiveIV.buf, 8); EVP_DigestSignUpdate (m_ReceiveMDCtx, m_ReceiveIV.buf, 8);
size_t l = 8; size_t l = 8;
EVP_DigestSignFinal (m_ReceiveMDCtx, m_ReceiveIV.buf, &l); EVP_DigestSignFinal (m_ReceiveMDCtx, m_ReceiveIV.buf, &l);
#else #else
i2p::crypto::Siphash<8> (m_ReceiveIV.buf, m_ReceiveIV.buf, 8, m_ReceiveSipKey); i2p::crypto::Siphash<8> (m_ReceiveIV.buf, m_ReceiveIV.buf, 8, m_ReceiveSipKey);
#endif #endif
@ -776,7 +780,7 @@ namespace transport
m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key); m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key);
LogPrint (eLogDebug, "NTCP2: received length ", m_NextReceivedLen); LogPrint (eLogDebug, "NTCP2: received length ", m_NextReceivedLen);
if (m_NextReceivedLen >= 16) if (m_NextReceivedLen >= 16)
{ {
if (m_NextReceivedBuffer) delete[] m_NextReceivedBuffer; if (m_NextReceivedBuffer) delete[] m_NextReceivedBuffer;
m_NextReceivedBuffer = new uint8_t[m_NextReceivedLen]; m_NextReceivedBuffer = new uint8_t[m_NextReceivedLen];
boost::system::error_code ec; boost::system::error_code ec;
@ -794,7 +798,7 @@ namespace transport
{ {
LogPrint (eLogError, "NTCP2: received length ", m_NextReceivedLen, " is too short"); LogPrint (eLogError, "NTCP2: received length ", m_NextReceivedLen, " is too short");
Terminate (); Terminate ();
} }
} }
} }
@ -821,7 +825,7 @@ namespace transport
uint8_t nonce[12]; uint8_t nonce[12];
CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++; CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++;
if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false)) if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false))
{ {
LogPrint (eLogDebug, "NTCP2: received message decrypted"); LogPrint (eLogDebug, "NTCP2: received message decrypted");
ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16); ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16);
delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = nullptr; // we don't need received buffer anymore delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = nullptr; // we don't need received buffer anymore
@ -831,7 +835,7 @@ namespace transport
{ {
LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed "); LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed ");
SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure); SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure);
} }
} }
} }
@ -854,7 +858,7 @@ namespace transport
{ {
case eNTCP2BlkDateTime: case eNTCP2BlkDateTime:
LogPrint (eLogDebug, "NTCP2: datetime"); LogPrint (eLogDebug, "NTCP2: datetime");
break; break;
case eNTCP2BlkOptions: case eNTCP2BlkOptions:
LogPrint (eLogDebug, "NTCP2: options"); LogPrint (eLogDebug, "NTCP2: options");
break; break;
@ -877,11 +881,11 @@ namespace transport
nextMsg->len = nextMsg->offset + size + 7; // 7 more bytes for full I2NP header nextMsg->len = nextMsg->offset + size + 7; // 7 more bytes for full I2NP header
memcpy (nextMsg->GetNTCP2Header (), frame + offset, size); memcpy (nextMsg->GetNTCP2Header (), frame + offset, size);
nextMsg->FromNTCP2 (); nextMsg->FromNTCP2 ();
m_Handler.PutNextMessage (nextMsg); m_Handler.PutNextMessage (nextMsg);
break; break;
} }
case eNTCP2BlkTermination: case eNTCP2BlkTermination:
if (size >= 9) if (size >= 9)
{ {
LogPrint (eLogDebug, "NTCP2: termination. reason=", (int)(frame[offset + 8])); LogPrint (eLogDebug, "NTCP2: termination. reason=", (int)(frame[offset + 8]));
Terminate (); Terminate ();
@ -904,46 +908,46 @@ namespace transport
{ {
#if OPENSSL_SIPHASH #if OPENSSL_SIPHASH
EVP_DigestSignInit (m_SendMDCtx, nullptr, nullptr, nullptr, nullptr); EVP_DigestSignInit (m_SendMDCtx, nullptr, nullptr, nullptr, nullptr);
EVP_DigestSignUpdate (m_SendMDCtx, m_SendIV.buf, 8); EVP_DigestSignUpdate (m_SendMDCtx, m_SendIV.buf, 8);
size_t l = 8; size_t l = 8;
EVP_DigestSignFinal (m_SendMDCtx, m_SendIV.buf, &l); EVP_DigestSignFinal (m_SendMDCtx, m_SendIV.buf, &l);
#else #else
i2p::crypto::Siphash<8> (m_SendIV.buf, m_SendIV.buf, 8, m_SendSipKey); i2p::crypto::Siphash<8> (m_SendIV.buf, m_SendIV.buf, 8, m_SendSipKey);
#endif #endif
// length must be in BigEndian // length must be in BigEndian
htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key)); htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key));
LogPrint (eLogDebug, "NTCP2: sent length ", frameLen); LogPrint (eLogDebug, "NTCP2: sent length ", frameLen);
} }
void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs) void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs)
{ {
if (msgs.empty () || IsTerminated ()) return; if (msgs.empty () || IsTerminated ()) return;
size_t totalLen = 0; size_t totalLen = 0;
std::vector<std::pair<uint8_t *, size_t> > encryptBufs; std::vector<std::pair<uint8_t *, size_t> > encryptBufs;
std::vector<boost::asio::const_buffer> bufs; std::vector<boost::asio::const_buffer> bufs;
std::shared_ptr<I2NPMessage> first; std::shared_ptr<I2NPMessage> first;
uint8_t * macBuf = nullptr; uint8_t * macBuf = nullptr;
for (auto& it: msgs) for (auto& it: msgs)
{ {
it->ToNTCP2 (); it->ToNTCP2 ();
auto buf = it->GetNTCP2Header (); auto buf = it->GetNTCP2Header ();
auto len = it->GetNTCP2Length (); auto len = it->GetNTCP2Length ();
// block header // block header
buf -= 3; buf -= 3;
buf[0] = eNTCP2BlkI2NPMessage; // blk buf[0] = eNTCP2BlkI2NPMessage; // blk
htobe16buf (buf + 1, len); // size htobe16buf (buf + 1, len); // size
len += 3; len += 3;
totalLen += len; totalLen += len;
encryptBufs.push_back ( {buf, len} ); encryptBufs.push_back ( {buf, len} );
if (&it == &msgs.front ()) // first message if (&it == &msgs.front ()) // first message
{ {
// allocate two bytes for length // allocate two bytes for length
buf -= 2; len += 2; buf -= 2; len += 2;
first = it; first = it;
} }
if (&it == &msgs.back () && it->len + 16 < it->maxLen) // last message if (&it == &msgs.back () && it->len + 16 < it->maxLen) // last message
{ {
// if it's long enough we add padding and MAC to it // if it's long enough we add padding and MAC to it
// create padding block // create padding block
auto paddingLen = CreatePaddingBlock (totalLen, buf + len, it->maxLen - it->len - 16); auto paddingLen = CreatePaddingBlock (totalLen, buf + len, it->maxLen - it->len - 16);
@ -956,8 +960,8 @@ namespace transport
macBuf = buf + len; macBuf = buf + len;
// allocate 16 bytes for MAC // allocate 16 bytes for MAC
len += 16; len += 16;
} }
bufs.push_back (boost::asio::buffer (buf, len)); bufs.push_back (boost::asio::buffer (buf, len));
} }
@ -969,42 +973,42 @@ namespace transport
auto paddingLen = CreatePaddingBlock (totalLen, m_NextSendBuffer, 287 - 16); auto paddingLen = CreatePaddingBlock (totalLen, m_NextSendBuffer, 287 - 16);
// and padding block to encrypt and send // and padding block to encrypt and send
if (paddingLen) if (paddingLen)
encryptBufs.push_back ( {m_NextSendBuffer, paddingLen} ); encryptBufs.push_back ( {m_NextSendBuffer, paddingLen} );
bufs.push_back (boost::asio::buffer (m_NextSendBuffer, paddingLen + 16)); bufs.push_back (boost::asio::buffer (m_NextSendBuffer, paddingLen + 16));
macBuf = m_NextSendBuffer + paddingLen; macBuf = m_NextSendBuffer + paddingLen;
totalLen += paddingLen; totalLen += paddingLen;
} }
uint8_t nonce[12]; uint8_t nonce[12];
CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++; CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
i2p::crypto::AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers i2p::crypto::AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers
SetNextSentFrameLength (totalLen + 16, first->GetNTCP2Header () - 5); // frame length right before first block SetNextSentFrameLength (totalLen + 16, first->GetNTCP2Header () - 5); // frame length right before first block
// send buffers // send buffers
m_IsSending = true; m_IsSending = true;
boost::asio::async_write (m_Socket, bufs, boost::asio::transfer_all (), boost::asio::async_write (m_Socket, bufs, boost::asio::transfer_all (),
std::bind(&NTCP2Session::HandleI2NPMsgsSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msgs)); std::bind(&NTCP2Session::HandleI2NPMsgsSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msgs));
} }
void NTCP2Session::HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs) void NTCP2Session::HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs)
{ {
HandleNextFrameSent (ecode, bytes_transferred); HandleNextFrameSent (ecode, bytes_transferred);
// msgs get destroyed here // msgs get destroyed here
} }
void NTCP2Session::EncryptAndSendNextBuffer (size_t payloadLen) void NTCP2Session::EncryptAndSendNextBuffer (size_t payloadLen)
{ {
if (IsTerminated ()) if (IsTerminated ())
{ {
delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr; delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;
return; return;
} }
// encrypt // encrypt
uint8_t nonce[12]; uint8_t nonce[12];
CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++; CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
i2p::crypto::AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2); i2p::crypto::AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2);
SetNextSentFrameLength (payloadLen + 16, m_NextSendBuffer); SetNextSentFrameLength (payloadLen + 16, m_NextSendBuffer);
// send // send
m_IsSending = true; m_IsSending = true;
boost::asio::async_write (m_Socket, boost::asio::buffer (m_NextSendBuffer, payloadLen + 16 + 2), boost::asio::transfer_all (), boost::asio::async_write (m_Socket, boost::asio::buffer (m_NextSendBuffer, payloadLen + 16 + 2), boost::asio::transfer_all (),
std::bind(&NTCP2Session::HandleNextFrameSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2)); std::bind(&NTCP2Session::HandleNextFrameSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
} }
@ -1013,21 +1017,21 @@ namespace transport
{ {
m_IsSending = false; m_IsSending = false;
delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr; delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;
if (ecode) if (ecode)
{ {
LogPrint (eLogWarning, "NTCP2: Couldn't send frame ", ecode.message ()); LogPrint (eLogWarning, "NTCP2: Couldn't send frame ", ecode.message ());
} }
else else
{ {
m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch (); m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
m_NumSentBytes += bytes_transferred; m_NumSentBytes += bytes_transferred;
i2p::transport::transports.UpdateSentBytes (bytes_transferred); i2p::transport::transports.UpdateSentBytes (bytes_transferred);
LogPrint (eLogDebug, "NTCP2: Next frame sent ", bytes_transferred); LogPrint (eLogDebug, "NTCP2: Next frame sent ", bytes_transferred);
SendQueue (); SendQueue ();
} }
} }
void NTCP2Session::SendQueue () void NTCP2Session::SendQueue ()
{ {
if (!m_SendQueue.empty ()) if (!m_SendQueue.empty ())
@ -1037,7 +1041,7 @@ namespace transport
while (!m_SendQueue.empty ()) while (!m_SendQueue.empty ())
{ {
auto msg = m_SendQueue.front (); auto msg = m_SendQueue.front ();
size_t len = msg->GetNTCP2Length (); size_t len = msg->GetNTCP2Length ();
if (s + len + 3 <= NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) // 3 bytes block header if (s + len + 3 <= NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) // 3 bytes block header
{ {
msgs.push_back (msg); msgs.push_back (msg);
@ -1053,12 +1057,12 @@ namespace transport
break; break;
} }
SendI2NPMsgs (msgs); SendI2NPMsgs (msgs);
} }
} }
size_t NTCP2Session::CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len) size_t NTCP2Session::CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len)
{ {
if (len < 3) return 0; if (len < 3) return 0;
len -= 3; len -= 3;
if (msgLen < 256) msgLen = 256; // for short message padding should not be always zero if (msgLen < 256) msgLen = 256; // for short message padding should not be always zero
size_t paddingSize = (msgLen*NTCP2_MAX_PADDING_RATIO)/100; size_t paddingSize = (msgLen*NTCP2_MAX_PADDING_RATIO)/100;
@ -1067,10 +1071,10 @@ namespace transport
if (paddingSize) paddingSize = rand () % paddingSize; if (paddingSize) paddingSize = rand () % paddingSize;
buf[0] = eNTCP2BlkPadding; // blk buf[0] = eNTCP2BlkPadding; // blk
htobe16buf (buf + 1, paddingSize); // size htobe16buf (buf + 1, paddingSize); // size
memset (buf + 3, 0, paddingSize); memset (buf + 3, 0, paddingSize);
return paddingSize + 3; return paddingSize + 3;
} }
void NTCP2Session::SendRouterInfo () void NTCP2Session::SendRouterInfo ()
{ {
if (!IsEstablished ()) return; if (!IsEstablished ()) return;
@ -1091,11 +1095,11 @@ namespace transport
void NTCP2Session::SendTermination (NTCP2TerminationReason reason) void NTCP2Session::SendTermination (NTCP2TerminationReason reason)
{ {
if (!m_SendKey || !m_SendSipKey) return; if (!m_SendKey || !m_SendSipKey) return;
m_NextSendBuffer = new uint8_t[49]; // 49 = 12 bytes message + 16 bytes MAC + 2 bytes size + up to 19 padding block m_NextSendBuffer = new uint8_t[49]; // 49 = 12 bytes message + 16 bytes MAC + 2 bytes size + up to 19 padding block
// termination block // termination block
m_NextSendBuffer[2] = eNTCP2BlkTermination; m_NextSendBuffer[2] = eNTCP2BlkTermination;
m_NextSendBuffer[3] = 0; m_NextSendBuffer[4] = 9; // 9 bytes block size m_NextSendBuffer[3] = 0; m_NextSendBuffer[4] = 9; // 9 bytes block size
htobe64buf (m_NextSendBuffer + 5, m_ReceiveSequenceNumber); htobe64buf (m_NextSendBuffer + 5, m_ReceiveSequenceNumber);
m_NextSendBuffer[13] = (uint8_t)reason; m_NextSendBuffer[13] = (uint8_t)reason;
// padding block // padding block
auto paddingSize = CreatePaddingBlock (12, m_NextSendBuffer + 14, 19); auto paddingSize = CreatePaddingBlock (12, m_NextSendBuffer + 14, 19);
@ -1119,13 +1123,13 @@ namespace transport
if (m_IsTerminated) return; if (m_IsTerminated) return;
for (auto it: msgs) for (auto it: msgs)
m_SendQueue.push_back (it); m_SendQueue.push_back (it);
if (!m_IsSending) if (!m_IsSending)
SendQueue (); SendQueue ();
else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE) else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE)
{ {
LogPrint (eLogWarning, "NTCP2: outgoing messages queue size exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE); LogPrint (eLogWarning, "NTCP2: outgoing messages queue size exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE);
Terminate (); Terminate ();
} }
} }
void NTCP2Session::SendLocalRouterInfo () void NTCP2Session::SendLocalRouterInfo ()
@ -1157,13 +1161,13 @@ namespace transport
if (!address) continue; if (!address) continue;
if (address->IsPublishedNTCP2 ()) if (address->IsPublishedNTCP2 ())
{ {
if (address->host.is_v4()) if (address->host.is_v4() && context.SupportsV4 ())
{ {
try try
{ {
m_NTCP2Acceptor.reset (new boost::asio::ip::tcp::acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), address->port))); m_NTCP2Acceptor.reset (new boost::asio::ip::tcp::acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), address->port)));
} }
catch ( std::exception & ex ) catch ( std::exception & ex )
{ {
LogPrint(eLogError, "NTCP2: Failed to bind to v4 port ",address->port, ex.what()); LogPrint(eLogError, "NTCP2: Failed to bind to v4 port ",address->port, ex.what());
continue; continue;
@ -1175,12 +1179,17 @@ namespace transport
} }
else if (address->host.is_v6() && context.SupportsV6 ()) else if (address->host.is_v6() && context.SupportsV6 ())
{ {
m_NTCP2V6Acceptor.reset (new boost::asio::ip::tcp::acceptor (m_Service));
try try
{ {
m_NTCP2V6Acceptor->open (boost::asio::ip::tcp::v6()); m_NTCP2V6Acceptor.reset (new boost::asio::ip::tcp::acceptor (m_Service));
m_NTCP2V6Acceptor->open (boost::asio::ip::tcp::v6 ());
m_NTCP2V6Acceptor->set_option (boost::asio::ip::v6_only (true)); m_NTCP2V6Acceptor->set_option (boost::asio::ip::v6_only (true));
m_NTCP2V6Acceptor->set_option (boost::asio::socket_base::reuse_address (true)); m_NTCP2V6Acceptor->set_option (boost::asio::socket_base::reuse_address (true));
#ifndef WIN32
// Set preference to use public IPv6 address -- works only on linux
typedef boost::asio::detail::socket_option::boolean<IPV6_ADDR_PREFERENCES, IPV6_PREFER_SRC_PUBLIC> ipv6PreferPubAddr;
m_NTCP2V6Acceptor->set_option (ipv6PreferPubAddr (true));
#endif
m_NTCP2V6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port)); m_NTCP2V6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port));
m_NTCP2V6Acceptor->listen (); m_NTCP2V6Acceptor->listen ();
@ -1271,7 +1280,7 @@ namespace transport
void NTCP2Server::Connect(const boost::asio::ip::address & address, uint16_t port, std::shared_ptr<NTCP2Session> conn) void NTCP2Server::Connect(const boost::asio::ip::address & address, uint16_t port, std::shared_ptr<NTCP2Session> conn)
{ {
LogPrint (eLogDebug, "NTCP2: Connecting to ", address ,":", port); LogPrint (eLogDebug, "NTCP2: Connecting to ", address ,":", port);
m_Service.post([this, address, port, conn]() m_Service.post([this, address, port, conn]()
{ {
if (this->AddNTCP2Session (conn)) if (this->AddNTCP2Session (conn))
{ {
@ -1279,7 +1288,7 @@ namespace transport
auto timeout = NTCP2_CONNECT_TIMEOUT * 5; auto timeout = NTCP2_CONNECT_TIMEOUT * 5;
conn->SetTerminationTimeout(timeout * 2); conn->SetTerminationTimeout(timeout * 2);
timer->expires_from_now (boost::posix_time::seconds(timeout)); timer->expires_from_now (boost::posix_time::seconds(timeout));
timer->async_wait ([conn, timeout](const boost::system::error_code& ecode) timer->async_wait ([conn, timeout](const boost::system::error_code& ecode)
{ {
if (ecode != boost::asio::error::operation_aborted) if (ecode != boost::asio::error::operation_aborted)
{ {
@ -1403,4 +1412,3 @@ namespace transport
} }
} }
} }

View file

@ -19,6 +19,10 @@
#include "Event.h" #include "Event.h"
#endif #endif
#ifndef WIN32
#include <linux/in6.h>
#endif
using namespace i2p::crypto; using namespace i2p::crypto;
namespace i2p namespace i2p
@ -850,9 +854,14 @@ namespace transport
try try
{ {
m_NTCPV6Acceptor = new boost::asio::ip::tcp::acceptor (m_Service); m_NTCPV6Acceptor = new boost::asio::ip::tcp::acceptor (m_Service);
m_NTCPV6Acceptor->open (boost::asio::ip::tcp::v6()); m_NTCPV6Acceptor->open (boost::asio::ip::tcp::v6 ());
m_NTCPV6Acceptor->set_option (boost::asio::ip::v6_only (true)); m_NTCPV6Acceptor->set_option (boost::asio::ip::v6_only (true));
m_NTCPV6Acceptor->set_option (boost::asio::socket_base::reuse_address (true)); m_NTCPV6Acceptor->set_option (boost::asio::socket_base::reuse_address (true));
#ifndef WIN32
// Set preference to use public IPv6 address -- works only on linux
typedef boost::asio::detail::socket_option::boolean<IPV6_ADDR_PREFERENCES, IPV6_PREFER_SRC_PUBLIC> ipv6PreferPubAddr;
m_NTCPV6Acceptor->set_option (ipv6PreferPubAddr (true));
#endif
m_NTCPV6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port)); m_NTCPV6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port));
m_NTCPV6Acceptor->listen (); m_NTCPV6Acceptor->listen ();

View file

@ -50,14 +50,14 @@ namespace transport
void SSUServer::OpenSocketV6 () void SSUServer::OpenSocketV6 ()
{ {
try { try {
m_SocketV6.open (boost::asio::ip::udp::v6()); m_SocketV6.open (boost::asio::ip::udp::v6 ());
m_SocketV6.set_option (boost::asio::ip::v6_only (true)); m_SocketV6.set_option (boost::asio::ip::v6_only (true));
m_SocketV6.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE)); m_SocketV6.set_option (boost::asio::socket_base::receive_buffer_size (SSU_SOCKET_RECEIVE_BUFFER_SIZE));
m_SocketV6.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE)); m_SocketV6.set_option (boost::asio::socket_base::send_buffer_size (SSU_SOCKET_SEND_BUFFER_SIZE));
#ifndef WIN32 #ifndef WIN32
// Set preference to use public IPv6 address -- works only on linux // Set preference to use public IPv6 address -- works only on linux
typedef boost::asio::detail::socket_option::boolean<IPV6_ADDR_PREFERENCES, IPV6_PREFER_SRC_PUBLIC> ipv6PreferPubAddr; typedef boost::asio::detail::socket_option::boolean<IPV6_ADDR_PREFERENCES, IPV6_PREFER_SRC_PUBLIC> ipv6PreferPubAddr;
m_SocketV6.set_option (ipv6PreferPubAddr(true)); m_SocketV6.set_option (ipv6PreferPubAddr (true));
#endif #endif
m_SocketV6.bind (m_EndpointV6); m_SocketV6.bind (m_EndpointV6);
LogPrint (eLogInfo, "SSU: Start listening v6 port ", m_EndpointV6.port()); LogPrint (eLogInfo, "SSU: Start listening v6 port ", m_EndpointV6.port());