i2pd/libi2pd/ECIESX25519AEADRatchetSession.cpp

1169 lines
40 KiB
C++
Raw Normal View History

/*
* Copyright (c) 2013-2020, The PurpleI2P Project
*
* This file is part of Purple i2pd project and licensed under BSD3
*
* See full license text in LICENSE file at top of project tree
*/
2020-01-15 20:13:43 +00:00
#include <string.h>
#include <openssl/sha.h>
#include "Log.h"
2020-12-27 16:18:53 +00:00
#include "util.h"
2020-01-15 20:13:43 +00:00
#include "Crypto.h"
#include "Elligator.h"
#include "Tag.h"
#include "I2PEndian.h"
2020-01-23 19:26:40 +00:00
#include "Timestamp.h"
2020-03-08 22:13:41 +00:00
#include "Tunnel.h"
#include "TunnelPool.h"
#include "Transports.h"
2020-01-15 20:13:43 +00:00
#include "ECIESX25519AEADRatchetSession.h"
namespace i2p
{
namespace garlic
{
void RatchetTagSet::DHInitialize (const uint8_t * rootKey, const uint8_t * k)
{
// DH_INITIALIZE(rootKey, k)
uint8_t keydata[64];
i2p::crypto::HKDF (rootKey, k, 32, "KDFDHRatchetStep", keydata); // keydata = HKDF(rootKey, k, "KDFDHRatchetStep", 64)
memcpy (m_NextRootKey, keydata, 32); // nextRootKey = keydata[0:31]
i2p::crypto::HKDF (keydata + 32, nullptr, 0, "TagAndKeyGenKeys", m_KeyData.buf);
// [sessTag_ck, symmKey_ck] = HKDF(keydata[32:63], ZEROLEN, "TagAndKeyGenKeys", 64)
2020-02-09 02:51:02 +00:00
memcpy (m_SymmKeyCK, m_KeyData.buf + 32, 32);
m_NextSymmKeyIndex = 0;
}
2020-01-20 20:17:38 +00:00
void RatchetTagSet::NextSessionTagRatchet ()
{
i2p::crypto::HKDF (m_KeyData.GetSessTagCK (), nullptr, 0, "STInitialization", m_KeyData.buf); // [sessTag_ck, sesstag_constant] = HKDF(sessTag_ck, ZEROLEN, "STInitialization", 64)
memcpy (m_SessTagConstant, m_KeyData.GetSessTagConstant (), 32);
2020-02-05 20:48:51 +00:00
m_NextIndex = 0;
}
2020-01-20 20:17:38 +00:00
uint64_t RatchetTagSet::GetNextSessionTag ()
{
m_NextIndex++;
if (m_NextIndex >= 65535)
2020-04-26 23:27:31 +00:00
{
LogPrint (eLogError, "Garlic: Tagset ", GetTagSetID (), " is empty");
return 0;
}
2020-12-26 22:18:29 +00:00
i2p::crypto::HKDF (m_KeyData.GetSessTagCK (), m_SessTagConstant, 32, "SessionTagKeyGen", m_KeyData.buf); // [sessTag_ck, tag] = HKDF(sessTag_chainkey, SESSTAG_CONSTANT, "SessionTagKeyGen", 64)
return m_KeyData.GetTag ();
}
2020-01-20 20:17:38 +00:00
2020-03-07 23:46:40 +00:00
void RatchetTagSet::GetSymmKey (int index, uint8_t * key)
2020-02-09 02:51:02 +00:00
{
2020-04-17 01:30:18 +00:00
if (index >= m_NextSymmKeyIndex)
{
2020-03-07 23:46:40 +00:00
auto num = index + 1 - m_NextSymmKeyIndex;
2020-04-17 01:30:18 +00:00
if (!m_NextSymmKeyIndex)
{
i2p::crypto::HKDF (m_SymmKeyCK, nullptr, 0, "SymmetricRatchet", m_CurrentSymmKeyCK); // keydata_0 = HKDF(symmKey_ck, SYMMKEY_CONSTANT, "SymmetricRatchet", 64)
m_NextSymmKeyIndex = 1;
num--;
}
2020-03-07 23:46:40 +00:00
for (int i = 0; i < num; i++)
{
2020-03-07 23:46:40 +00:00
i2p::crypto::HKDF (m_CurrentSymmKeyCK, nullptr, 0, "SymmetricRatchet", m_CurrentSymmKeyCK);
2020-04-17 01:30:18 +00:00
if (i < num - 1)
m_ItermediateSymmKeys.emplace (m_NextSymmKeyIndex + i, m_CurrentSymmKeyCK + 32);
}
2020-03-07 23:46:40 +00:00
m_NextSymmKeyIndex += num;
memcpy (key, m_CurrentSymmKeyCK + 32, 32);
2020-02-09 02:51:02 +00:00
}
else
2020-04-17 01:30:18 +00:00
{
auto it = m_ItermediateSymmKeys.find (index);
if (it != m_ItermediateSymmKeys.end ())
{
2020-04-17 01:30:18 +00:00
memcpy (key, it->second, 32);
m_ItermediateSymmKeys.erase (it);
}
2020-04-17 01:30:18 +00:00
else
LogPrint (eLogError, "Garlic: Missing symmetric key for index ", index);
}
}
2020-05-01 01:27:35 +00:00
2020-09-08 11:46:55 +00:00
void RatchetTagSet::DeleteSymmKey (int index)
{
m_ItermediateSymmKeys.erase (index);
}
void ReceiveRatchetTagSet::Expire ()
2020-05-01 01:27:35 +00:00
{
if (!m_ExpirationTimestamp)
m_ExpirationTimestamp = i2p::util::GetSecondsSinceEpoch () + ECIESX25519_PREVIOUS_TAGSET_EXPIRATION_TIMEOUT;
}
bool ReceiveRatchetTagSet::IsExpired (uint64_t ts) const
{
return m_ExpirationTimestamp && ts > m_ExpirationTimestamp;
}
bool ReceiveRatchetTagSet::IsIndexExpired (int index) const
{
2021-01-07 19:51:23 +00:00
return index < m_TrimBehindIndex;
}
2021-01-04 23:20:16 +00:00
bool ReceiveRatchetTagSet::HandleNextMessage (uint8_t * buf, size_t len, int index)
2020-09-15 23:39:18 +00:00
{
auto session = GetSession ();
if (!session) return false;
return session->HandleNextMessage (buf, len, shared_from_this (), index);
}
DatabaseLookupTagSet::DatabaseLookupTagSet (GarlicDestination * destination, const uint8_t * key):
2021-01-04 23:20:16 +00:00
ReceiveRatchetTagSet (nullptr), m_Destination (destination)
2020-09-15 23:39:18 +00:00
{
memcpy (m_Key, key, 32);
Expire ();
}
bool DatabaseLookupTagSet::HandleNextMessage (uint8_t * buf, size_t len, int index)
{
if (len < 24) return false;
uint8_t nonce[12];
memset (nonce, 0, 12); // n = 0
size_t offset = 8; // first 8 bytes is reply tag used as AD
len -= 16; // poly1305
if (!i2p::crypto::AEADChaCha20Poly1305 (buf + offset, len - offset, buf, 8, m_Key, nonce, buf + offset, len - offset, false)) // decrypt
{
LogPrint (eLogWarning, "Garlic: Lookup reply AEAD decryption failed");
return false;
}
// we assume 1 I2NP block with delivery type local
if (offset + 3 > len)
{
LogPrint (eLogWarning, "Garlic: Lookup reply is too short ", len);
return false;
}
if (buf[offset] != eECIESx25519BlkGalicClove)
{
LogPrint (eLogWarning, "Garlic: Lookup reply unexpected block ", (int)buf[offset]);
return false;
}
offset++;
auto size = bufbe16toh (buf + offset);
offset += 2;
if (offset + size > len)
{
LogPrint (eLogWarning, "Garlic: Lookup reply block is too long ", size);
return false;
}
if (m_Destination)
m_Destination->HandleECIESx25519GarlicClove (buf + offset, size);
return true;
}
ECIESX25519AEADRatchetSession::ECIESX25519AEADRatchetSession (GarlicDestination * owner, bool attachLeaseSet):
GarlicRoutingSession (owner, attachLeaseSet)
{
2020-06-14 01:24:16 +00:00
RAND_bytes (m_PaddingSizes, 32); m_NextPaddingSize = 0;
}
ECIESX25519AEADRatchetSession::~ECIESX25519AEADRatchetSession ()
{
}
2020-01-15 20:13:43 +00:00
2020-02-05 20:48:51 +00:00
void ECIESX25519AEADRatchetSession::CreateNonce (uint64_t seqn, uint8_t * nonce)
{
memset (nonce, 0, 4);
htole64buf (nonce + 4, seqn);
}
bool ECIESX25519AEADRatchetSession::GenerateEphemeralKeysAndEncode (uint8_t * buf)
{
bool ineligible = false;
while (!ineligible)
{
m_EphemeralKeys = i2p::transport::transports.GetNextX25519KeysPair ();
ineligible = m_EphemeralKeys->IsElligatorIneligible ();
if (!ineligible) // we haven't tried it yet
{
if (i2p::crypto::GetElligator ()->Encode (m_EphemeralKeys->GetPublicKey (), buf))
return true; // success
// otherwise return back
m_EphemeralKeys->SetElligatorIneligible ();
i2p::transport::transports.ReuseX25519KeysPair (m_EphemeralKeys);
}
else
i2p::transport::transports.ReuseX25519KeysPair (m_EphemeralKeys);
}
// we still didn't find elligator eligible pair
for (int i = 0; i < 10; i++)
{
// create new
m_EphemeralKeys = std::make_shared<i2p::crypto::X25519Keys>();
m_EphemeralKeys->GenerateKeys ();
if (i2p::crypto::GetElligator ()->Encode (m_EphemeralKeys->GetPublicKey (), buf))
return true; // success
else
{
// let NTCP2 use it
m_EphemeralKeys->SetElligatorIneligible ();
i2p::transport::transports.ReuseX25519KeysPair (m_EphemeralKeys);
}
}
LogPrint (eLogError, "Garlic: Can't generate elligator eligible x25519 keys");
return false;
2020-02-05 20:48:51 +00:00
}
void ECIESX25519AEADRatchetSession::InitNewSessionTagset (std::shared_ptr<RatchetTagSet> tagsetNsr) const
{
uint8_t tagsetKey[32];
i2p::crypto::HKDF (m_CK, nullptr, 0, "SessionReplyTags", tagsetKey, 32); // tagsetKey = HKDF(chainKey, ZEROLEN, "SessionReplyTags", 32)
// Session Tag Ratchet
tagsetNsr->DHInitialize (m_CK, tagsetKey); // tagset_nsr = DH_INITIALIZE(chainKey, tagsetKey)
tagsetNsr->NextSessionTagRatchet ();
}
bool ECIESX25519AEADRatchetSession::HandleNewIncomingSession (const uint8_t * buf, size_t len)
{
if (!GetOwner ()) return false;
// we are Bob
// KDF1
i2p::crypto::InitNoiseIKState (GetNoiseState (), GetOwner ()->GetEncryptionPublicKey (i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)); // bpk
2020-01-30 02:57:10 +00:00
if (!i2p::crypto::GetElligator ()->Decode (buf, m_Aepk))
{
2020-01-15 20:13:43 +00:00
LogPrint (eLogError, "Garlic: Can't decode elligator");
return false;
2020-01-15 20:13:43 +00:00
}
buf += 32; len -= 32;
MixHash (m_Aepk, 32); // h = SHA256(h || aepk)
uint8_t sharedSecret[32];
2021-01-01 20:03:11 +00:00
if (!GetOwner ()->Decrypt (m_Aepk, sharedSecret, nullptr, i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)) // x25519(bsk, aepk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Alice ephemeral key");
return false;
}
2020-11-05 20:27:37 +00:00
MixKey (sharedSecret);
// decrypt flags/static
2020-01-15 20:13:43 +00:00
uint8_t nonce[12], fs[32];
2020-02-05 20:48:51 +00:00
CreateNonce (0, nonce);
if (!i2p::crypto::AEADChaCha20Poly1305 (buf, 32, m_H, 32, m_CK + 32, nonce, fs, 32, false)) // decrypt
2020-01-15 20:13:43 +00:00
{
LogPrint (eLogWarning, "Garlic: Flags/static section AEAD verification failed ");
return false;
}
MixHash (buf, 48); // h = SHA256(h || ciphertext)
buf += 48; len -= 48; // 32 data + 16 poly
// KDF2 for payload
bool isStatic = !i2p::data::Tag<32> (fs).IsZero ();
2020-01-15 20:13:43 +00:00
if (isStatic)
{
// static key, fs is apk
memcpy (m_RemoteStaticKey, fs, 32);
2021-01-01 20:03:11 +00:00
if (!GetOwner ()->Decrypt (fs, sharedSecret, nullptr, i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)) // x25519(bsk, apk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Alice static key");
return false;
}
2020-11-05 20:27:37 +00:00
MixKey (sharedSecret);
2020-01-15 20:13:43 +00:00
}
else // all zeros flags
2020-02-05 20:48:51 +00:00
CreateNonce (1, nonce);
// decrypt payload
std::vector<uint8_t> payload (len - 16); // we must save original ciphertext
if (!i2p::crypto::AEADChaCha20Poly1305 (buf, len - 16, m_H, 32, m_CK + 32, nonce, payload.data (), len - 16, false)) // decrypt
2020-01-15 20:13:43 +00:00
{
LogPrint (eLogWarning, "Garlic: Payload section AEAD verification failed");
return false;
}
2020-11-05 20:27:37 +00:00
m_State = eSessionStateNewSessionReceived;
2020-11-05 20:27:37 +00:00
if (isStatic)
{
MixHash (buf, len); // h = SHA256(h || ciphertext)
GetOwner ()->AddECIESx25519Session (m_RemoteStaticKey, shared_from_this ());
}
HandlePayload (payload.data (), len - 16, nullptr, 0);
2020-01-15 20:13:43 +00:00
return true;
}
2020-01-15 20:13:43 +00:00
2021-01-04 23:20:16 +00:00
void ECIESX25519AEADRatchetSession::HandlePayload (const uint8_t * buf, size_t len, const std::shared_ptr<ReceiveRatchetTagSet>& receiveTagset, int index)
{
size_t offset = 0;
2020-01-15 20:13:43 +00:00
while (offset < len)
{
uint8_t blk = buf[offset];
offset++;
auto size = bufbe16toh (buf + offset);
offset += 2;
LogPrint (eLogDebug, "Garlic: Block type ", (int)blk, " of size ", size);
if (size > len)
{
LogPrint (eLogError, "Garlic: Unexpected block length ", size);
break;
}
switch (blk)
{
case eECIESx25519BlkGalicClove:
2020-05-05 17:01:23 +00:00
if (GetOwner ())
GetOwner ()->HandleECIESx25519GarlicClove (buf + offset, size);
2020-01-15 20:13:43 +00:00
break;
2020-04-25 01:36:08 +00:00
case eECIESx25519BlkNextKey:
LogPrint (eLogDebug, "Garlic: next key");
if (receiveTagset)
HandleNextKey (buf + offset, size, receiveTagset);
else
LogPrint (eLogError, "Garlic: Unexpected next key block");
2020-04-25 01:36:08 +00:00
break;
case eECIESx25519BlkAck:
{
LogPrint (eLogDebug, "Garlic: ack");
int numAcks = size >> 2; // /4
auto offset1 = offset;
for (auto i = 0; i < numAcks; i++)
{
offset1 += 2; // tagsetid
MessageConfirmed (bufbe16toh (buf + offset1)); offset1 += 2; // N
}
break;
}
2020-03-26 23:03:38 +00:00
case eECIESx25519BlkAckRequest:
{
2020-03-26 23:03:38 +00:00
LogPrint (eLogDebug, "Garlic: ack request");
m_AckRequests.push_back ({receiveTagset->GetTagSetID (), index});
break;
}
2020-05-05 17:01:23 +00:00
case eECIESx25519BlkTermination:
LogPrint (eLogDebug, "Garlic: termination");
if (GetOwner ())
GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey);
if (receiveTagset) receiveTagset->Expire ();
break;
2020-05-05 17:01:23 +00:00
case eECIESx25519BlkDateTime:
LogPrint (eLogDebug, "Garlic: datetime");
break;
2020-05-05 17:01:23 +00:00
case eECIESx25519BlkOptions:
LogPrint (eLogDebug, "Garlic: options");
break;
case eECIESx25519BlkPadding:
LogPrint (eLogDebug, "Garlic: padding");
break;
2020-01-15 20:13:43 +00:00
default:
LogPrint (eLogWarning, "Garlic: Unknown block type ", (int)blk);
}
offset += size;
}
}
2021-01-04 23:20:16 +00:00
void ECIESX25519AEADRatchetSession::HandleNextKey (const uint8_t * buf, size_t len, const std::shared_ptr<ReceiveRatchetTagSet>& receiveTagset)
2020-04-25 01:36:08 +00:00
{
uint8_t flag = buf[0]; buf++; // flag
if (flag & ECIESX25519_NEXT_KEY_REVERSE_KEY_FLAG)
{
2020-04-27 13:35:02 +00:00
if (!m_SendForwardKey || !m_NextSendRatchet) return;
2020-04-26 23:27:31 +00:00
uint16_t keyID = bufbe16toh (buf); buf += 2; // keyID
if (((!m_NextSendRatchet->newKey || !m_NextSendRatchet->keyID) && keyID == m_NextSendRatchet->keyID) ||
(m_NextSendRatchet->newKey && keyID == m_NextSendRatchet->keyID -1))
2020-04-26 23:27:31 +00:00
{
2020-04-27 13:35:02 +00:00
if (flag & ECIESX25519_NEXT_KEY_KEY_PRESENT_FLAG)
2020-04-26 23:27:31 +00:00
memcpy (m_NextSendRatchet->remote, buf, 32);
uint8_t sharedSecret[32], tagsetKey[32];
m_NextSendRatchet->key->Agree (m_NextSendRatchet->remote, sharedSecret);
2020-04-26 23:27:31 +00:00
i2p::crypto::HKDF (sharedSecret, nullptr, 0, "XDHRatchetTagSet", tagsetKey, 32); // tagsetKey = HKDF(sharedSecret, ZEROLEN, "XDHRatchetTagSet", 32)
2021-01-04 23:20:16 +00:00
auto newTagset = std::make_shared<RatchetTagSet> ();
2020-04-26 23:27:31 +00:00
newTagset->SetTagSetID (1 + m_NextSendRatchet->keyID + keyID);
newTagset->DHInitialize (m_SendTagset->GetNextRootKey (), tagsetKey);
2020-04-26 23:27:31 +00:00
newTagset->NextSessionTagRatchet ();
m_SendTagset = newTagset;
2020-04-26 23:27:31 +00:00
m_SendForwardKey = false;
LogPrint (eLogDebug, "Garlic: next send tagset ", newTagset->GetTagSetID (), " created");
}
else
LogPrint (eLogDebug, "Garlic: Unexpected next key ", keyID);
}
2020-04-25 01:36:08 +00:00
else
{
uint16_t keyID = bufbe16toh (buf); buf += 2; // keyID
bool newKey = flag & ECIESX25519_NEXT_KEY_REQUEST_REVERSE_KEY_FLAG;
m_SendReverseKey = true;
if (!m_NextReceiveRatchet)
m_NextReceiveRatchet.reset (new DHRatchet ());
else
{
if (keyID == m_NextReceiveRatchet->keyID && newKey == m_NextReceiveRatchet->newKey)
2020-04-25 18:45:53 +00:00
{
LogPrint (eLogDebug, "Garlic: Duplicate ", newKey ? "new" : "old", " key ", keyID, " received");
return;
}
m_NextReceiveRatchet->keyID = keyID;
2020-04-25 01:36:08 +00:00
}
int tagsetID = 2*keyID;
if (newKey)
{
m_NextReceiveRatchet->key = i2p::transport::transports.GetNextX25519KeysPair ();
m_NextReceiveRatchet->newKey = true;
tagsetID++;
}
2020-04-25 01:36:08 +00:00
else
m_NextReceiveRatchet->newKey = false;
if (flag & ECIESX25519_NEXT_KEY_KEY_PRESENT_FLAG)
memcpy (m_NextReceiveRatchet->remote, buf, 32);
uint8_t sharedSecret[32], tagsetKey[32];
m_NextReceiveRatchet->key->Agree (m_NextReceiveRatchet->remote, sharedSecret);
i2p::crypto::HKDF (sharedSecret, nullptr, 0, "XDHRatchetTagSet", tagsetKey, 32); // tagsetKey = HKDF(sharedSecret, ZEROLEN, "XDHRatchetTagSet", 32)
2021-01-04 23:20:16 +00:00
auto newTagset = std::make_shared<ReceiveRatchetTagSet>(shared_from_this ());
newTagset->SetTagSetID (tagsetID);
newTagset->DHInitialize (receiveTagset->GetNextRootKey (), tagsetKey);
newTagset->NextSessionTagRatchet ();
2020-06-13 00:42:54 +00:00
GenerateMoreReceiveTags (newTagset, (GetOwner () && GetOwner ()->GetNumRatchetInboundTags () > 0) ?
GetOwner ()->GetNumRatchetInboundTags () : ECIESX25519_MAX_NUM_GENERATED_TAGS);
2020-05-01 01:27:35 +00:00
receiveTagset->Expire ();
LogPrint (eLogDebug, "Garlic: next receive tagset ", tagsetID, " created");
}
}
2020-04-26 23:27:31 +00:00
void ECIESX25519AEADRatchetSession::NewNextSendRatchet ()
{
if (m_NextSendRatchet)
{
2020-04-27 13:35:02 +00:00
if (!m_NextSendRatchet->newKey || !m_NextSendRatchet->keyID)
2020-04-26 23:27:31 +00:00
{
2020-04-27 13:35:02 +00:00
m_NextSendRatchet->keyID++;
m_NextSendRatchet->newKey = true;
}
2020-04-26 23:27:31 +00:00
else
2020-04-27 13:35:02 +00:00
m_NextSendRatchet->newKey = false;
}
2020-04-27 13:35:02 +00:00
else
m_NextSendRatchet.reset (new DHRatchet ());
if (m_NextSendRatchet->newKey)
2020-06-30 19:05:17 +00:00
m_NextSendRatchet->key = i2p::transport::transports.GetNextX25519KeysPair ();
2020-04-26 23:27:31 +00:00
m_SendForwardKey = true;
2020-04-27 13:35:02 +00:00
LogPrint (eLogDebug, "Garlic: new send ratchet ", m_NextSendRatchet->newKey ? "new" : "old", " key ", m_NextSendRatchet->keyID, " created");
}
bool ECIESX25519AEADRatchetSession::NewOutgoingSessionMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen, bool isStatic)
{
// we are Alice, bpk is m_RemoteStaticKey
size_t offset = 0;
if (!GenerateEphemeralKeysAndEncode (out + offset))
{
LogPrint (eLogError, "Garlic: Can't encode elligator");
return false;
}
offset += 32;
// KDF1
i2p::crypto::InitNoiseIKState (GetNoiseState (), m_RemoteStaticKey); // bpk
MixHash (m_EphemeralKeys->GetPublicKey (), 32); // h = SHA256(h || aepk)
uint8_t sharedSecret[32];
2021-01-01 20:03:11 +00:00
if (!m_EphemeralKeys->Agree (m_RemoteStaticKey, sharedSecret)) // x25519(aesk, bpk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Bob static key");
return false;
}
2020-11-05 20:27:37 +00:00
MixKey (sharedSecret);
// encrypt flags/static key section
uint8_t nonce[12];
2020-02-05 20:48:51 +00:00
CreateNonce (0, nonce);
const uint8_t * fs;
if (isStatic)
fs = GetOwner ()->GetEncryptionPublicKey (i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD);
else
{
memset (out + offset, 0, 32); // all zeros flags section
fs = out + offset;
}
if (!i2p::crypto::AEADChaCha20Poly1305 (fs, 32, m_H, 32, m_CK + 32, nonce, out + offset, 48, true)) // encrypt
{
LogPrint (eLogWarning, "Garlic: Flags/static section AEAD encryption failed ");
return false;
}
MixHash (out + offset, 48); // h = SHA256(h || ciphertext)
offset += 48;
// KDF2
if (isStatic)
{
GetOwner ()->Decrypt (m_RemoteStaticKey, sharedSecret, nullptr, i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD); // x25519 (ask, bpk)
MixKey (sharedSecret);
}
else
CreateNonce (1, nonce);
// encrypt payload
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len, m_H, 32, m_CK + 32, nonce, out + offset, len + 16, true)) // encrypt
{
LogPrint (eLogWarning, "Garlic: Payload section AEAD encryption failed");
return false;
}
m_State = eSessionStateNewSessionSent;
if (isStatic)
{
MixHash (out + offset, len + 16); // h = SHA256(h || ciphertext)
if (GetOwner ())
{
auto tagsetNsr = std::make_shared<ReceiveRatchetTagSet>(shared_from_this (), true);
InitNewSessionTagset (tagsetNsr);
GenerateMoreReceiveTags (tagsetNsr, ECIESX25519_NSR_NUM_GENERATED_TAGS);
}
}
return true;
}
2020-12-04 00:43:43 +00:00
bool ECIESX25519AEADRatchetSession::NewOutgoingMessageForRouter (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen)
{
// we are Alice, router's bpk is m_RemoteStaticKey
i2p::crypto::InitNoiseNState (GetNoiseState (), m_RemoteStaticKey);
2020-12-04 00:43:43 +00:00
size_t offset = 0;
m_EphemeralKeys = i2p::transport::transports.GetNextX25519KeysPair ();
memcpy (out + offset, m_EphemeralKeys->GetPublicKey (), 32);
MixHash (out + offset, 32); // h = SHA256(h || aepk)
offset += 32;
uint8_t sharedSecret[32];
2021-01-01 20:03:11 +00:00
if (!m_EphemeralKeys->Agree (m_RemoteStaticKey, sharedSecret)) // x25519(aesk, bpk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Bob static key");
return false;
}
2020-12-04 00:43:43 +00:00
MixKey (sharedSecret);
uint8_t nonce[12];
CreateNonce (0, nonce);
2020-12-04 00:43:43 +00:00
// encrypt payload
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len, m_H, 32, m_CK + 32, nonce, out + offset, len + 16, true)) // encrypt
{
LogPrint (eLogWarning, "Garlic: Payload for router AEAD encryption failed");
return false;
}
m_State = eSessionStateNewSessionSent;
return true;
}
bool ECIESX25519AEADRatchetSession::NewSessionReplyMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen)
{
// we are Bob
m_NSRSendTagset = std::make_shared<RatchetTagSet>();
InitNewSessionTagset (m_NSRSendTagset);
2020-06-04 22:19:38 +00:00
uint64_t tag = m_NSRSendTagset->GetNextSessionTag ();
size_t offset = 0;
memcpy (out + offset, &tag, 8);
offset += 8;
if (!GenerateEphemeralKeysAndEncode (out + offset)) // bepk
{
2020-01-17 19:11:15 +00:00
LogPrint (eLogError, "Garlic: Can't encode elligator");
return false;
}
2020-04-28 22:23:13 +00:00
memcpy (m_NSREncodedKey, out + offset, 56); // for possible next NSR
memcpy (m_NSRH, m_H, 32);
offset += 32;
// KDF for Reply Key Section
MixHash ((const uint8_t *)&tag, 8); // h = SHA256(h || tag)
MixHash (m_EphemeralKeys->GetPublicKey (), 32); // h = SHA256(h || bepk)
uint8_t sharedSecret[32];
2021-01-01 20:03:11 +00:00
if (!m_EphemeralKeys->Agree (m_Aepk, sharedSecret)) // sharedSecret = x25519(besk, aepk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Alice ephemeral key");
return false;
}
2020-11-05 20:27:37 +00:00
MixKey (sharedSecret);
2021-01-01 20:03:11 +00:00
if (!m_EphemeralKeys->Agree (m_RemoteStaticKey, sharedSecret)) // sharedSecret = x25519(besk, apk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Alice static key");
return false;
}
2020-11-05 20:27:37 +00:00
MixKey (sharedSecret);
2020-01-31 00:30:30 +00:00
uint8_t nonce[12];
2020-02-05 20:48:51 +00:00
CreateNonce (0, nonce);
// calculate hash for zero length
2020-04-28 22:23:13 +00:00
if (!i2p::crypto::AEADChaCha20Poly1305 (nonce /* can be anything */, 0, m_H, 32, m_CK + 32, nonce, out + offset, 16, true)) // encrypt, ciphertext = ENCRYPT(k, n, ZEROLEN, ad)
2020-01-17 19:11:15 +00:00
{
LogPrint (eLogWarning, "Garlic: Reply key section AEAD encryption failed");
return false;
}
MixHash (out + offset, 16); // h = SHA256(h || ciphertext)
offset += 16;
// KDF for payload
uint8_t keydata[64];
i2p::crypto::HKDF (m_CK, nullptr, 0, "", keydata); // keydata = HKDF(chainKey, ZEROLEN, "", 64)
2020-02-09 02:51:02 +00:00
// k_ab = keydata[0:31], k_ba = keydata[32:63]
2021-01-04 23:20:16 +00:00
auto receiveTagset = std::make_shared<ReceiveRatchetTagSet>(shared_from_this());
receiveTagset->DHInitialize (m_CK, keydata); // tagset_ab = DH_INITIALIZE(chainKey, k_ab)
2020-04-25 01:36:08 +00:00
receiveTagset->NextSessionTagRatchet ();
2021-01-04 23:20:16 +00:00
m_SendTagset = std::make_shared<RatchetTagSet>();
m_SendTagset->DHInitialize (m_CK, keydata + 32); // tagset_ba = DH_INITIALIZE(chainKey, k_ba)
m_SendTagset->NextSessionTagRatchet ();
2020-06-13 00:42:54 +00:00
GenerateMoreReceiveTags (receiveTagset, (GetOwner () && GetOwner ()->GetNumRatchetInboundTags () > 0) ?
GetOwner ()->GetNumRatchetInboundTags () : ECIESX25519_MIN_NUM_GENERATED_TAGS);
i2p::crypto::HKDF (keydata + 32, nullptr, 0, "AttachPayloadKDF", m_NSRKey, 32); // k = HKDF(k_ba, ZEROLEN, "AttachPayloadKDF", 32)
// encrypt payload
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len, m_H, 32, m_NSRKey, nonce, out + offset, len + 16, true)) // encrypt
2020-01-17 19:11:15 +00:00
{
LogPrint (eLogWarning, "Garlic: NSR payload section AEAD encryption failed");
2020-01-17 19:11:15 +00:00
return false;
}
m_State = eSessionStateNewSessionReplySent;
m_SessionCreatedTimestamp = i2p::util::GetSecondsSinceEpoch ();
return true;
}
2020-12-04 00:43:43 +00:00
bool ECIESX25519AEADRatchetSession::NextNewSessionReplyMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen)
{
// we are Bob and sent NSR already
2020-06-04 22:19:38 +00:00
uint64_t tag = m_NSRSendTagset->GetNextSessionTag (); // next tag
memcpy (out, &tag, 8);
2020-04-28 22:23:13 +00:00
memcpy (out + 8, m_NSREncodedKey, 32);
// recalculate h with new tag
2020-04-28 22:23:13 +00:00
memcpy (m_H, m_NSRH, 32);
MixHash ((const uint8_t *)&tag, 8); // h = SHA256(h || tag)
MixHash (m_EphemeralKeys->GetPublicKey (), 32); // h = SHA256(h || bepk)
uint8_t nonce[12];
CreateNonce (0, nonce);
2020-04-28 22:23:13 +00:00
if (!i2p::crypto::AEADChaCha20Poly1305 (nonce /* can be anything */, 0, m_H, 32, m_CK + 32, nonce, out + 40, 16, true)) // encrypt, ciphertext = ENCRYPT(k, n, ZEROLEN, ad)
{
LogPrint (eLogWarning, "Garlic: Reply key section AEAD encryption failed");
return false;
}
MixHash (out + 40, 16); // h = SHA256(h || ciphertext)
// encrypt payload
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len, m_H, 32, m_NSRKey, nonce, out + 56, len + 16, true)) // encrypt
{
LogPrint (eLogWarning, "Garlic: Next NSR payload section AEAD encryption failed");
return false;
}
return true;
}
bool ECIESX25519AEADRatchetSession::HandleNewOutgoingSessionReply (uint8_t * buf, size_t len)
{
2020-01-29 17:54:26 +00:00
// we are Alice
2020-01-23 02:42:30 +00:00
LogPrint (eLogDebug, "Garlic: reply received");
2020-01-29 17:54:26 +00:00
const uint8_t * tag = buf;
buf += 8; len -= 8; // tag
uint8_t bepk[32]; // Bob's ephemeral key
2020-01-29 17:54:26 +00:00
if (!i2p::crypto::GetElligator ()->Decode (buf, bepk))
{
2020-01-29 17:54:26 +00:00
LogPrint (eLogError, "Garlic: Can't decode elligator");
return false;
}
2020-01-29 17:54:26 +00:00
buf += 32; len -= 32;
// KDF for Reply Key Section
i2p::util::SaveStateHelper<i2p::crypto::NoiseSymmetricState> s(GetNoiseState ()); // restore noise state on exit
MixHash (tag, 8); // h = SHA256(h || tag)
MixHash (bepk, 32); // h = SHA256(h || bepk)
uint8_t sharedSecret[32];
2021-01-01 20:03:11 +00:00
if (!m_EphemeralKeys->Agree (bepk, sharedSecret)) // sharedSecret = x25519(aesk, bepk)
{
LogPrint (eLogWarning, "Garlic: Incorrect Bob ephemeral key");
return false;
}
2020-12-27 16:18:53 +00:00
MixKey (sharedSecret);
GetOwner ()->Decrypt (bepk, sharedSecret, nullptr, i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD); // x25519 (ask, bepk)
MixKey (sharedSecret);
2020-01-31 00:30:30 +00:00
uint8_t nonce[12];
2020-02-05 20:48:51 +00:00
CreateNonce (0, nonce);
// calculate hash for zero length
if (!i2p::crypto::AEADChaCha20Poly1305 (buf, 0, m_H, 32, m_CK + 32, nonce, sharedSecret/* can be anything */, 0, false)) // decrypt, DECRYPT(k, n, ZEROLEN, ad) verification only
2020-01-29 17:54:26 +00:00
{
LogPrint (eLogWarning, "Garlic: Reply key section AEAD decryption failed");
return false;
}
MixHash (buf, 16); // h = SHA256(h || ciphertext)
2020-01-29 17:54:26 +00:00
buf += 16; len -= 16;
// KDF for payload
uint8_t keydata[64];
i2p::crypto::HKDF (m_CK, nullptr, 0, "", keydata); // keydata = HKDF(chainKey, ZEROLEN, "", 64)
2020-04-29 02:03:13 +00:00
if (m_State == eSessionStateNewSessionSent)
{
2020-12-27 16:18:53 +00:00
// only first time, then we keep using existing tagsets
// k_ab = keydata[0:31], k_ba = keydata[32:63]
2021-01-04 23:20:16 +00:00
m_SendTagset = std::make_shared<RatchetTagSet>();
m_SendTagset->DHInitialize (m_CK, keydata); // tagset_ab = DH_INITIALIZE(chainKey, k_ab)
2020-04-29 02:03:13 +00:00
m_SendTagset->NextSessionTagRatchet ();
2021-01-04 23:20:16 +00:00
auto receiveTagset = std::make_shared<ReceiveRatchetTagSet>(shared_from_this ());
receiveTagset->DHInitialize (m_CK, keydata + 32); // tagset_ba = DH_INITIALIZE(chainKey, k_ba)
2020-04-29 02:03:13 +00:00
receiveTagset->NextSessionTagRatchet ();
2020-06-13 00:42:54 +00:00
GenerateMoreReceiveTags (receiveTagset, (GetOwner () && GetOwner ()->GetNumRatchetInboundTags () > 0) ?
GetOwner ()->GetNumRatchetInboundTags () : ECIESX25519_MIN_NUM_GENERATED_TAGS);
}
i2p::crypto::HKDF (keydata + 32, nullptr, 0, "AttachPayloadKDF", keydata, 32); // k = HKDF(k_ba, ZEROLEN, "AttachPayloadKDF", 32)
2020-01-29 17:54:26 +00:00
// decrypt payload
if (!i2p::crypto::AEADChaCha20Poly1305 (buf, len - 16, m_H, 32, keydata, nonce, buf, len - 16, false)) // decrypt
2020-01-29 17:54:26 +00:00
{
LogPrint (eLogWarning, "Garlic: Payload section AEAD decryption failed");
return false;
}
2020-04-29 02:03:13 +00:00
if (m_State == eSessionStateNewSessionSent)
{
2020-04-29 02:03:13 +00:00
m_State = eSessionStateEstablished;
2020-12-27 16:18:53 +00:00
//m_EphemeralKeys = nullptr; // TODO: delete after a while
m_SessionCreatedTimestamp = i2p::util::GetSecondsSinceEpoch ();
2020-04-29 02:03:13 +00:00
GetOwner ()->AddECIESx25519Session (m_RemoteStaticKey, shared_from_this ());
}
HandlePayload (buf, len - 16, nullptr, 0);
2020-01-29 17:54:26 +00:00
// we have received reply to NS with LeaseSet in it
SetLeaseSetUpdateStatus (eLeaseSetUpToDate);
SetLeaseSetUpdateMsgID (0);
return true;
}
2020-01-21 19:40:23 +00:00
2020-02-05 20:48:51 +00:00
bool ECIESX25519AEADRatchetSession::NewExistingSessionMessage (const uint8_t * payload, size_t len, uint8_t * out, size_t outLen)
2020-02-03 21:21:07 +00:00
{
uint8_t nonce[12];
2020-04-24 19:46:02 +00:00
auto index = m_SendTagset->GetNextIndex ();
2020-02-09 02:51:02 +00:00
CreateNonce (index, nonce); // tag's index
2020-04-24 19:46:02 +00:00
uint64_t tag = m_SendTagset->GetNextSessionTag ();
2020-12-26 22:18:29 +00:00
if (!tag)
{
LogPrint (eLogError, "Garlic: can't create new ECIES-X25519-AEAD-Ratchet tag for send tagset");
if (GetOwner ())
GetOwner ()->RemoveECIESx25519Session (m_RemoteStaticKey);
return false;
}
2020-02-05 20:48:51 +00:00
memcpy (out, &tag, 8);
2020-02-03 21:21:07 +00:00
// ad = The session tag, 8 bytes
// ciphertext = ENCRYPT(k, n, payload, ad)
2020-03-07 23:46:40 +00:00
uint8_t key[32];
2020-04-24 19:46:02 +00:00
m_SendTagset->GetSymmKey (index, key);
2020-03-07 23:46:40 +00:00
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len, out, 8, key, nonce, out + 8, outLen - 8, true)) // encrypt
2020-02-05 20:48:51 +00:00
{
LogPrint (eLogWarning, "Garlic: Payload section AEAD encryption failed");
return false;
}
2020-04-26 23:27:31 +00:00
if (index >= ECIESX25519_TAGSET_MAX_NUM_TAGS && !m_SendForwardKey)
NewNextSendRatchet ();
2020-02-05 20:48:51 +00:00
return true;
}
bool ECIESX25519AEADRatchetSession::HandleExistingSessionMessage (uint8_t * buf, size_t len,
2021-01-04 23:20:16 +00:00
std::shared_ptr<ReceiveRatchetTagSet> receiveTagset, int index)
2020-02-05 20:48:51 +00:00
{
uint8_t nonce[12];
CreateNonce (index, nonce); // tag's index
len -= 8; // tag
uint8_t * payload = buf + 8;
2020-03-07 23:46:40 +00:00
uint8_t key[32];
2020-04-25 01:36:08 +00:00
receiveTagset->GetSymmKey (index, key);
if (!i2p::crypto::AEADChaCha20Poly1305 (payload, len - 16, buf, 8, key, nonce, payload, len - 16, false)) // decrypt
2020-02-03 21:21:07 +00:00
{
LogPrint (eLogWarning, "Garlic: Payload section AEAD decryption failed");
return false;
}
HandlePayload (payload, len - 16, receiveTagset, index);
2020-06-13 00:42:54 +00:00
if (GetOwner ())
{
int moreTags = 0;
if (GetOwner ()->GetNumRatchetInboundTags () > 0) // override in settings?
{
if (receiveTagset->GetNextIndex () - index < GetOwner ()->GetNumRatchetInboundTags ()/2)
moreTags = GetOwner ()->GetNumRatchetInboundTags ();
index -= GetOwner ()->GetNumRatchetInboundTags (); // trim behind
2020-06-13 00:42:54 +00:00
}
else
{
moreTags = ECIESX25519_MIN_NUM_GENERATED_TAGS + (index >> 2); // N/4
if (moreTags > ECIESX25519_MAX_NUM_GENERATED_TAGS) moreTags = ECIESX25519_MAX_NUM_GENERATED_TAGS;
moreTags -= (receiveTagset->GetNextIndex () - index);
index -= ECIESX25519_MAX_NUM_GENERATED_TAGS; // trim behind
2020-06-13 00:42:54 +00:00
}
if (moreTags > 0)
GenerateMoreReceiveTags (receiveTagset, moreTags);
if (index > 0)
receiveTagset->SetTrimBehind (index);
2020-06-13 00:42:54 +00:00
}
2020-02-03 21:21:07 +00:00
return true;
}
bool ECIESX25519AEADRatchetSession::HandleNextMessage (uint8_t * buf, size_t len,
2021-01-04 23:20:16 +00:00
std::shared_ptr<ReceiveRatchetTagSet> receiveTagset, int index)
{
m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
switch (m_State)
{
case eSessionStateNewSessionReplySent:
m_State = eSessionStateEstablished;
2020-06-04 22:19:38 +00:00
m_NSRSendTagset = nullptr;
m_EphemeralKeys = nullptr;
#if (__cplusplus >= 201703L) // C++ 17 or higher
[[fallthrough]];
#endif
2020-02-03 21:21:07 +00:00
case eSessionStateEstablished:
2020-12-27 16:18:53 +00:00
if (receiveTagset->IsNS ())
{
// our of sequence NSR
LogPrint (eLogDebug, "Garlic: check for out of order NSR with index ", index);
if (receiveTagset->GetNextIndex () - index < ECIESX25519_NSR_NUM_GENERATED_TAGS/2)
GenerateMoreReceiveTags (receiveTagset, ECIESX25519_NSR_NUM_GENERATED_TAGS);
return HandleNewOutgoingSessionReply (buf, len);
}
else
return HandleExistingSessionMessage (buf, len, receiveTagset, index);
case eSessionStateNew:
2020-02-03 21:21:07 +00:00
return HandleNewIncomingSession (buf, len);
case eSessionStateNewSessionSent:
2020-05-01 01:27:35 +00:00
receiveTagset->Expire (); // NSR tagset
2020-02-03 21:21:07 +00:00
return HandleNewOutgoingSessionReply (buf, len);
default:
return false;
}
return true;
}
std::shared_ptr<I2NPMessage> ECIESX25519AEADRatchetSession::WrapSingleMessage (std::shared_ptr<const I2NPMessage> msg)
{
auto payload = CreatePayload (msg, m_State != eSessionStateEstablished);
size_t len = payload.size ();
if (!len) return nullptr;
2020-04-30 19:38:15 +00:00
auto m = NewI2NPMessage (len + 100); // 96 + 4
m->Align (12); // in order to get buf aligned to 16 (12 + 4)
uint8_t * buf = m->GetPayload () + 4; // 4 bytes for length
switch (m_State)
{
2020-02-05 20:48:51 +00:00
case eSessionStateEstablished:
if (!NewExistingSessionMessage (payload.data (), payload.size (), buf, m->maxLen))
return nullptr;
len += 24;
break;
case eSessionStateNew:
if (!NewOutgoingSessionMessage (payload.data (), payload.size (), buf, m->maxLen))
return nullptr;
len += 96;
break;
case eSessionStateNewSessionReceived:
if (!NewSessionReplyMessage (payload.data (), payload.size (), buf, m->maxLen))
return nullptr;
len += 72;
break;
case eSessionStateNewSessionReplySent:
if (!NextNewSessionReplyMessage (payload.data (), payload.size (), buf, m->maxLen))
return nullptr;
len += 72;
break;
case eSessionStateOneTime:
if (!NewOutgoingSessionMessage (payload.data (), payload.size (), buf, m->maxLen, false))
return nullptr;
len += 96;
break;
2020-12-04 00:43:43 +00:00
case eSessionStateForRouter:
if (!NewOutgoingMessageForRouter (payload.data (), payload.size (), buf, m->maxLen))
return nullptr;
len += 48;
break;
default:
return nullptr;
}
htobe32buf (m->GetPayload (), len);
2020-01-17 16:21:41 +00:00
m->len += len + 4;
m->FillI2NPMessageHeader (eI2NPGarlic);
return m;
}
2020-01-17 16:21:41 +00:00
2020-12-04 00:43:43 +00:00
std::shared_ptr<I2NPMessage> ECIESX25519AEADRatchetSession::WrapOneTimeMessage (std::shared_ptr<const I2NPMessage> msg, bool isForRouter)
{
2020-12-04 00:43:43 +00:00
m_State = isForRouter ? eSessionStateForRouter : eSessionStateOneTime;
return WrapSingleMessage (msg);
}
std::vector<uint8_t> ECIESX25519AEADRatchetSession::CreatePayload (std::shared_ptr<const I2NPMessage> msg, bool first)
{
2020-03-08 22:13:41 +00:00
uint64_t ts = i2p::util::GetMillisecondsSinceEpoch ();
size_t payloadLen = 0;
if (first) payloadLen += 7;// datatime
if (msg)
{
payloadLen += msg->GetPayloadLength () + 13;
if (m_Destination) payloadLen += 32;
}
2021-01-24 02:25:52 +00:00
if (GetLeaseSetUpdateStatus () == eLeaseSetSubmitted && ts > GetLeaseSetSubmissionTime () + LEASET_CONFIRMATION_TIMEOUT)
{
// resubmit non-confirmed LeaseSet
SetLeaseSetUpdateStatus (eLeaseSetUpdated);
SetSharedRoutingPath (nullptr); // invalidate path since leaseset was not confirmed
}
auto leaseSet = (GetLeaseSetUpdateStatus () == eLeaseSetUpdated) ? GetOwner ()->GetLeaseSet () : nullptr;
2020-03-08 22:13:41 +00:00
if (leaseSet)
{
payloadLen += leaseSet->GetBufferLen () + DATABASE_STORE_HEADER_SIZE + 13;
if (!first)
{
// ack request
SetLeaseSetUpdateStatus (eLeaseSetSubmitted);
2020-04-24 19:46:02 +00:00
SetLeaseSetUpdateMsgID (m_SendTagset->GetNextIndex ());
SetLeaseSetSubmissionTime (ts);
payloadLen += 4;
}
}
2020-03-26 23:03:38 +00:00
if (m_AckRequests.size () > 0)
payloadLen += m_AckRequests.size ()*4 + 3;
if (m_SendReverseKey)
{
payloadLen += 6;
if (m_NextReceiveRatchet->newKey) payloadLen += 32;
}
2020-04-26 23:27:31 +00:00
if (m_SendForwardKey)
{
payloadLen += 6;
if (m_NextSendRatchet->newKey) payloadLen += 32;
}
uint8_t paddingSize = 0;
if (payloadLen || ts > m_LastSentTimestamp + ECIESX25519_SEND_INACTIVITY_TIMEOUT)
{
int delta = (int)ECIESX25519_OPTIMAL_PAYLOAD_SIZE - (int)payloadLen;
if (delta < 0 || delta > 3) // don't create padding if we are close to optimal size
{
2020-06-14 01:24:16 +00:00
paddingSize = m_PaddingSizes[m_NextPaddingSize++] & 0x0F; // 0 - 15
if (m_NextPaddingSize >= 32)
{
RAND_bytes (m_PaddingSizes, 32);
m_NextPaddingSize = 0;
}
if (delta > 3)
{
delta -= 3;
if (paddingSize >= delta) paddingSize %= delta;
}
paddingSize++;
payloadLen += paddingSize + 3;
}
}
std::vector<uint8_t> v(payloadLen);
if (payloadLen)
{
m_LastSentTimestamp = ts;
size_t offset = 0;
// DateTime
if (first)
{
v[offset] = eECIESx25519BlkDateTime; offset++;
htobe16buf (v.data () + offset, 4); offset += 2;
htobe32buf (v.data () + offset, ts/1000); offset += 4; // in seconds
}
// LeaseSet
if (leaseSet)
2020-03-26 23:03:38 +00:00
{
offset += CreateLeaseSetClove (leaseSet, ts, v.data () + offset, payloadLen - offset);
if (!first)
{
// ack request
v[offset] = eECIESx25519BlkAckRequest; offset++;
htobe16buf (v.data () + offset, 1); offset += 2;
v[offset] = 0; offset++; // flags
}
}
// msg
2020-11-09 20:35:50 +00:00
if (msg)
offset += CreateGarlicClove (msg, v.data () + offset, payloadLen - offset);
// ack
if (m_AckRequests.size () > 0)
{
v[offset] = eECIESx25519BlkAck; offset++;
htobe16buf (v.data () + offset, m_AckRequests.size () * 4); offset += 2;
for (auto& it: m_AckRequests)
{
htobe16buf (v.data () + offset, it.first); offset += 2;
htobe16buf (v.data () + offset, it.second); offset += 2;
}
m_AckRequests.clear ();
}
// next keys
if (m_SendReverseKey)
{
v[offset] = eECIESx25519BlkNextKey; offset++;
htobe16buf (v.data () + offset, m_NextReceiveRatchet->newKey ? 35 : 3); offset += 2;
v[offset] = ECIESX25519_NEXT_KEY_REVERSE_KEY_FLAG;
int keyID = m_NextReceiveRatchet->keyID - 1;
if (m_NextReceiveRatchet->newKey)
{
v[offset] |= ECIESX25519_NEXT_KEY_KEY_PRESENT_FLAG;
keyID++;
}
offset++; // flag
htobe16buf (v.data () + offset, keyID); offset += 2; // keyid
if (m_NextReceiveRatchet->newKey)
{
memcpy (v.data () + offset, m_NextReceiveRatchet->key->GetPublicKey (), 32);
offset += 32; // public key
}
m_SendReverseKey = false;
}
if (m_SendForwardKey)
{
v[offset] = eECIESx25519BlkNextKey; offset++;
htobe16buf (v.data () + offset, m_NextSendRatchet->newKey ? 35 : 3); offset += 2;
v[offset] = m_NextSendRatchet->newKey ? ECIESX25519_NEXT_KEY_KEY_PRESENT_FLAG : ECIESX25519_NEXT_KEY_REQUEST_REVERSE_KEY_FLAG;
if (!m_NextSendRatchet->keyID) v[offset] |= ECIESX25519_NEXT_KEY_REQUEST_REVERSE_KEY_FLAG; // for first key only
offset++; // flag
htobe16buf (v.data () + offset, m_NextSendRatchet->keyID); offset += 2; // keyid
if (m_NextSendRatchet->newKey)
{
memcpy (v.data () + offset, m_NextSendRatchet->key->GetPublicKey (), 32);
offset += 32; // public key
}
}
// padding
if (paddingSize)
{
v[offset] = eECIESx25519BlkPadding; offset++;
htobe16buf (v.data () + offset, paddingSize); offset += 2;
memset (v.data () + offset, 0, paddingSize); offset += paddingSize;
}
}
return v;
}
size_t ECIESX25519AEADRatchetSession::CreateGarlicClove (std::shared_ptr<const I2NPMessage> msg, uint8_t * buf, size_t len)
{
if (!msg) return 0;
uint16_t cloveSize = msg->GetPayloadLength () + 9 + 1;
if (m_Destination) cloveSize += 32;
if ((int)len < cloveSize + 3) return 0;
buf[0] = eECIESx25519BlkGalicClove; // clove type
htobe16buf (buf + 1, cloveSize); // size
2020-01-30 16:48:32 +00:00
buf += 3;
if (m_Destination)
2020-01-30 16:48:32 +00:00
{
*buf = (eGarlicDeliveryTypeDestination << 5);
memcpy (buf + 1, *m_Destination, 32); buf += 32;
}
else
*buf = 0;
2020-01-30 16:48:32 +00:00
buf++; // flag and delivery instructions
*buf = msg->GetTypeID (); // I2NP msg type
htobe32buf (buf + 1, msg->GetMsgID ()); // msgID
htobe32buf (buf + 5, msg->GetExpiration () / 1000); // expiration in seconds
memcpy (buf + 9, msg->GetPayload (), msg->GetPayloadLength ());
return cloveSize + 3;
}
2020-02-09 22:19:42 +00:00
2020-05-13 22:09:26 +00:00
size_t ECIESX25519AEADRatchetSession::CreateLeaseSetClove (std::shared_ptr<const i2p::data::LocalLeaseSet> ls, uint64_t ts, uint8_t * buf, size_t len)
{
2020-05-13 22:09:26 +00:00
if (!ls || ls->GetStoreType () != i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2)
{
LogPrint (eLogError, "Garlic: Incorrect LeasetSet type to send");
return 0;
}
2020-05-13 22:09:26 +00:00
uint16_t cloveSize = 1 + 9 + DATABASE_STORE_HEADER_SIZE + ls->GetBufferLen (); // to local
2020-03-08 22:13:41 +00:00
if ((int)len < cloveSize + 3) return 0;
buf[0] = eECIESx25519BlkGalicClove; // clove type
htobe16buf (buf + 1, cloveSize); // size
2020-03-08 22:13:41 +00:00
buf += 3;
2020-05-13 22:09:26 +00:00
*buf = 0; buf++; // flag and delivery instructions
*buf = eI2NPDatabaseStore; buf++; // I2NP msg type
RAND_bytes (buf, 4); buf += 4; // msgID
htobe32buf (buf, (ts + I2NP_MESSAGE_EXPIRATION_TIMEOUT)/1000); buf += 4; // expiration
2020-05-13 22:09:26 +00:00
// payload
memcpy (buf + DATABASE_STORE_KEY_OFFSET, ls->GetStoreHash (), 32);
buf[DATABASE_STORE_TYPE_OFFSET] = i2p::data::NETDB_STORE_TYPE_STANDARD_LEASESET2;
memset (buf + DATABASE_STORE_REPLY_TOKEN_OFFSET, 0, 4); // replyToken = 0
2020-05-13 22:09:26 +00:00
buf += DATABASE_STORE_HEADER_SIZE;
memcpy (buf, ls->GetBuffer (), ls->GetBufferLen ());
2020-03-08 22:13:41 +00:00
return cloveSize + 3;
2020-05-13 22:09:26 +00:00
}
2021-01-04 23:20:16 +00:00
void ECIESX25519AEADRatchetSession::GenerateMoreReceiveTags (std::shared_ptr<ReceiveRatchetTagSet> receiveTagset, int numTags)
2020-02-09 22:19:42 +00:00
{
if (GetOwner ())
{
for (int i = 0; i < numTags; i++)
2020-12-26 22:18:29 +00:00
{
auto tag = GetOwner ()->AddECIESx25519SessionNextTag (receiveTagset);
if (!tag)
{
LogPrint (eLogError, "Garlic: can't create new ECIES-X25519-AEAD-Ratchet tag for receive tagset");
break;
}
}
}
}
bool ECIESX25519AEADRatchetSession::CheckExpired (uint64_t ts)
{
CleanupUnconfirmedLeaseSet (ts);
2021-01-09 23:59:09 +00:00
return ts > m_LastActivityTimestamp + ECIESX25519_RECEIVE_EXPIRATION_TIMEOUT && // seconds
ts*1000 > m_LastSentTimestamp + ECIESX25519_SEND_EXPIRATION_TIMEOUT*1000; // milliseconds
}
RouterIncomingRatchetSession::RouterIncomingRatchetSession (const i2p::crypto::NoiseSymmetricState& initState):
ECIESX25519AEADRatchetSession (&i2p::context, false)
{
SetNoiseState (initState);
}
bool RouterIncomingRatchetSession::HandleNextMessage (const uint8_t * buf, size_t len)
{
if (!GetOwner ()) return false;
i2p::crypto::NoiseSymmetricState state (GetNoiseState ());
// we are Bob
state.MixHash (buf, 32);
uint8_t sharedSecret[32];
if (!GetOwner ()->Decrypt (buf, sharedSecret, nullptr, i2p::data::CRYPTO_KEY_TYPE_ECIES_X25519_AEAD)) // x25519(bsk, aepk)
{
LogPrint (eLogWarning, "Garlic: Incorrect N ephemeral public key");
return false;
}
state.MixKey (sharedSecret);
buf += 32; len -= 32;
uint8_t nonce[12];
CreateNonce (0, nonce);
std::vector<uint8_t> payload (len - 16);
if (!i2p::crypto::AEADChaCha20Poly1305 (buf, len - 16, state.m_H, 32, state.m_CK + 32, nonce, payload.data (), len - 16, false)) // decrypt
{
LogPrint (eLogWarning, "Garlic: Payload for router AEAD verification failed");
return false;
}
HandlePayload (payload.data (), len - 16, nullptr, 0);
return true;
}
std::shared_ptr<I2NPMessage> WrapECIESX25519AEADRatchetMessage (std::shared_ptr<const I2NPMessage> msg, const uint8_t * key, uint64_t tag)
{
auto m = NewI2NPMessage ();
m->Align (12); // in order to get buf aligned to 16 (12 + 4)
uint8_t * buf = m->GetPayload () + 4; // 4 bytes for length
uint8_t nonce[12];
memset (nonce, 0, 12); // n = 0
size_t offset = 0;
memcpy (buf + offset, &tag, 8); offset += 8;
auto payload = buf + offset;
uint16_t cloveSize = msg->GetPayloadLength () + 9 + 1;
size_t len = cloveSize + 3;
payload[0] = eECIESx25519BlkGalicClove; // clove type
htobe16buf (payload + 1, cloveSize); // size
payload += 3;
*payload = 0; payload++; // flag and delivery instructions
*payload = msg->GetTypeID (); // I2NP msg type
htobe32buf (payload + 1, msg->GetMsgID ()); // msgID
htobe32buf (payload + 5, msg->GetExpiration () / 1000); // expiration in seconds
memcpy (payload + 9, msg->GetPayload (), msg->GetPayloadLength ());
if (!i2p::crypto::AEADChaCha20Poly1305 (buf + offset, len, buf, 8, key, nonce, buf + offset, len + 16, true)) // encrypt
{
LogPrint (eLogWarning, "Garlic: Payload section AEAD encryption failed");
return nullptr;
}
offset += len + 16;
htobe32buf (m->GetPayload (), offset);
m->len += offset + 4;
m->FillI2NPMessageHeader (eI2NPGarlic);
return m;
}
2020-01-15 20:13:43 +00:00
}
}