NTCP2.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409
  1. /*
  2. * Copyright (c) 2013-2018, The PurpleI2P Project
  3. *
  4. * This file is part of Purple i2pd project and licensed under BSD3
  5. *
  6. * See full license text in LICENSE file at top of project tree
  7. *
  8. * Kovri go write your own code
  9. *
  10. */
  11. #include <openssl/rand.h>
  12. #include <openssl/sha.h>
  13. #include <openssl/hmac.h>
  14. #include <stdlib.h>
  15. #include <vector>
  16. #include "Log.h"
  17. #include "I2PEndian.h"
  18. #include "Crypto.h"
  19. #include "Siphash.h"
  20. #include "RouterContext.h"
  21. #include "Transports.h"
  22. #include "NetDb.hpp"
  23. #include "NTCP2.h"
  24. namespace i2p
  25. {
  26. namespace transport
  27. {
  28. NTCP2Establisher::NTCP2Establisher ():
  29. m_SessionRequestBuffer (nullptr), m_SessionCreatedBuffer (nullptr), m_SessionConfirmedBuffer (nullptr)
  30. {
  31. }
  32. NTCP2Establisher::~NTCP2Establisher ()
  33. {
  34. delete[] m_SessionRequestBuffer;
  35. delete[] m_SessionCreatedBuffer;
  36. delete[] m_SessionConfirmedBuffer;
  37. }
  38. void NTCP2Establisher::MixKey (const uint8_t * inputKeyMaterial)
  39. {
  40. // temp_key = HMAC-SHA256(ck, input_key_material)
  41. uint8_t tempKey[32]; unsigned int len;
  42. HMAC(EVP_sha256(), m_CK, 32, inputKeyMaterial, 32, tempKey, &len);
  43. // ck = HMAC-SHA256(temp_key, byte(0x01))
  44. static uint8_t one[1] = { 1 };
  45. HMAC(EVP_sha256(), tempKey, 32, one, 1, m_CK, &len);
  46. // derived = HMAC-SHA256(temp_key, ck || byte(0x02))
  47. m_CK[32] = 2;
  48. HMAC(EVP_sha256(), tempKey, 32, m_CK, 33, m_K, &len);
  49. }
  50. void NTCP2Establisher::MixHash (const uint8_t * buf, size_t len)
  51. {
  52. SHA256_CTX ctx;
  53. SHA256_Init (&ctx);
  54. SHA256_Update (&ctx, m_H, 32);
  55. SHA256_Update (&ctx, buf, len);
  56. SHA256_Final (m_H, &ctx);
  57. }
  58. void NTCP2Establisher::KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub)
  59. {
  60. static const uint8_t protocolNameHash[] =
  61. {
  62. 0x72, 0xe8, 0x42, 0xc5, 0x45, 0xe1, 0x80, 0x80, 0xd3, 0x9c, 0x44, 0x93, 0xbb, 0x91, 0xd7, 0xed,
  63. 0xf2, 0x28, 0x98, 0x17, 0x71, 0x21, 0x8c, 0x1f, 0x62, 0x4e, 0x20, 0x6f, 0x28, 0xd3, 0x2f, 0x71
  64. }; // SHA256 ("Noise_XKaesobfse+hs2+hs3_25519_ChaChaPoly_SHA256")
  65. static const uint8_t hh[32] =
  66. {
  67. 0x49, 0xff, 0x48, 0x3f, 0xc4, 0x04, 0xb9, 0xb2, 0x6b, 0x11, 0x94, 0x36, 0x72, 0xff, 0x05, 0xb5,
  68. 0x61, 0x27, 0x03, 0x31, 0xba, 0x89, 0xb8, 0xfc, 0x33, 0x15, 0x93, 0x87, 0x57, 0xdd, 0x3d, 0x1e
  69. }; // SHA256 (protocolNameHash)
  70. memcpy (m_CK, protocolNameHash, 32);
  71. // h = SHA256(hh || rs)
  72. SHA256_CTX ctx;
  73. SHA256_Init (&ctx);
  74. SHA256_Update (&ctx, hh, 32);
  75. SHA256_Update (&ctx, rs, 32);
  76. SHA256_Final (m_H, &ctx);
  77. // h = SHA256(h || epub)
  78. MixHash (epub, 32);
  79. // x25519 between pub and priv
  80. uint8_t inputKeyMaterial[32];
  81. priv.Agree (pub, inputKeyMaterial);
  82. MixKey (inputKeyMaterial);
  83. }
  84. void NTCP2Establisher::KDF1Alice ()
  85. {
  86. KeyDerivationFunction1 (m_RemoteStaticKey, m_EphemeralKeys, m_RemoteStaticKey, GetPub ());
  87. }
  88. void NTCP2Establisher::KDF1Bob ()
  89. {
  90. KeyDerivationFunction1 (GetRemotePub (), i2p::context.GetStaticKeys (), i2p::context.GetNTCP2StaticPublicKey (), GetRemotePub ());
  91. }
  92. void NTCP2Establisher::KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub)
  93. {
  94. MixHash (sessionRequest + 32, 32); // encrypted payload
  95. int paddingLength = sessionRequestLen - 64;
  96. if (paddingLength > 0)
  97. MixHash (sessionRequest + 64, paddingLength);
  98. MixHash (epub, 32);
  99. // x25519 between remote pub and ephemaral priv
  100. uint8_t inputKeyMaterial[32];
  101. m_EphemeralKeys.Agree (GetRemotePub (), inputKeyMaterial);
  102. MixKey (inputKeyMaterial);
  103. }
  104. void NTCP2Establisher::KDF2Alice ()
  105. {
  106. KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetRemotePub ());
  107. }
  108. void NTCP2Establisher::KDF2Bob ()
  109. {
  110. KeyDerivationFunction2 (m_SessionRequestBuffer, m_SessionRequestBufferLen, GetPub ());
  111. }
  112. void NTCP2Establisher::KDF3Alice ()
  113. {
  114. uint8_t inputKeyMaterial[32];
  115. i2p::context.GetStaticKeys ().Agree (GetRemotePub (), inputKeyMaterial);
  116. MixKey (inputKeyMaterial);
  117. }
  118. void NTCP2Establisher::KDF3Bob ()
  119. {
  120. uint8_t inputKeyMaterial[32];
  121. m_EphemeralKeys.Agree (m_RemoteStaticKey, inputKeyMaterial);
  122. MixKey (inputKeyMaterial);
  123. }
  124. void NTCP2Establisher::CreateEphemeralKey ()
  125. {
  126. m_EphemeralKeys.GenerateKeys ();
  127. }
  128. void NTCP2Establisher::CreateSessionRequestMessage ()
  129. {
  130. // create buffer and fill padding
  131. auto paddingLength = rand () % (287 - 64); // message length doesn't exceed 287 bytes
  132. m_SessionRequestBufferLen = paddingLength + 64;
  133. m_SessionRequestBuffer = new uint8_t[m_SessionRequestBufferLen];
  134. RAND_bytes (m_SessionRequestBuffer + 64, paddingLength);
  135. // encrypt X
  136. i2p::crypto::CBCEncryption encryption;
  137. encryption.SetKey (m_RemoteIdentHash);
  138. encryption.SetIV (m_IV);
  139. encryption.Encrypt (GetPub (), 32, m_SessionRequestBuffer); // X
  140. encryption.GetIV (m_IV); // save IV for SessionCreated
  141. // encryption key for next block
  142. KDF1Alice ();
  143. // fill options
  144. uint8_t options[32]; // actual options size is 16 bytes
  145. memset (options, 0, 16);
  146. options[1] = 2; // ver
  147. htobe16buf (options + 2, paddingLength); // padLen
  148. // m3p2Len
  149. auto bufLen = i2p::context.GetRouterInfo ().GetBufferLen ();
  150. m3p2Len = bufLen + 4 + 16; // (RI header + RI + MAC for now) TODO: implement options
  151. htobe16buf (options + 4, m3p2Len);
  152. // fill m3p2 payload (RouterInfo block)
  153. m_SessionConfirmedBuffer = new uint8_t[m3p2Len + 48]; // m3p1 is 48 bytes
  154. uint8_t * m3p2 = m_SessionConfirmedBuffer + 48;
  155. m3p2[0] = eNTCP2BlkRouterInfo; // block
  156. htobe16buf (m3p2 + 1, bufLen + 1); // flag + RI
  157. m3p2[3] = 0; // flag
  158. memcpy (m3p2 + 4, i2p::context.GetRouterInfo ().GetBuffer (), bufLen); // TODO: own RI should be protected by mutex
  159. // 2 bytes reserved
  160. htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsA
  161. // 4 bytes reserved
  162. // sign and encrypt options, use m_H as AD
  163. uint8_t nonce[12];
  164. memset (nonce, 0, 12); // set nonce to zero
  165. i2p::crypto::AEADChaCha20Poly1305 (options, 16, m_H, 32, m_K, nonce, m_SessionRequestBuffer + 32, 32, true); // encrypt
  166. }
  167. void NTCP2Establisher::CreateSessionCreatedMessage ()
  168. {
  169. auto paddingLen = rand () % (287 - 64);
  170. m_SessionCreatedBufferLen = paddingLen + 64;
  171. m_SessionCreatedBuffer = new uint8_t[m_SessionCreatedBufferLen];
  172. RAND_bytes (m_SessionCreatedBuffer + 64, paddingLen);
  173. // encrypt Y
  174. i2p::crypto::CBCEncryption encryption;
  175. encryption.SetKey (i2p::context.GetIdentHash ());
  176. encryption.SetIV (m_IV);
  177. encryption.Encrypt (GetPub (), 32, m_SessionCreatedBuffer); // Y
  178. // encryption key for next block (m_K)
  179. KDF2Bob ();
  180. uint8_t options[16];
  181. memset (options, 0, 16);
  182. htobe16buf (options + 2, paddingLen); // padLen
  183. htobe32buf (options + 8, i2p::util::GetSecondsSinceEpoch ()); // tsB
  184. // sign and encrypt options, use m_H as AD
  185. uint8_t nonce[12];
  186. memset (nonce, 0, 12); // set nonce to zero
  187. i2p::crypto::AEADChaCha20Poly1305 (options, 16, m_H, 32, m_K, nonce, m_SessionCreatedBuffer + 32, 32, true); // encrypt
  188. }
  189. void NTCP2Establisher::CreateSessionConfirmedMessagePart1 (const uint8_t * nonce)
  190. {
  191. // update AD
  192. MixHash (m_SessionCreatedBuffer + 32, 32); // encrypted payload
  193. int paddingLength = m_SessionCreatedBufferLen - 64;
  194. if (paddingLength > 0)
  195. MixHash (m_SessionCreatedBuffer + 64, paddingLength);
  196. // part1 48 bytes
  197. i2p::crypto::AEADChaCha20Poly1305 (i2p::context.GetNTCP2StaticPublicKey (), 32, m_H, 32, m_K, nonce, m_SessionConfirmedBuffer, 48, true); // encrypt
  198. }
  199. void NTCP2Establisher::CreateSessionConfirmedMessagePart2 (const uint8_t * nonce)
  200. {
  201. // part 2
  202. // update AD again
  203. MixHash (m_SessionConfirmedBuffer, 48);
  204. // encrypt m3p2, it must be filled in SessionRequest
  205. KDF3Alice ();
  206. uint8_t * m3p2 = m_SessionConfirmedBuffer + 48;
  207. i2p::crypto::AEADChaCha20Poly1305 (m3p2, m3p2Len - 16, m_H, 32, m_K, nonce, m3p2, m3p2Len, true); // encrypt
  208. // update h again
  209. MixHash (m3p2, m3p2Len); //h = SHA256(h || ciphertext)
  210. }
  211. bool NTCP2Establisher::ProcessSessionRequestMessage (uint16_t& paddingLen)
  212. {
  213. // decrypt X
  214. i2p::crypto::CBCDecryption decryption;
  215. decryption.SetKey (i2p::context.GetIdentHash ());
  216. decryption.SetIV (i2p::context.GetNTCP2IV ());
  217. decryption.Decrypt (m_SessionRequestBuffer, 32, GetRemotePub ());
  218. decryption.GetIV (m_IV); // save IV for SessionCreated
  219. // decryption key for next block
  220. KDF1Bob ();
  221. // verify MAC and decrypt options block (32 bytes), use m_H as AD
  222. uint8_t nonce[12], options[16];
  223. memset (nonce, 0, 12); // set nonce to zero
  224. if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionRequestBuffer + 32, 16, m_H, 32, m_K, nonce, options, 16, false)) // decrypt
  225. {
  226. // options
  227. if (options[1] == 2) // ver is always 2
  228. {
  229. paddingLen = bufbe16toh (options + 2);
  230. m_SessionRequestBufferLen = paddingLen + 64;
  231. m3p2Len = bufbe16toh (options + 4);
  232. if (m3p2Len < 16)
  233. {
  234. LogPrint (eLogWarning, "NTCP2: SessionRequest m3p2len=", m3p2Len, " is too short");
  235. return false;
  236. }
  237. // check timestamp
  238. auto ts = i2p::util::GetSecondsSinceEpoch ();
  239. uint32_t tsA = bufbe32toh (options + 8);
  240. if (tsA < ts - NTCP2_CLOCK_SKEW || tsA > ts + NTCP2_CLOCK_SKEW)
  241. {
  242. LogPrint (eLogWarning, "NTCP2: SessionRequest time difference ", (int)(ts - tsA), " exceeds clock skew");
  243. return false;
  244. }
  245. }
  246. else
  247. {
  248. LogPrint (eLogWarning, "NTCP2: SessionRequest version mismatch ", (int)options[1]);
  249. return false;
  250. }
  251. }
  252. else
  253. {
  254. LogPrint (eLogWarning, "NTCP2: SessionRequest AEAD verification failed ");
  255. return false;
  256. }
  257. return true;
  258. }
  259. bool NTCP2Establisher::ProcessSessionCreatedMessage (uint16_t& paddingLen)
  260. {
  261. m_SessionCreatedBufferLen = 64;
  262. // decrypt Y
  263. i2p::crypto::CBCDecryption decryption;
  264. decryption.SetKey (m_RemoteIdentHash);
  265. decryption.SetIV (m_IV);
  266. decryption.Decrypt (m_SessionCreatedBuffer, 32, GetRemotePub ());
  267. // decryption key for next block (m_K)
  268. KDF2Alice ();
  269. // decrypt and verify MAC
  270. uint8_t payload[16];
  271. uint8_t nonce[12];
  272. memset (nonce, 0, 12); // set nonce to zero
  273. if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionCreatedBuffer + 32, 16, m_H, 32, m_K, nonce, payload, 16, false)) // decrypt
  274. {
  275. // options
  276. paddingLen = bufbe16toh(payload + 2);
  277. // check timestamp
  278. auto ts = i2p::util::GetSecondsSinceEpoch ();
  279. uint32_t tsB = bufbe32toh (payload + 8);
  280. if (tsB < ts - NTCP2_CLOCK_SKEW || tsB > ts + NTCP2_CLOCK_SKEW)
  281. {
  282. LogPrint (eLogWarning, "NTCP2: SessionCreated time difference ", (int)(ts - tsB), " exceeds clock skew");
  283. return false;
  284. }
  285. }
  286. else
  287. {
  288. LogPrint (eLogWarning, "NTCP2: SessionCreated AEAD verification failed ");
  289. return false;
  290. }
  291. return true;
  292. }
  293. bool NTCP2Establisher::ProcessSessionConfirmedMessagePart1 (const uint8_t * nonce)
  294. {
  295. // update AD
  296. MixHash (m_SessionCreatedBuffer + 32, 32); // encrypted payload
  297. int paddingLength = m_SessionCreatedBufferLen - 64;
  298. if (paddingLength > 0)
  299. MixHash (m_SessionCreatedBuffer + 64, paddingLength);
  300. if (!i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer, 32, m_H, 32, m_K, nonce, m_RemoteStaticKey, 32, false)) // decrypt S
  301. {
  302. LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part1 AEAD verification failed ");
  303. return false;
  304. }
  305. return true;
  306. }
  307. bool NTCP2Establisher::ProcessSessionConfirmedMessagePart2 (const uint8_t * nonce, uint8_t * m3p2Buf)
  308. {
  309. // update AD again
  310. MixHash (m_SessionConfirmedBuffer, 48);
  311. KDF3Bob ();
  312. if (i2p::crypto::AEADChaCha20Poly1305 (m_SessionConfirmedBuffer + 48, m3p2Len - 16, m_H, 32, m_K, nonce, m3p2Buf, m3p2Len - 16, false)) // decrypt
  313. {
  314. // caclulate new h again for KDF data
  315. memcpy (m_SessionConfirmedBuffer + 16, m_H, 32); // h || ciphertext
  316. SHA256 (m_SessionConfirmedBuffer + 16, m3p2Len + 32, m_H); //h = SHA256(h || ciphertext);
  317. }
  318. else
  319. {
  320. LogPrint (eLogWarning, "NTCP2: SessionConfirmed Part2 AEAD verification failed ");
  321. return false;
  322. }
  323. return true;
  324. }
  325. NTCP2Session::NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter):
  326. TransportSession (in_RemoteRouter, NTCP2_ESTABLISH_TIMEOUT),
  327. m_Server (server), m_Socket (m_Server.GetService ()),
  328. m_IsEstablished (false), m_IsTerminated (false),
  329. m_Establisher (new NTCP2Establisher),
  330. m_SendSipKey (nullptr), m_ReceiveSipKey (nullptr),
  331. #if OPENSSL_SIPHASH
  332. m_SendMDCtx(nullptr), m_ReceiveMDCtx (nullptr),
  333. #endif
  334. m_NextReceivedLen (0), m_NextReceivedBuffer (nullptr), m_NextSendBuffer (nullptr),
  335. m_ReceiveSequenceNumber (0), m_SendSequenceNumber (0), m_IsSending (false)
  336. {
  337. if (in_RemoteRouter) // Alice
  338. {
  339. m_Establisher->m_RemoteIdentHash = GetRemoteIdentity ()->GetIdentHash ();
  340. auto addr = in_RemoteRouter->GetNTCP2Address (true); // we need a published address
  341. if (addr)
  342. {
  343. memcpy (m_Establisher->m_RemoteStaticKey, addr->ntcp2->staticKey, 32);
  344. memcpy (m_Establisher->m_IV, addr->ntcp2->iv, 16);
  345. }
  346. else
  347. LogPrint (eLogWarning, "NTCP2: Missing NTCP2 parameters");
  348. }
  349. }
  350. NTCP2Session::~NTCP2Session ()
  351. {
  352. delete[] m_NextReceivedBuffer;
  353. delete[] m_NextSendBuffer;
  354. #if OPENSSL_SIPHASH
  355. if (m_SendSipKey) EVP_PKEY_free (m_SendSipKey);
  356. if (m_ReceiveSipKey) EVP_PKEY_free (m_ReceiveSipKey);
  357. if (m_SendMDCtx) EVP_MD_CTX_destroy (m_SendMDCtx);
  358. if (m_ReceiveMDCtx) EVP_MD_CTX_destroy (m_ReceiveMDCtx);
  359. #endif
  360. }
  361. void NTCP2Session::Terminate ()
  362. {
  363. if (!m_IsTerminated)
  364. {
  365. m_IsTerminated = true;
  366. m_IsEstablished = false;
  367. boost::system::error_code ec;
  368. m_Socket.shutdown(boost::asio::ip::tcp::socket::shutdown_both, ec);
  369. if (ec)
  370. LogPrint (eLogDebug, "NTCP2: Couldn't shutdown socket: ", ec.message ());
  371. m_Socket.close ();
  372. transports.PeerDisconnected (shared_from_this ());
  373. m_Server.RemoveNTCP2Session (shared_from_this ());
  374. m_SendQueue.clear ();
  375. LogPrint (eLogDebug, "NTCP2: session terminated");
  376. }
  377. }
  378. void NTCP2Session::TerminateByTimeout ()
  379. {
  380. SendTerminationAndTerminate (eNTCP2IdleTimeout);
  381. }
  382. void NTCP2Session::Done ()
  383. {
  384. m_Server.GetService ().post (std::bind (&NTCP2Session::Terminate, shared_from_this ()));
  385. }
  386. void NTCP2Session::Established ()
  387. {
  388. m_IsEstablished = true;
  389. m_Establisher.reset (nullptr);
  390. SetTerminationTimeout (NTCP2_TERMINATION_TIMEOUT);
  391. transports.PeerConnected (shared_from_this ());
  392. }
  393. void NTCP2Session::CreateNonce (uint64_t seqn, uint8_t * nonce)
  394. {
  395. memset (nonce, 0, 4);
  396. htole64buf (nonce + 4, seqn);
  397. }
  398. void NTCP2Session::KeyDerivationFunctionDataPhase ()
  399. {
  400. uint8_t tempKey[32]; unsigned int len;
  401. HMAC(EVP_sha256(), m_Establisher->GetCK (), 32, nullptr, 0, tempKey, &len); // temp_key = HMAC-SHA256(ck, zerolen)
  402. static uint8_t one[1] = { 1 };
  403. HMAC(EVP_sha256(), tempKey, 32, one, 1, m_Kab, &len); // k_ab = HMAC-SHA256(temp_key, byte(0x01)).
  404. m_Kab[32] = 2;
  405. HMAC(EVP_sha256(), tempKey, 32, m_Kab, 33, m_Kba, &len); // k_ba = HMAC-SHA256(temp_key, k_ab || byte(0x02))
  406. static uint8_t ask[4] = { 'a', 's', 'k', 1 }, master[32];
  407. HMAC(EVP_sha256(), tempKey, 32, ask, 4, master, &len); // ask_master = HMAC-SHA256(temp_key, "ask" || byte(0x01))
  408. uint8_t h[39];
  409. memcpy (h, m_Establisher->GetH (), 32);
  410. memcpy (h + 32, "siphash", 7);
  411. HMAC(EVP_sha256(), master, 32, h, 39, tempKey, &len); // temp_key = HMAC-SHA256(ask_master, h || "siphash")
  412. HMAC(EVP_sha256(), tempKey, 32, one, 1, master, &len); // sip_master = HMAC-SHA256(temp_key, byte(0x01))
  413. HMAC(EVP_sha256(), master, 32, nullptr, 0, tempKey, &len); // temp_key = HMAC-SHA256(sip_master, zerolen)
  414. HMAC(EVP_sha256(), tempKey, 32, one, 1, m_Sipkeysab, &len); // sipkeys_ab = HMAC-SHA256(temp_key, byte(0x01)).
  415. m_Sipkeysab[32] = 2;
  416. HMAC(EVP_sha256(), tempKey, 32, m_Sipkeysab, 33, m_Sipkeysba, &len); // sipkeys_ba = HMAC-SHA256(temp_key, sipkeys_ab || byte(0x02))
  417. }
  418. void NTCP2Session::SendSessionRequest ()
  419. {
  420. m_Establisher->CreateSessionRequestMessage ();
  421. // send message
  422. boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionRequestBuffer, m_Establisher->m_SessionRequestBufferLen), boost::asio::transfer_all (),
  423. std::bind(&NTCP2Session::HandleSessionRequestSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  424. }
  425. void NTCP2Session::HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  426. {
  427. (void) bytes_transferred;
  428. if (ecode)
  429. {
  430. LogPrint (eLogWarning, "NTCP2: couldn't send SessionRequest message: ", ecode.message ());
  431. Terminate ();
  432. }
  433. else
  434. {
  435. m_Establisher->m_SessionCreatedBuffer = new uint8_t[287]; // TODO: determine actual max size
  436. // we receive first 64 bytes (32 Y, and 32 ChaCha/Poly frame) first
  437. boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionCreatedBuffer, 64), boost::asio::transfer_all (),
  438. std::bind(&NTCP2Session::HandleSessionCreatedReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  439. }
  440. }
  441. void NTCP2Session::HandleSessionRequestReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  442. {
  443. (void) bytes_transferred;
  444. if (ecode)
  445. {
  446. LogPrint (eLogWarning, "NTCP2: SessionRequest read error: ", ecode.message ());
  447. Terminate ();
  448. }
  449. else
  450. {
  451. LogPrint (eLogDebug, "NTCP2: SessionRequest received ", bytes_transferred);
  452. uint16_t paddingLen = 0;
  453. if (m_Establisher->ProcessSessionRequestMessage (paddingLen))
  454. {
  455. if (paddingLen > 0)
  456. {
  457. if (paddingLen <= 287 - 64) // session request is 287 bytes max
  458. {
  459. boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer + 64, paddingLen), boost::asio::transfer_all (),
  460. std::bind(&NTCP2Session::HandleSessionRequestPaddingReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  461. }
  462. else
  463. {
  464. LogPrint (eLogWarning, "NTCP2: SessionRequest padding length ", (int)paddingLen, " is too long");
  465. Terminate ();
  466. }
  467. }
  468. else
  469. SendSessionCreated ();
  470. }
  471. else
  472. Terminate ();
  473. }
  474. }
  475. void NTCP2Session::HandleSessionRequestPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  476. {
  477. if (ecode)
  478. {
  479. LogPrint (eLogWarning, "NTCP2: SessionRequest padding read error: ", ecode.message ());
  480. Terminate ();
  481. }
  482. else
  483. SendSessionCreated ();
  484. }
  485. void NTCP2Session::SendSessionCreated ()
  486. {
  487. m_Establisher->CreateSessionCreatedMessage ();
  488. // send message
  489. boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionCreatedBuffer, m_Establisher->m_SessionCreatedBufferLen), boost::asio::transfer_all (),
  490. std::bind(&NTCP2Session::HandleSessionCreatedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  491. }
  492. void NTCP2Session::HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  493. {
  494. if (ecode)
  495. {
  496. LogPrint (eLogWarning, "NTCP2: SessionCreated read error: ", ecode.message ());
  497. Terminate ();
  498. }
  499. else
  500. {
  501. LogPrint (eLogDebug, "NTCP2: SessionCreated received ", bytes_transferred);
  502. uint16_t paddingLen = 0;
  503. if (m_Establisher->ProcessSessionCreatedMessage (paddingLen))
  504. {
  505. if (paddingLen > 0)
  506. {
  507. if (paddingLen <= 287 - 64) // session created is 287 bytes max
  508. {
  509. boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionCreatedBuffer + 64, paddingLen), boost::asio::transfer_all (),
  510. std::bind(&NTCP2Session::HandleSessionCreatedPaddingReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  511. }
  512. else
  513. {
  514. LogPrint (eLogWarning, "NTCP2: SessionCreated padding length ", (int)paddingLen, " is too long");
  515. Terminate ();
  516. }
  517. }
  518. else
  519. SendSessionConfirmed ();
  520. }
  521. else
  522. Terminate ();
  523. }
  524. }
  525. void NTCP2Session::HandleSessionCreatedPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  526. {
  527. if (ecode)
  528. {
  529. LogPrint (eLogWarning, "NTCP2: SessionCreated padding read error: ", ecode.message ());
  530. Terminate ();
  531. }
  532. else
  533. {
  534. m_Establisher->m_SessionCreatedBufferLen += bytes_transferred;
  535. SendSessionConfirmed ();
  536. }
  537. }
  538. void NTCP2Session::SendSessionConfirmed ()
  539. {
  540. uint8_t nonce[12];
  541. CreateNonce (1, nonce); // set nonce to 1
  542. m_Establisher->CreateSessionConfirmedMessagePart1 (nonce);
  543. memset (nonce, 0, 12); // set nonce back to 0
  544. m_Establisher->CreateSessionConfirmedMessagePart2 (nonce);
  545. // send message
  546. boost::asio::async_write (m_Socket, boost::asio::buffer (m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (),
  547. std::bind(&NTCP2Session::HandleSessionConfirmedSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  548. }
  549. void NTCP2Session::HandleSessionConfirmedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  550. {
  551. LogPrint (eLogDebug, "NTCP2: SessionConfirmed sent");
  552. KeyDerivationFunctionDataPhase ();
  553. // Alice data phase keys
  554. m_SendKey = m_Kab;
  555. m_ReceiveKey = m_Kba;
  556. SetSipKeys (m_Sipkeysab, m_Sipkeysba);
  557. memcpy (m_ReceiveIV.buf, m_Sipkeysba + 16, 8);
  558. memcpy (m_SendIV.buf, m_Sipkeysab + 16, 8);
  559. Established ();
  560. ReceiveLength ();
  561. // TODO: remove
  562. // m_SendQueue.push_back (CreateDeliveryStatusMsg (1));
  563. // SendQueue ();
  564. }
  565. void NTCP2Session::HandleSessionCreatedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  566. {
  567. (void) bytes_transferred;
  568. if (ecode)
  569. {
  570. LogPrint (eLogWarning, "NTCP2: couldn't send SessionCreated message: ", ecode.message ());
  571. Terminate ();
  572. }
  573. else
  574. {
  575. LogPrint (eLogDebug, "NTCP2: SessionCreated sent");
  576. m_Establisher->m_SessionConfirmedBuffer = new uint8_t[m_Establisher->m3p2Len + 48];
  577. boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionConfirmedBuffer, m_Establisher->m3p2Len + 48), boost::asio::transfer_all (),
  578. std::bind(&NTCP2Session::HandleSessionConfirmedReceived , shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  579. }
  580. }
  581. void NTCP2Session::HandleSessionConfirmedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  582. {
  583. if (ecode)
  584. {
  585. LogPrint (eLogWarning, "NTCP2: SessionConfirmed read error: ", ecode.message ());
  586. Terminate ();
  587. }
  588. else
  589. {
  590. LogPrint (eLogDebug, "NTCP2: SessionConfirmed received");
  591. // part 1
  592. uint8_t nonce[12];
  593. CreateNonce (1, nonce);
  594. if (m_Establisher->ProcessSessionConfirmedMessagePart1 (nonce))
  595. {
  596. // part 2
  597. std::vector<uint8_t> buf(m_Establisher->m3p2Len - 16); // -MAC
  598. memset (nonce, 0, 12); // set nonce to 0 again
  599. if (m_Establisher->ProcessSessionConfirmedMessagePart2 (nonce, buf.data ()))
  600. {
  601. KeyDerivationFunctionDataPhase ();
  602. // Bob data phase keys
  603. m_SendKey = m_Kba;
  604. m_ReceiveKey = m_Kab;
  605. SetSipKeys (m_Sipkeysba, m_Sipkeysab);
  606. memcpy (m_ReceiveIV.buf, m_Sipkeysab + 16, 8);
  607. memcpy (m_SendIV.buf, m_Sipkeysba + 16, 8);
  608. // payload
  609. // process RI
  610. if (buf[0] != eNTCP2BlkRouterInfo)
  611. {
  612. LogPrint (eLogWarning, "NTCP2: unexpected block ", (int)buf[0], " in SessionConfirmed");
  613. Terminate ();
  614. return;
  615. }
  616. auto size = bufbe16toh (buf.data () + 1);
  617. if (size > buf.size () - 3)
  618. {
  619. LogPrint (eLogError, "NTCP2: Unexpected RouterInfo size ", size, " in SessionConfirmed");
  620. Terminate ();
  621. return;
  622. }
  623. // TODO: check flag
  624. i2p::data::RouterInfo ri (buf.data () + 4, size - 1); // 1 byte block type + 2 bytes size + 1 byte flag
  625. if (ri.IsUnreachable ())
  626. {
  627. LogPrint (eLogError, "NTCP2: Signature verification failed in SessionConfirmed");
  628. SendTerminationAndTerminate (eNTCP2RouterInfoSignatureVerificationFail);
  629. return;
  630. }
  631. if (i2p::util::GetMillisecondsSinceEpoch () > ri.GetTimestamp () + i2p::data::NETDB_MIN_EXPIRATION_TIMEOUT*1000LL) // 90 minutes
  632. {
  633. LogPrint (eLogError, "NTCP2: RouterInfo is too old in SessionConfirmed");
  634. SendTerminationAndTerminate (eNTCP2Message3Error);
  635. return;
  636. }
  637. auto addr = ri.GetNTCP2Address (false); // any NTCP2 address
  638. if (!addr)
  639. {
  640. LogPrint (eLogError, "NTCP2: No NTCP2 address found in SessionConfirmed");
  641. Terminate ();
  642. return;
  643. }
  644. if (memcmp (addr->ntcp2->staticKey, m_Establisher->m_RemoteStaticKey, 32))
  645. {
  646. LogPrint (eLogError, "NTCP2: Static key mismatch in SessionConfirmed");
  647. SendTerminationAndTerminate (eNTCP2IncorrectSParameter);
  648. return;
  649. }
  650. i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, buf.data () + 3, size)); // TODO: should insert ri and not parse it twice
  651. // TODO: process options
  652. // ready to communicate
  653. auto existing = i2p::data::netdb.FindRouter (ri.GetRouterIdentity ()->GetIdentHash ()); // check if exists already
  654. SetRemoteIdentity (existing ? existing->GetRouterIdentity () : ri.GetRouterIdentity ());
  655. m_Server.AddNTCP2Session (shared_from_this ());
  656. Established ();
  657. ReceiveLength ();
  658. }
  659. else
  660. Terminate ();
  661. }
  662. else
  663. Terminate ();
  664. }
  665. }
  666. void NTCP2Session::SetSipKeys (const uint8_t * sendSipKey, const uint8_t * receiveSipKey)
  667. {
  668. #if OPENSSL_SIPHASH
  669. m_SendSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, sendSipKey, 16);
  670. m_SendMDCtx = EVP_MD_CTX_create ();
  671. EVP_PKEY_CTX *ctx = nullptr;
  672. EVP_DigestSignInit (m_SendMDCtx, &ctx, nullptr, nullptr, m_SendSipKey);
  673. EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr);
  674. m_ReceiveSipKey = EVP_PKEY_new_raw_private_key (EVP_PKEY_SIPHASH, nullptr, receiveSipKey, 16);
  675. m_ReceiveMDCtx = EVP_MD_CTX_create ();
  676. ctx = nullptr;
  677. EVP_DigestSignInit (m_ReceiveMDCtx, &ctx, NULL, NULL, m_ReceiveSipKey);
  678. EVP_PKEY_CTX_ctrl (ctx, -1, EVP_PKEY_OP_SIGNCTX, EVP_PKEY_CTRL_SET_DIGEST_SIZE, 8, nullptr);
  679. #else
  680. m_SendSipKey = sendSipKey;
  681. m_ReceiveSipKey = receiveSipKey;
  682. #endif
  683. }
  684. void NTCP2Session::ClientLogin ()
  685. {
  686. m_Establisher->CreateEphemeralKey ();
  687. SendSessionRequest ();
  688. }
  689. void NTCP2Session::ServerLogin ()
  690. {
  691. m_Establisher->CreateEphemeralKey ();
  692. m_Establisher->m_SessionRequestBuffer = new uint8_t[287]; // 287 bytes max for now
  693. boost::asio::async_read (m_Socket, boost::asio::buffer(m_Establisher->m_SessionRequestBuffer, 64), boost::asio::transfer_all (),
  694. std::bind(&NTCP2Session::HandleSessionRequestReceived, shared_from_this (),
  695. std::placeholders::_1, std::placeholders::_2));
  696. }
  697. void NTCP2Session::ReceiveLength ()
  698. {
  699. if (IsTerminated ()) return;
  700. boost::asio::async_read (m_Socket, boost::asio::buffer(&m_NextReceivedLen, 2), boost::asio::transfer_all (),
  701. std::bind(&NTCP2Session::HandleReceivedLength, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  702. }
  703. void NTCP2Session::HandleReceivedLength (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  704. {
  705. if (ecode)
  706. {
  707. if (ecode != boost::asio::error::operation_aborted)
  708. LogPrint (eLogWarning, "NTCP2: receive length read error: ", ecode.message ());
  709. Terminate ();
  710. }
  711. else
  712. {
  713. #if OPENSSL_SIPHASH
  714. EVP_DigestSignInit (m_ReceiveMDCtx, nullptr, nullptr, nullptr, nullptr);
  715. EVP_DigestSignUpdate (m_ReceiveMDCtx, m_ReceiveIV.buf, 8);
  716. size_t l = 8;
  717. EVP_DigestSignFinal (m_ReceiveMDCtx, m_ReceiveIV.buf, &l);
  718. #else
  719. i2p::crypto::Siphash<8> (m_ReceiveIV.buf, m_ReceiveIV.buf, 8, m_ReceiveSipKey);
  720. #endif
  721. // m_NextReceivedLen comes from the network in BigEndian
  722. m_NextReceivedLen = be16toh (m_NextReceivedLen) ^ le16toh (m_ReceiveIV.key);
  723. LogPrint (eLogDebug, "NTCP2: received length ", m_NextReceivedLen);
  724. if (m_NextReceivedLen >= 16)
  725. {
  726. if (m_NextReceivedBuffer) delete[] m_NextReceivedBuffer;
  727. m_NextReceivedBuffer = new uint8_t[m_NextReceivedLen];
  728. boost::system::error_code ec;
  729. size_t moreBytes = m_Socket.available(ec);
  730. if (!ec && moreBytes >= m_NextReceivedLen)
  731. {
  732. // read and process message immediately if available
  733. moreBytes = boost::asio::read (m_Socket, boost::asio::buffer(m_NextReceivedBuffer, m_NextReceivedLen), boost::asio::transfer_all (), ec);
  734. HandleReceived (ec, moreBytes);
  735. }
  736. else
  737. Receive ();
  738. }
  739. else
  740. {
  741. LogPrint (eLogError, "NTCP2: received length ", m_NextReceivedLen, " is too short");
  742. Terminate ();
  743. }
  744. }
  745. }
  746. void NTCP2Session::Receive ()
  747. {
  748. if (IsTerminated ()) return;
  749. boost::asio::async_read (m_Socket, boost::asio::buffer(m_NextReceivedBuffer, m_NextReceivedLen), boost::asio::transfer_all (),
  750. std::bind(&NTCP2Session::HandleReceived, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  751. }
  752. void NTCP2Session::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  753. {
  754. if (ecode)
  755. {
  756. if (ecode != boost::asio::error::operation_aborted)
  757. LogPrint (eLogWarning, "NTCP2: receive read error: ", ecode.message ());
  758. Terminate ();
  759. }
  760. else
  761. {
  762. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  763. m_NumReceivedBytes += bytes_transferred + 2; // + length
  764. i2p::transport::transports.UpdateReceivedBytes (bytes_transferred);
  765. uint8_t nonce[12];
  766. CreateNonce (m_ReceiveSequenceNumber, nonce); m_ReceiveSequenceNumber++;
  767. if (i2p::crypto::AEADChaCha20Poly1305 (m_NextReceivedBuffer, m_NextReceivedLen-16, nullptr, 0, m_ReceiveKey, nonce, m_NextReceivedBuffer, m_NextReceivedLen, false))
  768. {
  769. LogPrint (eLogDebug, "NTCP2: received message decrypted");
  770. ProcessNextFrame (m_NextReceivedBuffer, m_NextReceivedLen-16);
  771. delete[] m_NextReceivedBuffer; m_NextReceivedBuffer = nullptr; // we don't need received buffer anymore
  772. ReceiveLength ();
  773. }
  774. else
  775. {
  776. LogPrint (eLogWarning, "NTCP2: Received AEAD verification failed ");
  777. SendTerminationAndTerminate (eNTCP2DataPhaseAEADFailure);
  778. }
  779. }
  780. }
  781. void NTCP2Session::ProcessNextFrame (const uint8_t * frame, size_t len)
  782. {
  783. size_t offset = 0;
  784. while (offset < len)
  785. {
  786. uint8_t blk = frame[offset];
  787. offset++;
  788. auto size = bufbe16toh (frame + offset);
  789. offset += 2;
  790. LogPrint (eLogDebug, "NTCP2: Block type ", (int)blk, " of size ", size);
  791. if (size > len)
  792. {
  793. LogPrint (eLogError, "NTCP2: Unexpected block length ", size);
  794. break;
  795. }
  796. switch (blk)
  797. {
  798. case eNTCP2BlkDateTime:
  799. LogPrint (eLogDebug, "NTCP2: datetime");
  800. break;
  801. case eNTCP2BlkOptions:
  802. LogPrint (eLogDebug, "NTCP2: options");
  803. break;
  804. case eNTCP2BlkRouterInfo:
  805. {
  806. LogPrint (eLogDebug, "NTCP2: RouterInfo flag=", (int)frame[offset]);
  807. i2p::data::netdb.PostI2NPMsg (CreateI2NPMessage (eI2NPDummyMsg, frame + offset, size));
  808. break;
  809. }
  810. case eNTCP2BlkI2NPMessage:
  811. {
  812. LogPrint (eLogDebug, "NTCP2: I2NP");
  813. if (size > I2NP_MAX_MESSAGE_SIZE)
  814. {
  815. LogPrint (eLogError, "NTCP2: I2NP block is too long ", size);
  816. break;
  817. }
  818. auto nextMsg = NewI2NPMessage (size);
  819. nextMsg->Align (12); // for possible tunnel msg
  820. nextMsg->len = nextMsg->offset + size + 7; // 7 more bytes for full I2NP header
  821. memcpy (nextMsg->GetNTCP2Header (), frame + offset, size);
  822. nextMsg->FromNTCP2 ();
  823. m_Handler.PutNextMessage (nextMsg);
  824. break;
  825. }
  826. case eNTCP2BlkTermination:
  827. if (size >= 9)
  828. {
  829. LogPrint (eLogDebug, "NTCP2: termination. reason=", (int)(frame[offset + 8]));
  830. Terminate ();
  831. }
  832. else
  833. LogPrint (eLogWarning, "NTCP2: Unexpected termination block size ", size);
  834. break;
  835. case eNTCP2BlkPadding:
  836. LogPrint (eLogDebug, "NTCP2: padding");
  837. break;
  838. default:
  839. LogPrint (eLogWarning, "NTCP2: Unknown block type ", (int)blk);
  840. }
  841. offset += size;
  842. }
  843. m_Handler.Flush ();
  844. }
  845. void NTCP2Session::SetNextSentFrameLength (size_t frameLen, uint8_t * lengthBuf)
  846. {
  847. #if OPENSSL_SIPHASH
  848. EVP_DigestSignInit (m_SendMDCtx, nullptr, nullptr, nullptr, nullptr);
  849. EVP_DigestSignUpdate (m_SendMDCtx, m_SendIV.buf, 8);
  850. size_t l = 8;
  851. EVP_DigestSignFinal (m_SendMDCtx, m_SendIV.buf, &l);
  852. #else
  853. i2p::crypto::Siphash<8> (m_SendIV.buf, m_SendIV.buf, 8, m_SendSipKey);
  854. #endif
  855. // length must be in BigEndian
  856. htobe16buf (lengthBuf, frameLen ^ le16toh (m_SendIV.key));
  857. LogPrint (eLogDebug, "NTCP2: sent length ", frameLen);
  858. }
  859. void NTCP2Session::SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs)
  860. {
  861. if (msgs.empty () || IsTerminated ()) return;
  862. size_t totalLen = 0;
  863. std::vector<std::pair<uint8_t *, size_t> > encryptBufs;
  864. std::vector<boost::asio::const_buffer> bufs;
  865. std::shared_ptr<I2NPMessage> first;
  866. uint8_t * macBuf = nullptr;
  867. for (auto& it: msgs)
  868. {
  869. it->ToNTCP2 ();
  870. auto buf = it->GetNTCP2Header ();
  871. auto len = it->GetNTCP2Length ();
  872. // block header
  873. buf -= 3;
  874. buf[0] = eNTCP2BlkI2NPMessage; // blk
  875. htobe16buf (buf + 1, len); // size
  876. len += 3;
  877. totalLen += len;
  878. encryptBufs.push_back ( {buf, len} );
  879. if (&it == &msgs.front ()) // first message
  880. {
  881. // allocate two bytes for length
  882. buf -= 2; len += 2;
  883. first = it;
  884. }
  885. if (&it == &msgs.back () && it->len + 16 < it->maxLen) // last message
  886. {
  887. // if it's long enough we add padding and MAC to it
  888. // create padding block
  889. auto paddingLen = CreatePaddingBlock (totalLen, buf + len, it->maxLen - it->len - 16);
  890. if (paddingLen)
  891. {
  892. encryptBufs.push_back ( {buf + len, paddingLen} );
  893. len += paddingLen;
  894. totalLen += paddingLen;
  895. }
  896. macBuf = buf + len;
  897. // allocate 16 bytes for MAC
  898. len += 16;
  899. }
  900. bufs.push_back (boost::asio::buffer (buf, len));
  901. }
  902. if (!macBuf) // last block was not enough for MAC
  903. {
  904. // allocate send buffer
  905. m_NextSendBuffer = new uint8_t[287]; // can be any size > 16, we just allocate 287 frequently
  906. // crate padding block
  907. auto paddingLen = CreatePaddingBlock (totalLen, m_NextSendBuffer, 287 - 16);
  908. // and padding block to encrypt and send
  909. if (paddingLen)
  910. encryptBufs.push_back ( {m_NextSendBuffer, paddingLen} );
  911. bufs.push_back (boost::asio::buffer (m_NextSendBuffer, paddingLen + 16));
  912. macBuf = m_NextSendBuffer + paddingLen;
  913. totalLen += paddingLen;
  914. }
  915. uint8_t nonce[12];
  916. CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
  917. i2p::crypto::AEADChaCha20Poly1305Encrypt (encryptBufs, m_SendKey, nonce, macBuf); // encrypt buffers
  918. SetNextSentFrameLength (totalLen + 16, first->GetNTCP2Header () - 5); // frame length right before first block
  919. // send buffers
  920. m_IsSending = true;
  921. boost::asio::async_write (m_Socket, bufs, boost::asio::transfer_all (),
  922. std::bind(&NTCP2Session::HandleI2NPMsgsSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msgs));
  923. }
  924. void NTCP2Session::HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs)
  925. {
  926. HandleNextFrameSent (ecode, bytes_transferred);
  927. // msgs get destroyed here
  928. }
  929. void NTCP2Session::EncryptAndSendNextBuffer (size_t payloadLen)
  930. {
  931. if (IsTerminated ())
  932. {
  933. delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;
  934. return;
  935. }
  936. // encrypt
  937. uint8_t nonce[12];
  938. CreateNonce (m_SendSequenceNumber, nonce); m_SendSequenceNumber++;
  939. i2p::crypto::AEADChaCha20Poly1305Encrypt ({ {m_NextSendBuffer + 2, payloadLen} }, m_SendKey, nonce, m_NextSendBuffer + payloadLen + 2);
  940. SetNextSentFrameLength (payloadLen + 16, m_NextSendBuffer);
  941. // send
  942. m_IsSending = true;
  943. boost::asio::async_write (m_Socket, boost::asio::buffer (m_NextSendBuffer, payloadLen + 16 + 2), boost::asio::transfer_all (),
  944. std::bind(&NTCP2Session::HandleNextFrameSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  945. }
  946. void NTCP2Session::HandleNextFrameSent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  947. {
  948. m_IsSending = false;
  949. delete[] m_NextSendBuffer; m_NextSendBuffer = nullptr;
  950. if (ecode)
  951. {
  952. LogPrint (eLogWarning, "NTCP2: Couldn't send frame ", ecode.message ());
  953. }
  954. else
  955. {
  956. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  957. m_NumSentBytes += bytes_transferred;
  958. i2p::transport::transports.UpdateSentBytes (bytes_transferred);
  959. LogPrint (eLogDebug, "NTCP2: Next frame sent ", bytes_transferred);
  960. SendQueue ();
  961. }
  962. }
  963. void NTCP2Session::SendQueue ()
  964. {
  965. if (!m_SendQueue.empty ())
  966. {
  967. std::vector<std::shared_ptr<I2NPMessage> > msgs;
  968. size_t s = 0;
  969. while (!m_SendQueue.empty ())
  970. {
  971. auto msg = m_SendQueue.front ();
  972. size_t len = msg->GetNTCP2Length ();
  973. if (s + len + 3 <= NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) // 3 bytes block header
  974. {
  975. msgs.push_back (msg);
  976. s += (len + 3);
  977. m_SendQueue.pop_front ();
  978. }
  979. else if (len + 3 > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE)
  980. {
  981. LogPrint (eLogError, "NTCP2: I2NP message of size ", len, " can't be sent. Dropped");
  982. m_SendQueue.pop_front ();
  983. }
  984. else
  985. break;
  986. }
  987. SendI2NPMsgs (msgs);
  988. }
  989. }
  990. size_t NTCP2Session::CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len)
  991. {
  992. if (len < 3) return 0;
  993. len -= 3;
  994. if (msgLen < 256) msgLen = 256; // for short message padding should not be always zero
  995. size_t paddingSize = (msgLen*NTCP2_MAX_PADDING_RATIO)/100;
  996. if (msgLen + paddingSize + 3 > NTCP2_UNENCRYPTED_FRAME_MAX_SIZE) paddingSize = NTCP2_UNENCRYPTED_FRAME_MAX_SIZE - msgLen -3;
  997. if (paddingSize > len) paddingSize = len;
  998. if (paddingSize) paddingSize = rand () % paddingSize;
  999. buf[0] = eNTCP2BlkPadding; // blk
  1000. htobe16buf (buf + 1, paddingSize); // size
  1001. memset (buf + 3, 0, paddingSize);
  1002. return paddingSize + 3;
  1003. }
  1004. void NTCP2Session::SendRouterInfo ()
  1005. {
  1006. if (!IsEstablished ()) return;
  1007. auto riLen = i2p::context.GetRouterInfo ().GetBufferLen ();
  1008. size_t payloadLen = riLen + 4; // 3 bytes block header + 1 byte RI flag
  1009. m_NextSendBuffer = new uint8_t[payloadLen + 16 + 2 + 64]; // up to 64 bytes padding
  1010. m_NextSendBuffer[2] = eNTCP2BlkRouterInfo;
  1011. htobe16buf (m_NextSendBuffer + 3, riLen + 1); // size
  1012. m_NextSendBuffer[5] = 0; // flag
  1013. memcpy (m_NextSendBuffer + 6, i2p::context.GetRouterInfo ().GetBuffer (), riLen);
  1014. // padding block
  1015. auto paddingSize = CreatePaddingBlock (payloadLen, m_NextSendBuffer + 2 + payloadLen, 64);
  1016. payloadLen += paddingSize;
  1017. // encrypt and send
  1018. EncryptAndSendNextBuffer (payloadLen);
  1019. }
  1020. void NTCP2Session::SendTermination (NTCP2TerminationReason reason)
  1021. {
  1022. if (!m_SendKey || !m_SendSipKey) return;
  1023. m_NextSendBuffer = new uint8_t[49]; // 49 = 12 bytes message + 16 bytes MAC + 2 bytes size + up to 19 padding block
  1024. // termination block
  1025. m_NextSendBuffer[2] = eNTCP2BlkTermination;
  1026. m_NextSendBuffer[3] = 0; m_NextSendBuffer[4] = 9; // 9 bytes block size
  1027. htobe64buf (m_NextSendBuffer + 5, m_ReceiveSequenceNumber);
  1028. m_NextSendBuffer[13] = (uint8_t)reason;
  1029. // padding block
  1030. auto paddingSize = CreatePaddingBlock (12, m_NextSendBuffer + 14, 19);
  1031. // encrypt and send
  1032. EncryptAndSendNextBuffer (paddingSize + 12);
  1033. }
  1034. void NTCP2Session::SendTerminationAndTerminate (NTCP2TerminationReason reason)
  1035. {
  1036. SendTermination (reason);
  1037. m_Server.GetService ().post (std::bind (&NTCP2Session::Terminate, shared_from_this ())); // let termination message go
  1038. }
  1039. void NTCP2Session::SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs)
  1040. {
  1041. m_Server.GetService ().post (std::bind (&NTCP2Session::PostI2NPMessages, shared_from_this (), msgs));
  1042. }
  1043. void NTCP2Session::PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs)
  1044. {
  1045. if (m_IsTerminated) return;
  1046. for (auto it: msgs)
  1047. m_SendQueue.push_back (it);
  1048. if (!m_IsSending)
  1049. SendQueue ();
  1050. else if (m_SendQueue.size () > NTCP2_MAX_OUTGOING_QUEUE_SIZE)
  1051. {
  1052. LogPrint (eLogWarning, "NTCP2: outgoing messages queue size exceeds ", NTCP2_MAX_OUTGOING_QUEUE_SIZE);
  1053. Terminate ();
  1054. }
  1055. }
  1056. void NTCP2Session::SendLocalRouterInfo ()
  1057. {
  1058. if (!IsOutgoing ()) // we send it in SessionConfirmed
  1059. m_Server.GetService ().post (std::bind (&NTCP2Session::SendRouterInfo, shared_from_this ()));
  1060. }
  1061. NTCP2Server::NTCP2Server ():
  1062. m_IsRunning (false), m_Thread (nullptr), m_Work (m_Service),
  1063. m_TerminationTimer (m_Service)
  1064. {
  1065. }
  1066. NTCP2Server::~NTCP2Server ()
  1067. {
  1068. Stop ();
  1069. }
  1070. void NTCP2Server::Start ()
  1071. {
  1072. if (!m_IsRunning)
  1073. {
  1074. m_IsRunning = true;
  1075. m_Thread = new std::thread (std::bind (&NTCP2Server::Run, this));
  1076. auto& addresses = context.GetRouterInfo ().GetAddresses ();
  1077. for (const auto& address: addresses)
  1078. {
  1079. if (!address) continue;
  1080. if (address->IsPublishedNTCP2 ())
  1081. {
  1082. if (address->host.is_v4())
  1083. {
  1084. try
  1085. {
  1086. m_NTCP2Acceptor.reset (new boost::asio::ip::tcp::acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), address->port)));
  1087. }
  1088. catch ( std::exception & ex )
  1089. {
  1090. LogPrint(eLogError, "NTCP2: Failed to bind to ip4 port ",address->port, ex.what());
  1091. continue;
  1092. }
  1093. LogPrint (eLogInfo, "NTCP2: Start listening TCP port ", address->port);
  1094. auto conn = std::make_shared<NTCP2Session>(*this);
  1095. m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this, conn, std::placeholders::_1));
  1096. }
  1097. else if (address->host.is_v6() && context.SupportsV6 ())
  1098. {
  1099. m_NTCP2V6Acceptor.reset (new boost::asio::ip::tcp::acceptor (m_Service));
  1100. try
  1101. {
  1102. m_NTCP2V6Acceptor->open (boost::asio::ip::tcp::v6());
  1103. m_NTCP2V6Acceptor->set_option (boost::asio::ip::v6_only (true));
  1104. m_NTCP2V6Acceptor->set_option (boost::asio::socket_base::reuse_address (true));
  1105. m_NTCP2V6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port));
  1106. m_NTCP2V6Acceptor->listen ();
  1107. LogPrint (eLogInfo, "NTCP2: Start listening V6 TCP port ", address->port);
  1108. auto conn = std::make_shared<NTCP2Session> (*this);
  1109. m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this, conn, std::placeholders::_1));
  1110. } catch ( std::exception & ex ) {
  1111. LogPrint(eLogError, "NTCP2: failed to bind to ip6 port ", address->port);
  1112. continue;
  1113. }
  1114. }
  1115. }
  1116. }
  1117. ScheduleTermination ();
  1118. }
  1119. }
  1120. void NTCP2Server::Stop ()
  1121. {
  1122. {
  1123. // we have to copy it because Terminate changes m_NTCP2Sessions
  1124. auto ntcpSessions = m_NTCP2Sessions;
  1125. for (auto& it: ntcpSessions)
  1126. it.second->Terminate ();
  1127. for (auto& it: m_PendingIncomingSessions)
  1128. it->Terminate ();
  1129. }
  1130. m_NTCP2Sessions.clear ();
  1131. if (m_IsRunning)
  1132. {
  1133. m_IsRunning = false;
  1134. m_TerminationTimer.cancel ();
  1135. m_Service.stop ();
  1136. if (m_Thread)
  1137. {
  1138. m_Thread->join ();
  1139. delete m_Thread;
  1140. m_Thread = nullptr;
  1141. }
  1142. }
  1143. }
  1144. void NTCP2Server::Run ()
  1145. {
  1146. while (m_IsRunning)
  1147. {
  1148. try
  1149. {
  1150. m_Service.run ();
  1151. }
  1152. catch (std::exception& ex)
  1153. {
  1154. LogPrint (eLogError, "NTCP2: runtime exception: ", ex.what ());
  1155. }
  1156. }
  1157. }
  1158. bool NTCP2Server::AddNTCP2Session (std::shared_ptr<NTCP2Session> session)
  1159. {
  1160. if (!session || !session->GetRemoteIdentity ()) return false;
  1161. auto& ident = session->GetRemoteIdentity ()->GetIdentHash ();
  1162. auto it = m_NTCP2Sessions.find (ident);
  1163. if (it != m_NTCP2Sessions.end ())
  1164. {
  1165. LogPrint (eLogWarning, "NTCP2: session to ", ident.ToBase64 (), " already exists");
  1166. session->Terminate();
  1167. return false;
  1168. }
  1169. m_NTCP2Sessions.insert (std::make_pair (ident, session));
  1170. return true;
  1171. }
  1172. void NTCP2Server::RemoveNTCP2Session (std::shared_ptr<NTCP2Session> session)
  1173. {
  1174. if (session && session->GetRemoteIdentity ())
  1175. m_NTCP2Sessions.erase (session->GetRemoteIdentity ()->GetIdentHash ());
  1176. }
  1177. std::shared_ptr<NTCP2Session> NTCP2Server::FindNTCP2Session (const i2p::data::IdentHash& ident)
  1178. {
  1179. auto it = m_NTCP2Sessions.find (ident);
  1180. if (it != m_NTCP2Sessions.end ())
  1181. return it->second;
  1182. return nullptr;
  1183. }
  1184. void NTCP2Server::Connect(const boost::asio::ip::address & address, uint16_t port, std::shared_ptr<NTCP2Session> conn)
  1185. {
  1186. LogPrint (eLogDebug, "NTCP2: Connecting to ", address ,":", port);
  1187. m_Service.post([this, address, port, conn]()
  1188. {
  1189. if (this->AddNTCP2Session (conn))
  1190. {
  1191. auto timer = std::make_shared<boost::asio::deadline_timer>(m_Service);
  1192. auto timeout = NTCP2_CONNECT_TIMEOUT * 5;
  1193. conn->SetTerminationTimeout(timeout * 2);
  1194. timer->expires_from_now (boost::posix_time::seconds(timeout));
  1195. timer->async_wait ([conn, timeout](const boost::system::error_code& ecode)
  1196. {
  1197. if (ecode != boost::asio::error::operation_aborted)
  1198. {
  1199. LogPrint (eLogInfo, "NTCP2: Not connected in ", timeout, " seconds");
  1200. //i2p::data::netdb.SetUnreachable (conn->GetRemoteIdentity ()->GetIdentHash (), true);
  1201. conn->Terminate ();
  1202. }
  1203. });
  1204. conn->GetSocket ().async_connect (boost::asio::ip::tcp::endpoint (address, port), std::bind (&NTCP2Server::HandleConnect, this, std::placeholders::_1, conn, timer));
  1205. }
  1206. });
  1207. }
  1208. void NTCP2Server::HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer)
  1209. {
  1210. timer->cancel ();
  1211. if (ecode)
  1212. {
  1213. LogPrint (eLogInfo, "NTCP2: Connect error ", ecode.message ());
  1214. conn->Terminate ();
  1215. }
  1216. else
  1217. {
  1218. LogPrint (eLogDebug, "NTCP2: Connected to ", conn->GetSocket ().remote_endpoint ());
  1219. conn->ClientLogin ();
  1220. }
  1221. }
  1222. void NTCP2Server::HandleAccept (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error)
  1223. {
  1224. if (!error)
  1225. {
  1226. boost::system::error_code ec;
  1227. auto ep = conn->GetSocket ().remote_endpoint(ec);
  1228. if (!ec)
  1229. {
  1230. LogPrint (eLogDebug, "NTCP2: Connected from ", ep);
  1231. if (conn)
  1232. {
  1233. conn->ServerLogin ();
  1234. m_PendingIncomingSessions.push_back (conn);
  1235. }
  1236. }
  1237. else
  1238. LogPrint (eLogError, "NTCP2: Connected from error ", ec.message ());
  1239. }
  1240. if (error != boost::asio::error::operation_aborted)
  1241. {
  1242. conn = std::make_shared<NTCP2Session> (*this);
  1243. m_NTCP2Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAccept, this,
  1244. conn, std::placeholders::_1));
  1245. }
  1246. }
  1247. void NTCP2Server::HandleAcceptV6 (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error)
  1248. {
  1249. if (!error)
  1250. {
  1251. boost::system::error_code ec;
  1252. auto ep = conn->GetSocket ().remote_endpoint(ec);
  1253. if (!ec)
  1254. {
  1255. LogPrint (eLogDebug, "NTCP2: Connected from ", ep);
  1256. if (conn)
  1257. {
  1258. conn->ServerLogin ();
  1259. m_PendingIncomingSessions.push_back (conn);
  1260. }
  1261. }
  1262. else
  1263. LogPrint (eLogError, "NTCP2: Connected from error ", ec.message ());
  1264. }
  1265. if (error != boost::asio::error::operation_aborted)
  1266. {
  1267. conn = std::make_shared<NTCP2Session> (*this);
  1268. m_NTCP2V6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCP2Server::HandleAcceptV6, this,
  1269. conn, std::placeholders::_1));
  1270. }
  1271. }
  1272. void NTCP2Server::ScheduleTermination ()
  1273. {
  1274. m_TerminationTimer.expires_from_now (boost::posix_time::seconds(NTCP2_TERMINATION_CHECK_TIMEOUT));
  1275. m_TerminationTimer.async_wait (std::bind (&NTCP2Server::HandleTerminationTimer,
  1276. this, std::placeholders::_1));
  1277. }
  1278. void NTCP2Server::HandleTerminationTimer (const boost::system::error_code& ecode)
  1279. {
  1280. if (ecode != boost::asio::error::operation_aborted)
  1281. {
  1282. auto ts = i2p::util::GetSecondsSinceEpoch ();
  1283. // established
  1284. for (auto& it: m_NTCP2Sessions)
  1285. if (it.second->IsTerminationTimeoutExpired (ts))
  1286. {
  1287. auto session = it.second;
  1288. LogPrint (eLogDebug, "NTCP2: No activity for ", session->GetTerminationTimeout (), " seconds");
  1289. session->TerminateByTimeout (); // it doesn't change m_NTCP2Session right a way
  1290. }
  1291. // pending
  1292. for (auto it = m_PendingIncomingSessions.begin (); it != m_PendingIncomingSessions.end ();)
  1293. {
  1294. if ((*it)->IsEstablished () || (*it)->IsTerminated ())
  1295. it = m_PendingIncomingSessions.erase (it); // established or terminated
  1296. else if ((*it)->IsTerminationTimeoutExpired (ts))
  1297. {
  1298. (*it)->Terminate ();
  1299. it = m_PendingIncomingSessions.erase (it); // expired
  1300. }
  1301. else
  1302. it++;
  1303. }
  1304. ScheduleTermination ();
  1305. }
  1306. }
  1307. }
  1308. }