SSUSession.cpp 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206
  1. #include <boost/bind.hpp>
  2. #include "Crypto.h"
  3. #include "Log.h"
  4. #include "Timestamp.h"
  5. #include "RouterContext.h"
  6. #include "Transports.h"
  7. #include "NetDb.hpp"
  8. #include "SSU.h"
  9. #include "SSUSession.h"
  10. namespace i2p
  11. {
  12. namespace transport
  13. {
  14. SSUSession::SSUSession (SSUServer& server, boost::asio::ip::udp::endpoint& remoteEndpoint,
  15. std::shared_ptr<const i2p::data::RouterInfo> router, bool peerTest ):
  16. TransportSession (router, SSU_TERMINATION_TIMEOUT),
  17. m_Server (server), m_RemoteEndpoint (remoteEndpoint), m_ConnectTimer (GetService ()),
  18. m_IsPeerTest (peerTest),m_State (eSessionStateUnknown), m_IsSessionKey (false),
  19. m_RelayTag (0), m_SentRelayTag (0), m_Data (*this), m_IsDataReceived (false)
  20. {
  21. if (router)
  22. {
  23. // we are client
  24. auto address = router->GetSSUAddress (false);
  25. if (address) m_IntroKey = address->ssu->key;
  26. m_Data.AdjustPacketSize (router); // mtu
  27. }
  28. else
  29. {
  30. // we are server
  31. auto address = i2p::context.GetRouterInfo ().GetSSUAddress (false);
  32. if (address) m_IntroKey = address->ssu->key;
  33. }
  34. m_CreationTime = i2p::util::GetSecondsSinceEpoch ();
  35. }
  36. SSUSession::~SSUSession ()
  37. {
  38. }
  39. boost::asio::io_service& SSUSession::GetService ()
  40. {
  41. return IsV6 () ? m_Server.GetServiceV6 () : m_Server.GetService ();
  42. }
  43. void SSUSession::CreateAESandMacKey (const uint8_t * pubKey)
  44. {
  45. uint8_t sharedKey[256];
  46. m_DHKeysPair->Agree (pubKey, sharedKey);
  47. uint8_t * sessionKey = m_SessionKey, * macKey = m_MacKey;
  48. if (sharedKey[0] & 0x80)
  49. {
  50. sessionKey[0] = 0;
  51. memcpy (sessionKey + 1, sharedKey, 31);
  52. memcpy (macKey, sharedKey + 31, 32);
  53. }
  54. else if (sharedKey[0])
  55. {
  56. memcpy (sessionKey, sharedKey, 32);
  57. memcpy (macKey, sharedKey + 32, 32);
  58. }
  59. else
  60. {
  61. // find first non-zero byte
  62. uint8_t * nonZero = sharedKey + 1;
  63. while (!*nonZero)
  64. {
  65. nonZero++;
  66. if (nonZero - sharedKey > 32)
  67. {
  68. LogPrint (eLogWarning, "SSU: first 32 bytes of shared key is all zeros. Ignored");
  69. return;
  70. }
  71. }
  72. memcpy (sessionKey, nonZero, 32);
  73. SHA256(nonZero, 64 - (nonZero - sharedKey), macKey);
  74. }
  75. m_IsSessionKey = true;
  76. m_SessionKeyEncryption.SetKey (m_SessionKey);
  77. m_SessionKeyDecryption.SetKey (m_SessionKey);
  78. }
  79. void SSUSession::ProcessNextMessage (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
  80. {
  81. m_NumReceivedBytes += len;
  82. i2p::transport::transports.UpdateReceivedBytes (len);
  83. if (m_State == eSessionStateIntroduced)
  84. {
  85. // HolePunch received
  86. LogPrint (eLogDebug, "SSU: HolePunch of ", len, " bytes received");
  87. m_State = eSessionStateUnknown;
  88. Connect ();
  89. }
  90. else
  91. {
  92. if (!len) return; // ignore zero-length packets
  93. if (m_State == eSessionStateEstablished)
  94. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  95. if (m_IsSessionKey && Validate (buf, len, m_MacKey)) // try session key first
  96. DecryptSessionKey (buf, len);
  97. else
  98. {
  99. if (m_State == eSessionStateEstablished) Reset (); // new session key required
  100. // try intro key depending on side
  101. if (Validate (buf, len, m_IntroKey))
  102. Decrypt (buf, len, m_IntroKey);
  103. else
  104. {
  105. // try own intro key
  106. auto address = i2p::context.GetRouterInfo ().GetSSUAddress (false);
  107. if (!address)
  108. {
  109. LogPrint (eLogInfo, "SSU is not supported");
  110. return;
  111. }
  112. if (Validate (buf, len, address->ssu->key))
  113. Decrypt (buf, len, address->ssu->key);
  114. else
  115. {
  116. LogPrint (eLogWarning, "SSU: MAC verification failed ", len, " bytes from ", senderEndpoint);
  117. m_Server.DeleteSession (shared_from_this ());
  118. return;
  119. }
  120. }
  121. }
  122. // successfully decrypted
  123. ProcessMessage (buf, len, senderEndpoint);
  124. }
  125. }
  126. size_t SSUSession::GetSSUHeaderSize (const uint8_t * buf) const
  127. {
  128. size_t s = sizeof (SSUHeader);
  129. if (((const SSUHeader *)buf)->IsExtendedOptions ())
  130. s += buf[s] + 1; // byte right after header is extended options length
  131. return s;
  132. }
  133. void SSUSession::ProcessMessage (uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
  134. {
  135. len -= (len & 0x0F); // %16, delete extra padding
  136. if (len <= sizeof (SSUHeader)) return; // drop empty message
  137. //TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
  138. auto headerSize = GetSSUHeaderSize (buf);
  139. if (headerSize >= len)
  140. {
  141. LogPrint (eLogError, "SSU header size ", headerSize, " exceeds packet length ", len);
  142. return;
  143. }
  144. SSUHeader * header = (SSUHeader *)buf;
  145. switch (header->GetPayloadType ())
  146. {
  147. case PAYLOAD_TYPE_DATA:
  148. ProcessData (buf + headerSize, len - headerSize);
  149. break;
  150. case PAYLOAD_TYPE_SESSION_REQUEST:
  151. ProcessSessionRequest (buf, len); // buf with header
  152. break;
  153. case PAYLOAD_TYPE_SESSION_CREATED:
  154. ProcessSessionCreated (buf, len); // buf with header
  155. break;
  156. case PAYLOAD_TYPE_SESSION_CONFIRMED:
  157. ProcessSessionConfirmed (buf, len); // buf with header
  158. break;
  159. case PAYLOAD_TYPE_PEER_TEST:
  160. LogPrint (eLogDebug, "SSU: peer test received");
  161. ProcessPeerTest (buf + headerSize, len - headerSize, senderEndpoint);
  162. break;
  163. case PAYLOAD_TYPE_SESSION_DESTROYED:
  164. {
  165. LogPrint (eLogDebug, "SSU: session destroy received");
  166. m_Server.DeleteSession (shared_from_this ());
  167. break;
  168. }
  169. case PAYLOAD_TYPE_RELAY_RESPONSE:
  170. ProcessRelayResponse (buf + headerSize, len - headerSize);
  171. if (m_State != eSessionStateEstablished)
  172. m_Server.DeleteSession (shared_from_this ());
  173. break;
  174. case PAYLOAD_TYPE_RELAY_REQUEST:
  175. LogPrint (eLogDebug, "SSU: relay request received");
  176. ProcessRelayRequest (buf + headerSize, len - headerSize, senderEndpoint);
  177. break;
  178. case PAYLOAD_TYPE_RELAY_INTRO:
  179. LogPrint (eLogDebug, "SSU: relay intro received");
  180. ProcessRelayIntro (buf + headerSize, len - headerSize);
  181. break;
  182. default:
  183. LogPrint (eLogWarning, "SSU: Unexpected payload type ", (int)header->GetPayloadType ());
  184. }
  185. }
  186. void SSUSession::ProcessSessionRequest (const uint8_t * buf, size_t len)
  187. {
  188. LogPrint (eLogDebug, "SSU message: session request");
  189. bool sendRelayTag = true;
  190. auto headerSize = sizeof (SSUHeader);
  191. if (((SSUHeader *)buf)->IsExtendedOptions ())
  192. {
  193. uint8_t extendedOptionsLen = buf[headerSize];
  194. headerSize++;
  195. if (extendedOptionsLen >= 3) // options are presented
  196. {
  197. uint16_t flags = bufbe16toh (buf + headerSize);
  198. sendRelayTag = flags & EXTENDED_OPTIONS_FLAG_REQUEST_RELAY_TAG;
  199. }
  200. headerSize += extendedOptionsLen;
  201. }
  202. if (headerSize >= len)
  203. {
  204. LogPrint (eLogError, "Session request header size ", headerSize, " exceeds packet length ", len);
  205. return;
  206. }
  207. if (!m_DHKeysPair)
  208. m_DHKeysPair = transports.GetNextDHKeysPair ();
  209. CreateAESandMacKey (buf + headerSize);
  210. SendSessionCreated (buf + headerSize, sendRelayTag);
  211. }
  212. void SSUSession::ProcessSessionCreated (uint8_t * buf, size_t len)
  213. {
  214. if (!IsOutgoing () || !m_DHKeysPair)
  215. {
  216. LogPrint (eLogWarning, "SSU: Unsolicited session created message");
  217. return;
  218. }
  219. LogPrint (eLogDebug, "SSU message: session created");
  220. m_ConnectTimer.cancel (); // connect timer
  221. SignedData s; // x,y, our IP, our port, remote IP, remote port, relayTag, signed on time
  222. auto headerSize = GetSSUHeaderSize (buf);
  223. if (headerSize >= len)
  224. {
  225. LogPrint (eLogError, "Session created header size ", headerSize, " exceeds packet length ", len);
  226. return;
  227. }
  228. uint8_t * payload = buf + headerSize;
  229. uint8_t * y = payload;
  230. CreateAESandMacKey (y);
  231. s.Insert (m_DHKeysPair->GetPublicKey (), 256); // x
  232. s.Insert (y, 256); // y
  233. payload += 256;
  234. uint8_t addressSize = *payload;
  235. payload += 1; // size
  236. uint8_t * ourAddress = payload;
  237. boost::asio::ip::address ourIP;
  238. if (addressSize == 4) // v4
  239. {
  240. boost::asio::ip::address_v4::bytes_type bytes;
  241. memcpy (bytes.data (), ourAddress, 4);
  242. ourIP = boost::asio::ip::address_v4 (bytes);
  243. }
  244. else // v6
  245. {
  246. boost::asio::ip::address_v6::bytes_type bytes;
  247. memcpy (bytes.data (), ourAddress, 16);
  248. ourIP = boost::asio::ip::address_v6 (bytes);
  249. }
  250. s.Insert (ourAddress, addressSize); // our IP
  251. payload += addressSize; // address
  252. uint16_t ourPort = bufbe16toh (payload);
  253. s.Insert (payload, 2); // our port
  254. payload += 2; // port
  255. if (m_RemoteEndpoint.address ().is_v4 ())
  256. s.Insert (m_RemoteEndpoint.address ().to_v4 ().to_bytes ().data (), 4); // remote IP v4
  257. else
  258. s.Insert (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), 16); // remote IP v6
  259. s.Insert<uint16_t> (htobe16 (m_RemoteEndpoint.port ())); // remote port
  260. s.Insert (payload, 8); // relayTag and signed on time
  261. m_RelayTag = bufbe32toh (payload);
  262. payload += 4; // relayTag
  263. if (i2p::context.GetStatus () == eRouterStatusTesting)
  264. {
  265. auto ts = i2p::util::GetSecondsSinceEpoch ();
  266. uint32_t signedOnTime = bufbe32toh(payload);
  267. if (signedOnTime < ts - SSU_CLOCK_SKEW || signedOnTime > ts + SSU_CLOCK_SKEW)
  268. {
  269. LogPrint (eLogError, "SSU: clock skew detected ", (int)ts - signedOnTime, ". Check your clock");
  270. i2p::context.SetError (eRouterErrorClockSkew);
  271. }
  272. }
  273. payload += 4; // signed on time
  274. // decrypt signature
  275. size_t signatureLen = m_RemoteIdentity->GetSignatureLen ();
  276. size_t paddingSize = signatureLen & 0x0F; // %16
  277. if (paddingSize > 0) signatureLen += (16 - paddingSize);
  278. //TODO: since we are accessing a uint8_t this is unlikely to crash due to alignment but should be improved
  279. m_SessionKeyDecryption.SetIV (((SSUHeader *)buf)->iv);
  280. m_SessionKeyDecryption.Decrypt (payload, signatureLen, payload); // TODO: non-const payload
  281. // verify signature
  282. if (s.Verify (m_RemoteIdentity, payload))
  283. {
  284. LogPrint (eLogInfo, "SSU: Our external address is ", ourIP.to_string (), ":", ourPort);
  285. i2p::context.UpdateAddress (ourIP);
  286. SendSessionConfirmed (y, ourAddress, addressSize + 2);
  287. }
  288. else
  289. {
  290. LogPrint (eLogError, "SSU: message 'created' signature verification failed");
  291. Failed ();
  292. }
  293. }
  294. void SSUSession::ProcessSessionConfirmed (const uint8_t * buf, size_t len)
  295. {
  296. LogPrint (eLogDebug, "SSU: Session confirmed received");
  297. auto headerSize = GetSSUHeaderSize (buf);
  298. if (headerSize >= len)
  299. {
  300. LogPrint (eLogError, "SSU: Session confirmed header size ", len, " exceeds packet length ", len);
  301. return;
  302. }
  303. const uint8_t * payload = buf + headerSize;
  304. payload++; // identity fragment info
  305. uint16_t identitySize = bufbe16toh (payload);
  306. payload += 2; // size of identity fragment
  307. auto identity = std::make_shared<i2p::data::IdentityEx> (payload, identitySize);
  308. auto existing = i2p::data::netdb.FindRouter (identity->GetIdentHash ()); // check if exists already
  309. SetRemoteIdentity (existing ? existing->GetRouterIdentity () : identity);
  310. m_Data.UpdatePacketSize (m_RemoteIdentity->GetIdentHash ());
  311. payload += identitySize; // identity
  312. auto ts = i2p::util::GetSecondsSinceEpoch ();
  313. uint32_t signedOnTime = bufbe32toh(payload);
  314. if (signedOnTime < ts - SSU_CLOCK_SKEW || signedOnTime > ts + SSU_CLOCK_SKEW)
  315. {
  316. LogPrint (eLogError, "SSU message 'confirmed' time difference ", (int)ts - signedOnTime, " exceeds clock skew");
  317. Failed ();
  318. return;
  319. }
  320. if (m_SignedData)
  321. m_SignedData->Insert (payload, 4); // insert Alice's signed on time
  322. payload += 4; // signed-on time
  323. size_t paddingSize = (payload - buf) + m_RemoteIdentity->GetSignatureLen ();
  324. paddingSize &= 0x0F; // %16
  325. if (paddingSize > 0) paddingSize = 16 - paddingSize;
  326. payload += paddingSize;
  327. // verify signature
  328. if (m_SignedData && m_SignedData->Verify (m_RemoteIdentity, payload))
  329. {
  330. m_Data.Send (CreateDeliveryStatusMsg (0));
  331. Established ();
  332. }
  333. else
  334. {
  335. LogPrint (eLogError, "SSU message 'confirmed' signature verification failed");
  336. Failed ();
  337. }
  338. }
  339. void SSUSession::SendSessionRequest ()
  340. {
  341. uint8_t buf[320 + 18] = {0}; // 304 bytes for ipv4, 320 for ipv6
  342. uint8_t * payload = buf + sizeof (SSUHeader);
  343. uint8_t flag = 0;
  344. // fill extended options, 3 bytes extended options don't change message size
  345. if (i2p::context.GetStatus () == eRouterStatusOK) // we don't need relays
  346. {
  347. // tell out peer to now assign relay tag
  348. flag = SSU_HEADER_EXTENDED_OPTIONS_INCLUDED;
  349. *payload = 2; payload++; // 1 byte length
  350. uint16_t flags = 0; // clear EXTENDED_OPTIONS_FLAG_REQUEST_RELAY_TAG
  351. htobe16buf (payload, flags);
  352. payload += 2;
  353. }
  354. // fill payload
  355. memcpy (payload, m_DHKeysPair->GetPublicKey (), 256); // x
  356. bool isV4 = m_RemoteEndpoint.address ().is_v4 ();
  357. if (isV4)
  358. {
  359. payload[256] = 4;
  360. memcpy (payload + 257, m_RemoteEndpoint.address ().to_v4 ().to_bytes ().data(), 4);
  361. }
  362. else
  363. {
  364. payload[256] = 16;
  365. memcpy (payload + 257, m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data(), 16);
  366. }
  367. // encrypt and send
  368. uint8_t iv[16];
  369. RAND_bytes (iv, 16); // random iv
  370. FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_REQUEST, buf, isV4 ? 304 : 320, m_IntroKey, iv, m_IntroKey, flag);
  371. m_Server.Send (buf, isV4 ? 304 : 320, m_RemoteEndpoint);
  372. }
  373. void SSUSession::SendRelayRequest (const i2p::data::RouterInfo::Introducer& introducer, uint32_t nonce)
  374. {
  375. auto address = i2p::context.GetRouterInfo ().GetSSUAddress (false);
  376. if (!address)
  377. {
  378. LogPrint (eLogInfo, "SSU is not supported");
  379. return;
  380. }
  381. uint8_t buf[96 + 18] = {0};
  382. uint8_t * payload = buf + sizeof (SSUHeader);
  383. htobe32buf (payload, introducer.iTag);
  384. payload += 4;
  385. *payload = 0; // no address
  386. payload++;
  387. htobuf16(payload, 0); // port = 0
  388. payload += 2;
  389. *payload = 0; // challenge
  390. payload++;
  391. memcpy (payload, (const uint8_t *)address->ssu->key, 32);
  392. payload += 32;
  393. htobe32buf (payload, nonce); // nonce
  394. uint8_t iv[16];
  395. RAND_bytes (iv, 16); // random iv
  396. if (m_State == eSessionStateEstablished)
  397. FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_REQUEST, buf, 96, m_SessionKey, iv, m_MacKey);
  398. else
  399. FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_REQUEST, buf, 96, introducer.iKey, iv, introducer.iKey);
  400. m_Server.Send (buf, 96, m_RemoteEndpoint);
  401. }
  402. void SSUSession::SendSessionCreated (const uint8_t * x, bool sendRelayTag)
  403. {
  404. auto address = IsV6 () ? i2p::context.GetRouterInfo ().GetSSUV6Address () :
  405. i2p::context.GetRouterInfo ().GetSSUAddress (true); //v4 only
  406. if (!address)
  407. {
  408. LogPrint (eLogInfo, "SSU is not supported");
  409. return;
  410. }
  411. SignedData s; // x,y, remote IP, remote port, our IP, our port, relayTag, signed on time
  412. s.Insert (x, 256); // x
  413. uint8_t buf[384 + 18] = {0};
  414. uint8_t * payload = buf + sizeof (SSUHeader);
  415. memcpy (payload, m_DHKeysPair->GetPublicKey (), 256);
  416. s.Insert (payload, 256); // y
  417. payload += 256;
  418. if (m_RemoteEndpoint.address ().is_v4 ())
  419. {
  420. // ipv4
  421. *payload = 4;
  422. payload++;
  423. memcpy (payload, m_RemoteEndpoint.address ().to_v4 ().to_bytes ().data(), 4);
  424. s.Insert (payload, 4); // remote endpoint IP V4
  425. payload += 4;
  426. }
  427. else
  428. {
  429. // ipv6
  430. *payload = 16;
  431. payload++;
  432. memcpy (payload, m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data(), 16);
  433. s.Insert (payload, 16); // remote endpoint IP V6
  434. payload += 16;
  435. }
  436. htobe16buf (payload, m_RemoteEndpoint.port ());
  437. s.Insert (payload, 2); // remote port
  438. payload += 2;
  439. if (address->host.is_v4 ())
  440. s.Insert (address->host.to_v4 ().to_bytes ().data (), 4); // our IP V4
  441. else
  442. s.Insert (address->host.to_v6 ().to_bytes ().data (), 16); // our IP V6
  443. s.Insert<uint16_t> (htobe16 (address->port)); // our port
  444. if (sendRelayTag && i2p::context.GetRouterInfo ().IsIntroducer () && !IsV6 ())
  445. {
  446. RAND_bytes((uint8_t *)&m_SentRelayTag, 4);
  447. if (!m_SentRelayTag) m_SentRelayTag = 1;
  448. }
  449. htobe32buf (payload, m_SentRelayTag);
  450. payload += 4; // relay tag
  451. htobe32buf (payload, i2p::util::GetSecondsSinceEpoch ()); // signed on time
  452. payload += 4;
  453. s.Insert (payload - 8, 4); // relayTag
  454. // we have to store this signed data for session confirmed
  455. // same data but signed on time, it will Alice's there
  456. m_SignedData = std::unique_ptr<SignedData>(new SignedData (s));
  457. s.Insert (payload - 4, 4); // BOB's signed on time
  458. s.Sign (i2p::context.GetPrivateKeys (), payload); // DSA signature
  459. uint8_t iv[16];
  460. RAND_bytes (iv, 16); // random iv
  461. // encrypt signature and padding with newly created session key
  462. size_t signatureLen = i2p::context.GetIdentity ()->GetSignatureLen ();
  463. size_t paddingSize = signatureLen & 0x0F; // %16
  464. if (paddingSize > 0)
  465. {
  466. // fill random padding
  467. RAND_bytes(payload + signatureLen, (16 - paddingSize));
  468. signatureLen += (16 - paddingSize);
  469. }
  470. m_SessionKeyEncryption.SetIV (iv);
  471. m_SessionKeyEncryption.Encrypt (payload, signatureLen, payload);
  472. payload += signatureLen;
  473. size_t msgLen = payload - buf;
  474. // encrypt message with intro key
  475. FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_CREATED, buf, msgLen, m_IntroKey, iv, m_IntroKey);
  476. Send (buf, msgLen);
  477. }
  478. void SSUSession::SendSessionConfirmed (const uint8_t * y, const uint8_t * ourAddress, size_t ourAddressLen)
  479. {
  480. uint8_t buf[512 + 18] = {0};
  481. uint8_t * payload = buf + sizeof (SSUHeader);
  482. *payload = 1; // 1 fragment
  483. payload++; // info
  484. size_t identLen = i2p::context.GetIdentity ()->GetFullLen (); // 387+ bytes
  485. htobe16buf (payload, identLen);
  486. payload += 2; // cursize
  487. i2p::context.GetIdentity ()->ToBuffer (payload, identLen);
  488. payload += identLen;
  489. uint32_t signedOnTime = i2p::util::GetSecondsSinceEpoch ();
  490. htobe32buf (payload, signedOnTime); // signed on time
  491. payload += 4;
  492. auto signatureLen = i2p::context.GetIdentity ()->GetSignatureLen ();
  493. size_t paddingSize = ((payload - buf) + signatureLen)%16;
  494. if (paddingSize > 0) paddingSize = 16 - paddingSize;
  495. RAND_bytes(payload, paddingSize); // fill padding with random
  496. payload += paddingSize; // padding size
  497. // signature
  498. SignedData s; // x,y, our IP, our port, remote IP, remote port, relayTag, our signed on time
  499. s.Insert (m_DHKeysPair->GetPublicKey (), 256); // x
  500. s.Insert (y, 256); // y
  501. s.Insert (ourAddress, ourAddressLen); // our address/port as seem by party
  502. if (m_RemoteEndpoint.address ().is_v4 ())
  503. s.Insert (m_RemoteEndpoint.address ().to_v4 ().to_bytes ().data (), 4); // remote IP V4
  504. else
  505. s.Insert (m_RemoteEndpoint.address ().to_v6 ().to_bytes ().data (), 16); // remote IP V6
  506. s.Insert<uint16_t> (htobe16 (m_RemoteEndpoint.port ())); // remote port
  507. s.Insert (htobe32 (m_RelayTag)); // relay tag
  508. s.Insert (htobe32 (signedOnTime)); // signed on time
  509. s.Sign (i2p::context.GetPrivateKeys (), payload); // DSA signature
  510. payload += signatureLen;
  511. size_t msgLen = payload - buf;
  512. uint8_t iv[16];
  513. RAND_bytes (iv, 16); // random iv
  514. // encrypt message with session key
  515. FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_CONFIRMED, buf, msgLen, m_SessionKey, iv, m_MacKey);
  516. Send (buf, msgLen);
  517. }
  518. void SSUSession::ProcessRelayRequest (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& from)
  519. {
  520. uint32_t relayTag = bufbe32toh (buf);
  521. auto session = m_Server.FindRelaySession (relayTag);
  522. if (session)
  523. {
  524. buf += 4; // relay tag
  525. uint8_t size = *buf;
  526. buf++; // size
  527. buf += size; // address
  528. buf += 2; // port
  529. uint8_t challengeSize = *buf;
  530. buf++; // challenge size
  531. buf += challengeSize;
  532. const uint8_t * introKey = buf;
  533. buf += 32; // introkey
  534. uint32_t nonce = bufbe32toh (buf);
  535. SendRelayResponse (nonce, from, introKey, session->m_RemoteEndpoint);
  536. SendRelayIntro (session, from);
  537. }
  538. }
  539. void SSUSession::SendRelayResponse (uint32_t nonce, const boost::asio::ip::udp::endpoint& from,
  540. const uint8_t * introKey, const boost::asio::ip::udp::endpoint& to)
  541. {
  542. // Charlie's address always v4
  543. if (!to.address ().is_v4 ())
  544. {
  545. LogPrint (eLogWarning, "SSU: Charlie's IP must be v4");
  546. return;
  547. }
  548. uint8_t buf[80 + 18] = {0}; // 64 Alice's ipv4 and 80 Alice's ipv6
  549. uint8_t * payload = buf + sizeof (SSUHeader);
  550. *payload = 4;
  551. payload++; // size
  552. htobe32buf (payload, to.address ().to_v4 ().to_ulong ()); // Charlie's IP
  553. payload += 4; // address
  554. htobe16buf (payload, to.port ()); // Charlie's port
  555. payload += 2; // port
  556. // Alice
  557. bool isV4 = from.address ().is_v4 (); // Alice's
  558. if (isV4)
  559. {
  560. *payload = 4;
  561. payload++; // size
  562. memcpy (payload, from.address ().to_v4 ().to_bytes ().data (), 4); // Alice's IP V4
  563. payload += 4; // address
  564. }
  565. else
  566. {
  567. *payload = 16;
  568. payload++; // size
  569. memcpy (payload, from.address ().to_v6 ().to_bytes ().data (), 16); // Alice's IP V6
  570. payload += 16; // address
  571. }
  572. htobe16buf (payload, from.port ()); // Alice's port
  573. payload += 2; // port
  574. htobe32buf (payload, nonce);
  575. if (m_State == eSessionStateEstablished)
  576. {
  577. // encrypt with session key
  578. FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_RESPONSE, buf, isV4 ? 64 : 80);
  579. Send (buf, isV4 ? 64 : 80);
  580. }
  581. else
  582. {
  583. // ecrypt with Alice's intro key
  584. uint8_t iv[16];
  585. RAND_bytes (iv, 16); // random iv
  586. FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_RESPONSE, buf, isV4 ? 64 : 80, introKey, iv, introKey);
  587. m_Server.Send (buf, isV4 ? 64 : 80, from);
  588. }
  589. LogPrint (eLogDebug, "SSU: relay response sent");
  590. }
  591. void SSUSession::SendRelayIntro (std::shared_ptr<SSUSession> session, const boost::asio::ip::udp::endpoint& from)
  592. {
  593. if (!session) return;
  594. // Alice's address always v4
  595. if (!from.address ().is_v4 ())
  596. {
  597. LogPrint (eLogWarning, "SSU: Alice's IP must be v4");
  598. return;
  599. }
  600. uint8_t buf[48 + 18] = {0};
  601. uint8_t * payload = buf + sizeof (SSUHeader);
  602. *payload = 4;
  603. payload++; // size
  604. htobe32buf (payload, from.address ().to_v4 ().to_ulong ()); // Alice's IP
  605. payload += 4; // address
  606. htobe16buf (payload, from.port ()); // Alice's port
  607. payload += 2; // port
  608. *payload = 0; // challenge size
  609. uint8_t iv[16];
  610. RAND_bytes (iv, 16); // random iv
  611. FillHeaderAndEncrypt (PAYLOAD_TYPE_RELAY_INTRO, buf, 48, session->m_SessionKey, iv, session->m_MacKey);
  612. m_Server.Send (buf, 48, session->m_RemoteEndpoint);
  613. LogPrint (eLogDebug, "SSU: relay intro sent");
  614. }
  615. void SSUSession::ProcessRelayResponse (const uint8_t * buf, size_t len)
  616. {
  617. LogPrint (eLogDebug, "SSU message: Relay response received");
  618. uint8_t remoteSize = *buf;
  619. buf++; // remote size
  620. boost::asio::ip::address_v4 remoteIP (bufbe32toh (buf));
  621. buf += remoteSize; // remote address
  622. uint16_t remotePort = bufbe16toh (buf);
  623. buf += 2; // remote port
  624. uint8_t ourSize = *buf;
  625. buf++; // our size
  626. boost::asio::ip::address ourIP;
  627. if (ourSize == 4)
  628. {
  629. boost::asio::ip::address_v4::bytes_type bytes;
  630. memcpy (bytes.data (), buf, 4);
  631. ourIP = boost::asio::ip::address_v4 (bytes);
  632. }
  633. else
  634. {
  635. boost::asio::ip::address_v6::bytes_type bytes;
  636. memcpy (bytes.data (), buf, 16);
  637. ourIP = boost::asio::ip::address_v6 (bytes);
  638. }
  639. buf += ourSize; // our address
  640. uint16_t ourPort = bufbe16toh (buf);
  641. buf += 2; // our port
  642. LogPrint (eLogInfo, "SSU: Our external address is ", ourIP.to_string (), ":", ourPort);
  643. i2p::context.UpdateAddress (ourIP);
  644. uint32_t nonce = bufbe32toh (buf);
  645. buf += 4; // nonce
  646. auto it = m_RelayRequests.find (nonce);
  647. if (it != m_RelayRequests.end ())
  648. {
  649. // check if we are waiting for introduction
  650. boost::asio::ip::udp::endpoint remoteEndpoint (remoteIP, remotePort);
  651. if (!m_Server.FindSession (remoteEndpoint))
  652. {
  653. // we didn't have correct endpoint when sent relay request
  654. // now we do
  655. LogPrint (eLogInfo, "SSU: RelayReponse connecting to endpoint ", remoteEndpoint);
  656. if (i2p::context.GetRouterInfo ().UsesIntroducer ()) // if we are unreachable
  657. m_Server.Send (buf, 0, remoteEndpoint); // send HolePunch
  658. m_Server.CreateDirectSession (it->second, remoteEndpoint, false);
  659. }
  660. // delete request
  661. m_RelayRequests.erase (it);
  662. }
  663. else
  664. LogPrint (eLogError, "SSU: Unsolicited RelayResponse, nonce=", nonce);
  665. }
  666. void SSUSession::ProcessRelayIntro (const uint8_t * buf, size_t len)
  667. {
  668. uint8_t size = *buf;
  669. if (size == 4)
  670. {
  671. buf++; // size
  672. boost::asio::ip::address_v4 address (bufbe32toh (buf));
  673. buf += 4; // address
  674. uint16_t port = bufbe16toh (buf);
  675. // send hole punch of 0 bytes
  676. m_Server.Send (buf, 0, boost::asio::ip::udp::endpoint (address, port));
  677. }
  678. else
  679. LogPrint (eLogWarning, "SSU: Address size ", size, " is not supported");
  680. }
  681. void SSUSession::FillHeaderAndEncrypt (uint8_t payloadType, uint8_t * buf, size_t len,
  682. const i2p::crypto::AESKey& aesKey, const uint8_t * iv, const i2p::crypto::MACKey& macKey, uint8_t flag)
  683. {
  684. if (len < sizeof (SSUHeader))
  685. {
  686. LogPrint (eLogError, "SSU: Unexpected packet length ", len);
  687. return;
  688. }
  689. SSUHeader * header = (SSUHeader *)buf;
  690. memcpy (header->iv, iv, 16);
  691. header->flag = flag | (payloadType << 4); // MSB is 0
  692. htobe32buf (header->time, i2p::util::GetSecondsSinceEpoch ());
  693. uint8_t * encrypted = &header->flag;
  694. uint16_t encryptedLen = len - (encrypted - buf);
  695. i2p::crypto::CBCEncryption encryption;
  696. encryption.SetKey (aesKey);
  697. encryption.SetIV (iv);
  698. encryption.Encrypt (encrypted, encryptedLen, encrypted);
  699. // assume actual buffer size is 18 (16 + 2) bytes more
  700. memcpy (buf + len, iv, 16);
  701. htobe16buf (buf + len + 16, encryptedLen);
  702. i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, macKey, header->mac);
  703. }
  704. void SSUSession::FillHeaderAndEncrypt (uint8_t payloadType, uint8_t * buf, size_t len)
  705. {
  706. if (len < sizeof (SSUHeader))
  707. {
  708. LogPrint (eLogError, "SSU: Unexpected packet length ", len);
  709. return;
  710. }
  711. SSUHeader * header = (SSUHeader *)buf;
  712. RAND_bytes (header->iv, 16); // random iv
  713. m_SessionKeyEncryption.SetIV (header->iv);
  714. header->flag = payloadType << 4; // MSB is 0
  715. htobe32buf (header->time, i2p::util::GetSecondsSinceEpoch ());
  716. uint8_t * encrypted = &header->flag;
  717. uint16_t encryptedLen = len - (encrypted - buf);
  718. m_SessionKeyEncryption.Encrypt (encrypted, encryptedLen, encrypted);
  719. // assume actual buffer size is 18 (16 + 2) bytes more
  720. memcpy (buf + len, header->iv, 16);
  721. htobe16buf (buf + len + 16, encryptedLen);
  722. i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, m_MacKey, header->mac);
  723. }
  724. void SSUSession::Decrypt (uint8_t * buf, size_t len, const i2p::crypto::AESKey& aesKey)
  725. {
  726. if (len < sizeof (SSUHeader))
  727. {
  728. LogPrint (eLogError, "SSU: Unexpected packet length ", len);
  729. return;
  730. }
  731. SSUHeader * header = (SSUHeader *)buf;
  732. uint8_t * encrypted = &header->flag;
  733. uint16_t encryptedLen = len - (encrypted - buf);
  734. i2p::crypto::CBCDecryption decryption;
  735. decryption.SetKey (aesKey);
  736. decryption.SetIV (header->iv);
  737. decryption.Decrypt (encrypted, encryptedLen, encrypted);
  738. }
  739. void SSUSession::DecryptSessionKey (uint8_t * buf, size_t len)
  740. {
  741. if (len < sizeof (SSUHeader))
  742. {
  743. LogPrint (eLogError, "SSU: Unexpected packet length ", len);
  744. return;
  745. }
  746. SSUHeader * header = (SSUHeader *)buf;
  747. uint8_t * encrypted = &header->flag;
  748. uint16_t encryptedLen = len - (encrypted - buf);
  749. if (encryptedLen > 0)
  750. {
  751. m_SessionKeyDecryption.SetIV (header->iv);
  752. m_SessionKeyDecryption.Decrypt (encrypted, encryptedLen, encrypted);
  753. }
  754. }
  755. bool SSUSession::Validate (uint8_t * buf, size_t len, const i2p::crypto::MACKey& macKey)
  756. {
  757. if (len < sizeof (SSUHeader))
  758. {
  759. LogPrint (eLogError, "SSU: Unexpected packet length ", len);
  760. return false;
  761. }
  762. SSUHeader * header = (SSUHeader *)buf;
  763. uint8_t * encrypted = &header->flag;
  764. uint16_t encryptedLen = len - (encrypted - buf);
  765. // assume actual buffer size is 18 (16 + 2) bytes more
  766. memcpy (buf + len, header->iv, 16);
  767. htobe16buf (buf + len + 16, encryptedLen);
  768. uint8_t digest[16];
  769. i2p::crypto::HMACMD5Digest (encrypted, encryptedLen + 18, macKey, digest);
  770. return !memcmp (header->mac, digest, 16);
  771. }
  772. void SSUSession::Connect ()
  773. {
  774. if (m_State == eSessionStateUnknown)
  775. {
  776. // set connect timer
  777. ScheduleConnectTimer ();
  778. m_DHKeysPair = transports.GetNextDHKeysPair ();
  779. SendSessionRequest ();
  780. }
  781. }
  782. void SSUSession::WaitForConnect ()
  783. {
  784. if (!IsOutgoing ()) // incoming session
  785. ScheduleConnectTimer ();
  786. else
  787. LogPrint (eLogError, "SSU: wait for connect for outgoing session");
  788. }
  789. void SSUSession::ScheduleConnectTimer ()
  790. {
  791. m_ConnectTimer.cancel ();
  792. m_ConnectTimer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
  793. m_ConnectTimer.async_wait (std::bind (&SSUSession::HandleConnectTimer,
  794. shared_from_this (), std::placeholders::_1));
  795. }
  796. void SSUSession::HandleConnectTimer (const boost::system::error_code& ecode)
  797. {
  798. if (!ecode)
  799. {
  800. // timeout expired
  801. LogPrint (eLogWarning, "SSU: session with ", m_RemoteEndpoint, " was not established after ", SSU_CONNECT_TIMEOUT, " seconds");
  802. Failed ();
  803. }
  804. }
  805. void SSUSession::Introduce (const i2p::data::RouterInfo::Introducer& introducer,
  806. std::shared_ptr<const i2p::data::RouterInfo> to)
  807. {
  808. if (m_State == eSessionStateUnknown)
  809. {
  810. // set connect timer
  811. m_ConnectTimer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
  812. m_ConnectTimer.async_wait (std::bind (&SSUSession::HandleConnectTimer,
  813. shared_from_this (), std::placeholders::_1));
  814. }
  815. uint32_t nonce;
  816. RAND_bytes ((uint8_t *)&nonce, 4);
  817. m_RelayRequests[nonce] = to;
  818. SendRelayRequest (introducer, nonce);
  819. }
  820. void SSUSession::WaitForIntroduction ()
  821. {
  822. m_State = eSessionStateIntroduced;
  823. // set connect timer
  824. m_ConnectTimer.expires_from_now (boost::posix_time::seconds(SSU_CONNECT_TIMEOUT));
  825. m_ConnectTimer.async_wait (std::bind (&SSUSession::HandleConnectTimer,
  826. shared_from_this (), std::placeholders::_1));
  827. }
  828. void SSUSession::Close ()
  829. {
  830. SendSessionDestroyed ();
  831. Reset ();
  832. m_State = eSessionStateClosed;
  833. }
  834. void SSUSession::Reset ()
  835. {
  836. m_State = eSessionStateUnknown;
  837. transports.PeerDisconnected (shared_from_this ());
  838. m_Data.Stop ();
  839. m_ConnectTimer.cancel ();
  840. if (m_SentRelayTag)
  841. {
  842. m_Server.RemoveRelay (m_SentRelayTag); // relay tag is not valid anymore
  843. m_SentRelayTag = 0;
  844. }
  845. m_DHKeysPair = nullptr;
  846. m_SignedData = nullptr;
  847. m_IsSessionKey = false;
  848. }
  849. void SSUSession::Done ()
  850. {
  851. GetService ().post (std::bind (&SSUSession::Failed, shared_from_this ()));
  852. }
  853. void SSUSession::Established ()
  854. {
  855. m_State = eSessionStateEstablished;
  856. m_DHKeysPair = nullptr;
  857. m_SignedData = nullptr;
  858. m_Data.Start ();
  859. transports.PeerConnected (shared_from_this ());
  860. if (m_IsPeerTest)
  861. SendPeerTest ();
  862. if (m_SentRelayTag)
  863. m_Server.AddRelay (m_SentRelayTag, shared_from_this ());
  864. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  865. }
  866. void SSUSession::Failed ()
  867. {
  868. if (m_State != eSessionStateFailed)
  869. {
  870. m_State = eSessionStateFailed;
  871. m_Server.DeleteSession (shared_from_this ());
  872. }
  873. }
  874. void SSUSession::SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs)
  875. {
  876. GetService ().post (std::bind (&SSUSession::PostI2NPMessages, shared_from_this (), msgs));
  877. }
  878. void SSUSession::PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs)
  879. {
  880. if (m_State == eSessionStateEstablished)
  881. {
  882. for (const auto& it: msgs)
  883. if (it)
  884. {
  885. if (it->GetLength () <= SSU_MAX_I2NP_MESSAGE_SIZE)
  886. m_Data.Send (it);
  887. else
  888. LogPrint (eLogError, "SSU: I2NP message of size ", it->GetLength (), " can't be sent. Dropped");
  889. }
  890. }
  891. }
  892. void SSUSession::ProcessData (uint8_t * buf, size_t len)
  893. {
  894. m_Data.ProcessMessage (buf, len);
  895. m_IsDataReceived = true;
  896. }
  897. void SSUSession::FlushData ()
  898. {
  899. if (m_IsDataReceived)
  900. {
  901. m_Data.FlushReceivedMessage ();
  902. m_IsDataReceived = false;
  903. }
  904. }
  905. void SSUSession::ProcessPeerTest (const uint8_t * buf, size_t len, const boost::asio::ip::udp::endpoint& senderEndpoint)
  906. {
  907. uint32_t nonce = bufbe32toh (buf); // 4 bytes
  908. uint8_t size = buf[4]; // 1 byte
  909. const uint8_t * address = buf + 5; // big endian, size bytes
  910. uint16_t port = buf16toh(buf + size + 5); // big endian, 2 bytes
  911. const uint8_t * introKey = buf + size + 7;
  912. if (port && (size != 4) && (size != 16))
  913. {
  914. LogPrint (eLogWarning, "SSU: Address of ", size, " bytes not supported");
  915. return;
  916. }
  917. switch (m_Server.GetPeerTestParticipant (nonce))
  918. {
  919. // existing test
  920. case ePeerTestParticipantAlice1:
  921. {
  922. if (m_Server.GetPeerTestSession (nonce) == shared_from_this ()) // Alice-Bob
  923. {
  924. LogPrint (eLogDebug, "SSU: peer test from Bob. We are Alice");
  925. if (i2p::context.GetStatus () == eRouterStatusTesting) // still not OK
  926. i2p::context.SetStatus (eRouterStatusFirewalled);
  927. }
  928. else
  929. {
  930. LogPrint (eLogDebug, "SSU: first peer test from Charlie. We are Alice");
  931. if (m_State == eSessionStateEstablished)
  932. LogPrint (eLogWarning, "SSU: first peer test from Charlie through established session. We are Alice");
  933. i2p::context.SetStatus (eRouterStatusOK);
  934. m_Server.UpdatePeerTest (nonce, ePeerTestParticipantAlice2);
  935. SendPeerTest (nonce, senderEndpoint.address (), senderEndpoint.port (), introKey, true, false); // to Charlie
  936. }
  937. break;
  938. }
  939. case ePeerTestParticipantAlice2:
  940. {
  941. if (m_Server.GetPeerTestSession (nonce) == shared_from_this ()) // Alice-Bob
  942. LogPrint (eLogDebug, "SSU: peer test from Bob. We are Alice");
  943. else
  944. {
  945. // peer test successive
  946. LogPrint (eLogDebug, "SSU: second peer test from Charlie. We are Alice");
  947. i2p::context.SetStatus (eRouterStatusOK);
  948. m_Server.RemovePeerTest (nonce);
  949. }
  950. break;
  951. }
  952. case ePeerTestParticipantBob:
  953. {
  954. LogPrint (eLogDebug, "SSU: peer test from Charlie. We are Bob");
  955. auto session = m_Server.GetPeerTestSession (nonce); // session with Alice from PeerTest
  956. if (session && session->m_State == eSessionStateEstablished)
  957. session->Send (PAYLOAD_TYPE_PEER_TEST, buf, len); // back to Alice
  958. m_Server.RemovePeerTest (nonce); // nonce has been used
  959. break;
  960. }
  961. case ePeerTestParticipantCharlie:
  962. {
  963. LogPrint (eLogDebug, "SSU: peer test from Alice. We are Charlie");
  964. SendPeerTest (nonce, senderEndpoint.address (), senderEndpoint.port (), introKey); // to Alice with her actual address
  965. m_Server.RemovePeerTest (nonce); // nonce has been used
  966. break;
  967. }
  968. // test not found
  969. case ePeerTestParticipantUnknown:
  970. {
  971. if (m_State == eSessionStateEstablished)
  972. {
  973. // new test
  974. if (port)
  975. {
  976. LogPrint (eLogDebug, "SSU: peer test from Bob. We are Charlie");
  977. m_Server.NewPeerTest (nonce, ePeerTestParticipantCharlie);
  978. Send (PAYLOAD_TYPE_PEER_TEST, buf, len); // back to Bob
  979. boost::asio::ip::address addr; // Alice's address
  980. if (size == 4) // v4
  981. {
  982. boost::asio::ip::address_v4::bytes_type bytes;
  983. memcpy (bytes.data (), address, 4);
  984. addr = boost::asio::ip::address_v4 (bytes);
  985. }
  986. else // v6
  987. {
  988. boost::asio::ip::address_v6::bytes_type bytes;
  989. memcpy (bytes.data (), address, 16);
  990. addr = boost::asio::ip::address_v6 (bytes);
  991. }
  992. SendPeerTest (nonce, addr, be16toh (port), introKey); // to Alice with her address received from Bob
  993. }
  994. else
  995. {
  996. LogPrint (eLogDebug, "SSU: peer test from Alice. We are Bob");
  997. auto session = senderEndpoint.address ().is_v4 () ? m_Server.GetRandomEstablishedV4Session (shared_from_this ()) : m_Server.GetRandomEstablishedV6Session (shared_from_this ()); // Charlie
  998. if (session)
  999. {
  1000. m_Server.NewPeerTest (nonce, ePeerTestParticipantBob, shared_from_this ());
  1001. session->SendPeerTest (nonce, senderEndpoint.address (), senderEndpoint.port (), introKey, false); // to Charlie with Alice's actual address
  1002. }
  1003. }
  1004. }
  1005. else
  1006. LogPrint (eLogError, "SSU: unexpected peer test");
  1007. }
  1008. }
  1009. }
  1010. void SSUSession::SendPeerTest (uint32_t nonce, const boost::asio::ip::address& address, uint16_t port,
  1011. const uint8_t * introKey, bool toAddress, bool sendAddress)
  1012. // toAddress is true for Alice<->Chalie communications only
  1013. // sendAddress is false if message comes from Alice
  1014. {
  1015. uint8_t buf[80 + 18] = {0};
  1016. uint8_t iv[16];
  1017. uint8_t * payload = buf + sizeof (SSUHeader);
  1018. htobe32buf (payload, nonce);
  1019. payload += 4; // nonce
  1020. // address and port
  1021. if (sendAddress)
  1022. {
  1023. if (address.is_v4 ())
  1024. {
  1025. *payload = 4;
  1026. memcpy (payload + 1, address.to_v4 ().to_bytes ().data (), 4); // our IP V4
  1027. }
  1028. else if (address.is_v6 ())
  1029. {
  1030. *payload = 16;
  1031. memcpy (payload + 1, address.to_v6 ().to_bytes ().data (), 16); // our IP V6
  1032. }
  1033. else
  1034. *payload = 0;
  1035. payload += (payload[0] + 1);
  1036. }
  1037. else
  1038. {
  1039. *payload = 0;
  1040. payload++; //size
  1041. }
  1042. htobe16buf (payload, port);
  1043. payload += 2; // port
  1044. // intro key
  1045. if (toAddress)
  1046. {
  1047. // send our intro key to address instead of its own
  1048. auto addr = i2p::context.GetRouterInfo ().GetSSUAddress ();
  1049. if (addr)
  1050. memcpy (payload, addr->ssu->key, 32); // intro key
  1051. else
  1052. LogPrint (eLogInfo, "SSU is not supported. Can't send peer test");
  1053. }
  1054. else
  1055. memcpy (payload, introKey, 32); // intro key
  1056. // send
  1057. RAND_bytes (iv, 16); // random iv
  1058. if (toAddress)
  1059. {
  1060. // encrypt message with specified intro key
  1061. FillHeaderAndEncrypt (PAYLOAD_TYPE_PEER_TEST, buf, 80, introKey, iv, introKey);
  1062. boost::asio::ip::udp::endpoint e (address, port);
  1063. m_Server.Send (buf, 80, e);
  1064. }
  1065. else
  1066. {
  1067. // encrypt message with session key
  1068. FillHeaderAndEncrypt (PAYLOAD_TYPE_PEER_TEST, buf, 80);
  1069. Send (buf, 80);
  1070. }
  1071. }
  1072. void SSUSession::SendPeerTest ()
  1073. {
  1074. // we are Alice
  1075. LogPrint (eLogDebug, "SSU: sending peer test");
  1076. auto address = i2p::context.GetRouterInfo ().GetSSUAddress (i2p::context.SupportsV4 ());
  1077. if (!address)
  1078. {
  1079. LogPrint (eLogInfo, "SSU is not supported. Can't send peer test");
  1080. return;
  1081. }
  1082. uint32_t nonce;
  1083. RAND_bytes ((uint8_t *)&nonce, 4);
  1084. if (!nonce) nonce = 1;
  1085. m_IsPeerTest = false;
  1086. m_Server.NewPeerTest (nonce, ePeerTestParticipantAlice1, shared_from_this ());
  1087. SendPeerTest (nonce, boost::asio::ip::address(), 0, address->ssu->key, false, false); // address and port always zero for Alice
  1088. }
  1089. void SSUSession::SendKeepAlive ()
  1090. {
  1091. if (m_State == eSessionStateEstablished)
  1092. {
  1093. uint8_t buf[48 + 18] = {0};
  1094. uint8_t * payload = buf + sizeof (SSUHeader);
  1095. *payload = 0; // flags
  1096. payload++;
  1097. *payload = 0; // num fragments
  1098. // encrypt message with session key
  1099. FillHeaderAndEncrypt (PAYLOAD_TYPE_DATA, buf, 48);
  1100. Send (buf, 48);
  1101. LogPrint (eLogDebug, "SSU: keep-alive sent");
  1102. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  1103. }
  1104. }
  1105. void SSUSession::SendSessionDestroyed ()
  1106. {
  1107. if (m_IsSessionKey)
  1108. {
  1109. uint8_t buf[48 + 18] = {0};
  1110. // encrypt message with session key
  1111. FillHeaderAndEncrypt (PAYLOAD_TYPE_SESSION_DESTROYED, buf, 48);
  1112. try
  1113. {
  1114. Send (buf, 48);
  1115. }
  1116. catch (std::exception& ex)
  1117. {
  1118. LogPrint (eLogWarning, "SSU: exception while sending session destoroyed: ", ex.what ());
  1119. }
  1120. LogPrint (eLogDebug, "SSU: session destroyed sent");
  1121. }
  1122. }
  1123. void SSUSession::Send (uint8_t type, const uint8_t * payload, size_t len)
  1124. {
  1125. uint8_t buf[SSU_MTU_V4 + 18] = {0};
  1126. size_t msgSize = len + sizeof (SSUHeader);
  1127. size_t paddingSize = msgSize & 0x0F; // %16
  1128. if (paddingSize > 0) msgSize += (16 - paddingSize);
  1129. if (msgSize > SSU_MTU_V4)
  1130. {
  1131. LogPrint (eLogWarning, "SSU: payload size ", msgSize, " exceeds MTU");
  1132. return;
  1133. }
  1134. memcpy (buf + sizeof (SSUHeader), payload, len);
  1135. // encrypt message with session key
  1136. FillHeaderAndEncrypt (type, buf, msgSize);
  1137. Send (buf, msgSize);
  1138. }
  1139. void SSUSession::Send (const uint8_t * buf, size_t size)
  1140. {
  1141. m_NumSentBytes += size;
  1142. i2p::transport::transports.UpdateSentBytes (size);
  1143. m_Server.Send (buf, size, m_RemoteEndpoint);
  1144. }
  1145. }
  1146. }