NTCPSession.cpp 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <future>
  4. #include "I2PEndian.h"
  5. #include "Base.h"
  6. #include "Crypto.h"
  7. #include "Log.h"
  8. #include "Timestamp.h"
  9. #include "I2NPProtocol.h"
  10. #include "RouterContext.h"
  11. #include "Transports.h"
  12. #include "NetDb.hpp"
  13. #include "NTCPSession.h"
  14. #include "HTTP.h"
  15. #include "util.h"
  16. #ifdef WITH_EVENTS
  17. #include "Event.h"
  18. #endif
  19. using namespace i2p::crypto;
  20. namespace i2p
  21. {
  22. namespace transport
  23. {
  24. struct NTCPWork
  25. {
  26. std::shared_ptr<NTCPSession> session;
  27. };
  28. NTCPSession::NTCPSession (NTCPServer& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter):
  29. TransportSession (in_RemoteRouter, NTCP_ESTABLISH_TIMEOUT),
  30. m_Server (server), m_Socket (m_Server.GetService ()),
  31. m_IsEstablished (false), m_IsTerminated (false),
  32. m_ReceiveBufferOffset (0), m_NextMessage (nullptr), m_IsSending (false)
  33. {
  34. m_Establisher = new Establisher;
  35. }
  36. NTCPSession::~NTCPSession ()
  37. {
  38. delete m_Establisher;
  39. }
  40. void NTCPSession::CreateAESKey (uint8_t * pubKey)
  41. {
  42. uint8_t sharedKey[256];
  43. m_DHKeysPair->Agree (pubKey, sharedKey); // time consuming operation
  44. i2p::crypto::AESKey aesKey;
  45. if (sharedKey[0] & 0x80)
  46. {
  47. aesKey[0] = 0;
  48. memcpy (aesKey + 1, sharedKey, 31);
  49. }
  50. else if (sharedKey[0])
  51. memcpy (aesKey, sharedKey, 32);
  52. else
  53. {
  54. // find first non-zero byte
  55. uint8_t * nonZero = sharedKey + 1;
  56. while (!*nonZero)
  57. {
  58. nonZero++;
  59. if (nonZero - sharedKey > 32)
  60. {
  61. LogPrint (eLogWarning, "NTCP: First 32 bytes of shared key is all zeros, ignored");
  62. return;
  63. }
  64. }
  65. memcpy (aesKey, nonZero, 32);
  66. }
  67. m_Decryption.SetKey (aesKey);
  68. m_Encryption.SetKey (aesKey);
  69. }
  70. void NTCPSession::Done ()
  71. {
  72. m_Server.GetService ().post (std::bind (&NTCPSession::Terminate, shared_from_this ()));
  73. }
  74. void NTCPSession::Terminate ()
  75. {
  76. if (!m_IsTerminated)
  77. {
  78. m_IsTerminated = true;
  79. m_IsEstablished = false;
  80. m_Socket.close ();
  81. transports.PeerDisconnected (shared_from_this ());
  82. m_Server.RemoveNTCPSession (shared_from_this ());
  83. m_SendQueue.clear ();
  84. m_NextMessage = nullptr;
  85. LogPrint (eLogDebug, "NTCP: session terminated");
  86. }
  87. }
  88. void NTCPSession::Connected ()
  89. {
  90. m_IsEstablished = true;
  91. delete m_Establisher;
  92. m_Establisher = nullptr;
  93. m_DHKeysPair = nullptr;
  94. SetTerminationTimeout (NTCP_TERMINATION_TIMEOUT);
  95. SendTimeSyncMessage ();
  96. transports.PeerConnected (shared_from_this ());
  97. }
  98. boost::asio::io_service & NTCPSession::GetService()
  99. {
  100. return m_Server.GetService();
  101. }
  102. void NTCPSession::ClientLogin ()
  103. {
  104. if (!m_DHKeysPair)
  105. m_DHKeysPair = transports.GetNextDHKeysPair ();
  106. // send Phase1
  107. const uint8_t * x = m_DHKeysPair->GetPublicKey ();
  108. memcpy (m_Establisher->phase1.pubKey, x, 256);
  109. SHA256(x, 256, m_Establisher->phase1.HXxorHI);
  110. const uint8_t * ident = m_RemoteIdentity->GetIdentHash ();
  111. for (int i = 0; i < 32; i++)
  112. m_Establisher->phase1.HXxorHI[i] ^= ident[i];
  113. boost::asio::async_write (m_Socket, boost::asio::buffer (&m_Establisher->phase1, sizeof (NTCPPhase1)), boost::asio::transfer_all (),
  114. std::bind(&NTCPSession::HandlePhase1Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  115. }
  116. void NTCPSession::ServerLogin ()
  117. {
  118. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  119. // receive Phase1
  120. boost::asio::async_read (m_Socket, boost::asio::buffer(&m_Establisher->phase1, sizeof (NTCPPhase1)), boost::asio::transfer_all (),
  121. std::bind(&NTCPSession::HandlePhase1Received, shared_from_this (),
  122. std::placeholders::_1, std::placeholders::_2));
  123. }
  124. void NTCPSession::HandlePhase1Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  125. {
  126. (void) bytes_transferred;
  127. if (ecode)
  128. {
  129. LogPrint (eLogInfo, "NTCP: couldn't send Phase 1 message: ", ecode.message ());
  130. if (ecode != boost::asio::error::operation_aborted)
  131. Terminate ();
  132. }
  133. else
  134. {
  135. boost::asio::async_read (m_Socket, boost::asio::buffer(&m_Establisher->phase2, sizeof (NTCPPhase2)), boost::asio::transfer_all (),
  136. std::bind(&NTCPSession::HandlePhase2Received, shared_from_this (),
  137. std::placeholders::_1, std::placeholders::_2));
  138. }
  139. }
  140. void NTCPSession::HandlePhase1Received (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  141. {
  142. (void) bytes_transferred;
  143. if (ecode)
  144. {
  145. LogPrint (eLogInfo, "NTCP: phase 1 read error: ", ecode.message ());
  146. if (ecode != boost::asio::error::operation_aborted)
  147. Terminate ();
  148. }
  149. else
  150. {
  151. // verify ident
  152. uint8_t digest[32];
  153. SHA256(m_Establisher->phase1.pubKey, 256, digest);
  154. const uint8_t * ident = i2p::context.GetIdentHash ();
  155. for (int i = 0; i < 32; i++)
  156. {
  157. if ((m_Establisher->phase1.HXxorHI[i] ^ ident[i]) != digest[i])
  158. {
  159. LogPrint (eLogError, "NTCP: phase 1 error: ident mismatch");
  160. Terminate ();
  161. return;
  162. }
  163. }
  164. // TODO: check for number of pending keys
  165. auto work = new NTCPWork{shared_from_this()};
  166. m_Server.Work(work->session, [work, this]() -> std::function<void(void)> {
  167. if (!work->session->m_DHKeysPair)
  168. work->session->m_DHKeysPair = transports.GetNextDHKeysPair ();
  169. work->session->CreateAESKey (work->session->m_Establisher->phase1.pubKey);
  170. return std::bind(&NTCPSession::SendPhase2, work->session, work);
  171. });
  172. }
  173. }
  174. void NTCPSession::SendPhase2 (NTCPWork * work)
  175. {
  176. if(work)
  177. delete work;
  178. const uint8_t * y = m_DHKeysPair->GetPublicKey ();
  179. memcpy (m_Establisher->phase2.pubKey, y, 256);
  180. uint8_t xy[512];
  181. memcpy (xy, m_Establisher->phase1.pubKey, 256);
  182. memcpy (xy + 256, y, 256);
  183. SHA256(xy, 512, m_Establisher->phase2.encrypted.hxy);
  184. uint32_t tsB = htobe32 (i2p::util::GetSecondsSinceEpoch ());
  185. memcpy (m_Establisher->phase2.encrypted.timestamp, &tsB, 4);
  186. RAND_bytes (m_Establisher->phase2.encrypted.filler, 12);
  187. m_Encryption.SetIV (y + 240);
  188. m_Decryption.SetIV (m_Establisher->phase1.HXxorHI + 16);
  189. m_Encryption.Encrypt ((uint8_t *)&m_Establisher->phase2.encrypted, sizeof(m_Establisher->phase2.encrypted), (uint8_t *)&m_Establisher->phase2.encrypted);
  190. boost::asio::async_write(m_Socket, boost::asio::buffer (&m_Establisher->phase2, sizeof (NTCPPhase2)), boost::asio::transfer_all(),
  191. std::bind(&NTCPSession::HandlePhase2Sent, shared_from_this(), std::placeholders::_1, std::placeholders::_2, tsB));
  192. }
  193. void NTCPSession::HandlePhase2Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB)
  194. {
  195. (void) bytes_transferred;
  196. if (ecode)
  197. {
  198. LogPrint (eLogInfo, "NTCP: Couldn't send Phase 2 message: ", ecode.message ());
  199. if (ecode != boost::asio::error::operation_aborted)
  200. Terminate ();
  201. }
  202. else
  203. {
  204. boost::asio::async_read (m_Socket, boost::asio::buffer(m_ReceiveBuffer, NTCP_DEFAULT_PHASE3_SIZE), boost::asio::transfer_all (),
  205. std::bind(&NTCPSession::HandlePhase3Received, shared_from_this (),
  206. std::placeholders::_1, std::placeholders::_2, tsB));
  207. }
  208. }
  209. void NTCPSession::HandlePhase2Received (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  210. {
  211. (void) bytes_transferred;
  212. if (ecode)
  213. {
  214. LogPrint (eLogInfo, "NTCP: Phase 2 read error: ", ecode.message (), ". Wrong ident assumed");
  215. if (ecode != boost::asio::error::operation_aborted)
  216. {
  217. // this RI is not valid
  218. i2p::data::netdb.SetUnreachable (GetRemoteIdentity ()->GetIdentHash (), true);
  219. transports.ReuseDHKeysPair (m_DHKeysPair);
  220. m_DHKeysPair = nullptr;
  221. Terminate ();
  222. }
  223. }
  224. else
  225. {
  226. auto work = new NTCPWork{shared_from_this()};
  227. m_Server.Work(work->session, [work, this]() -> std::function<void(void)> {
  228. work->session->CreateAESKey (work->session->m_Establisher->phase2.pubKey);
  229. return std::bind(&NTCPSession::HandlePhase2, work->session, work);
  230. });
  231. }
  232. }
  233. void NTCPSession::HandlePhase2 (NTCPWork * work)
  234. {
  235. if(work) delete work;
  236. m_Decryption.SetIV (m_Establisher->phase2.pubKey + 240);
  237. m_Encryption.SetIV (m_Establisher->phase1.HXxorHI + 16);
  238. m_Decryption.Decrypt((uint8_t *)&m_Establisher->phase2.encrypted, sizeof(m_Establisher->phase2.encrypted), (uint8_t *)&m_Establisher->phase2.encrypted);
  239. // verify
  240. uint8_t xy[512];
  241. memcpy (xy, m_DHKeysPair->GetPublicKey (), 256);
  242. memcpy (xy + 256, m_Establisher->phase2.pubKey, 256);
  243. uint8_t digest[32];
  244. SHA256 (xy, 512, digest);
  245. if (memcmp(m_Establisher->phase2.encrypted.hxy, digest, 32))
  246. {
  247. LogPrint (eLogError, "NTCP: Phase 2 process error: incorrect hash");
  248. transports.ReuseDHKeysPair (m_DHKeysPair);
  249. m_DHKeysPair = nullptr;
  250. Terminate ();
  251. return ;
  252. }
  253. SendPhase3 ();
  254. }
  255. void NTCPSession::SendPhase3 ()
  256. {
  257. auto& keys = i2p::context.GetPrivateKeys ();
  258. uint8_t * buf = m_ReceiveBuffer;
  259. htobe16buf (buf, keys.GetPublic ()->GetFullLen ());
  260. buf += 2;
  261. buf += i2p::context.GetIdentity ()->ToBuffer (buf, NTCP_BUFFER_SIZE);
  262. uint32_t tsA = htobe32 (i2p::util::GetSecondsSinceEpoch ());
  263. htobuf32(buf,tsA);
  264. buf += 4;
  265. size_t signatureLen = keys.GetPublic ()->GetSignatureLen ();
  266. size_t len = (buf - m_ReceiveBuffer) + signatureLen;
  267. size_t paddingSize = len & 0x0F; // %16
  268. if (paddingSize > 0)
  269. {
  270. paddingSize = 16 - paddingSize;
  271. // fill padding with random data
  272. RAND_bytes(buf, paddingSize);
  273. buf += paddingSize;
  274. len += paddingSize;
  275. }
  276. SignedData s;
  277. s.Insert (m_Establisher->phase1.pubKey, 256); // x
  278. s.Insert (m_Establisher->phase2.pubKey, 256); // y
  279. s.Insert (m_RemoteIdentity->GetIdentHash (), 32); // ident
  280. s.Insert (tsA); // tsA
  281. s.Insert (m_Establisher->phase2.encrypted.timestamp, 4); // tsB
  282. s.Sign (keys, buf);
  283. m_Encryption.Encrypt(m_ReceiveBuffer, len, m_ReceiveBuffer);
  284. boost::asio::async_write (m_Socket, boost::asio::buffer (m_ReceiveBuffer, len), boost::asio::transfer_all (),
  285. std::bind(&NTCPSession::HandlePhase3Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, tsA));
  286. }
  287. void NTCPSession::HandlePhase3Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA)
  288. {
  289. (void) bytes_transferred;
  290. if (ecode)
  291. {
  292. LogPrint (eLogInfo, "NTCP: Couldn't send Phase 3 message: ", ecode.message ());
  293. if (ecode != boost::asio::error::operation_aborted)
  294. Terminate ();
  295. }
  296. else
  297. {
  298. // wait for phase4
  299. auto signatureLen = m_RemoteIdentity->GetSignatureLen ();
  300. size_t paddingSize = signatureLen & 0x0F; // %16
  301. if (paddingSize > 0) signatureLen += (16 - paddingSize);
  302. boost::asio::async_read (m_Socket, boost::asio::buffer(m_ReceiveBuffer, signatureLen), boost::asio::transfer_all (),
  303. std::bind(&NTCPSession::HandlePhase4Received, shared_from_this (),
  304. std::placeholders::_1, std::placeholders::_2, tsA));
  305. }
  306. }
  307. void NTCPSession::HandlePhase3Received (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB)
  308. {
  309. if (ecode)
  310. {
  311. LogPrint (eLogInfo, "NTCP: Phase 3 read error: ", ecode.message ());
  312. if (ecode != boost::asio::error::operation_aborted)
  313. Terminate ();
  314. }
  315. else
  316. {
  317. m_Decryption.Decrypt (m_ReceiveBuffer, bytes_transferred, m_ReceiveBuffer);
  318. uint8_t * buf = m_ReceiveBuffer;
  319. uint16_t size = bufbe16toh (buf);
  320. auto identity = std::make_shared<i2p::data::IdentityEx> (buf + 2, size);
  321. if (m_Server.FindNTCPSession (identity->GetIdentHash ()))
  322. {
  323. LogPrint (eLogInfo, "NTCP: session already exists");
  324. Terminate ();
  325. }
  326. auto existing = i2p::data::netdb.FindRouter (identity->GetIdentHash ()); // check if exists already
  327. SetRemoteIdentity (existing ? existing->GetRouterIdentity () : identity);
  328. size_t expectedSize = size + 2/*size*/ + 4/*timestamp*/ + m_RemoteIdentity->GetSignatureLen ();
  329. size_t paddingLen = expectedSize & 0x0F;
  330. if (paddingLen) paddingLen = (16 - paddingLen);
  331. if (expectedSize > NTCP_DEFAULT_PHASE3_SIZE)
  332. {
  333. // we need more bytes for Phase3
  334. expectedSize += paddingLen;
  335. boost::asio::async_read (m_Socket, boost::asio::buffer(m_ReceiveBuffer + NTCP_DEFAULT_PHASE3_SIZE, expectedSize - NTCP_DEFAULT_PHASE3_SIZE), boost::asio::transfer_all (),
  336. std::bind(&NTCPSession::HandlePhase3ExtraReceived, shared_from_this (),
  337. std::placeholders::_1, std::placeholders::_2, tsB, paddingLen));
  338. }
  339. else
  340. HandlePhase3 (tsB, paddingLen);
  341. }
  342. }
  343. void NTCPSession::HandlePhase3ExtraReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsB, size_t paddingLen)
  344. {
  345. if (ecode)
  346. {
  347. LogPrint (eLogInfo, "NTCP: Phase 3 extra read error: ", ecode.message ());
  348. if (ecode != boost::asio::error::operation_aborted)
  349. Terminate ();
  350. }
  351. else
  352. {
  353. m_Decryption.Decrypt (m_ReceiveBuffer + NTCP_DEFAULT_PHASE3_SIZE, bytes_transferred, m_ReceiveBuffer+ NTCP_DEFAULT_PHASE3_SIZE);
  354. HandlePhase3 (tsB, paddingLen);
  355. }
  356. }
  357. void NTCPSession::HandlePhase3 (uint32_t tsB, size_t paddingLen)
  358. {
  359. uint8_t * buf = m_ReceiveBuffer + m_RemoteIdentity->GetFullLen () + 2 /*size*/;
  360. uint32_t tsA = buf32toh(buf);
  361. buf += 4;
  362. buf += paddingLen;
  363. // check timestamp
  364. auto ts = i2p::util::GetSecondsSinceEpoch ();
  365. uint32_t tsA1 = be32toh (tsA);
  366. if (tsA1 < ts - NTCP_CLOCK_SKEW || tsA1 > ts + NTCP_CLOCK_SKEW)
  367. {
  368. LogPrint (eLogError, "NTCP: Phase3 time difference ", (int)(ts - tsA1), " exceeds clock skew");
  369. Terminate ();
  370. return;
  371. }
  372. // check signature
  373. SignedData s;
  374. s.Insert (m_Establisher->phase1.pubKey, 256); // x
  375. s.Insert (m_Establisher->phase2.pubKey, 256); // y
  376. s.Insert (i2p::context.GetRouterInfo ().GetIdentHash (), 32); // ident
  377. s.Insert (tsA); // tsA
  378. s.Insert (tsB); // tsB
  379. if (!s.Verify (m_RemoteIdentity, buf))
  380. {
  381. LogPrint (eLogError, "NTCP: signature verification failed");
  382. Terminate ();
  383. return;
  384. }
  385. SendPhase4 (tsA, tsB);
  386. }
  387. void NTCPSession::SendPhase4 (uint32_t tsA, uint32_t tsB)
  388. {
  389. SignedData s;
  390. s.Insert (m_Establisher->phase1.pubKey, 256); // x
  391. s.Insert (m_Establisher->phase2.pubKey, 256); // y
  392. s.Insert (m_RemoteIdentity->GetIdentHash (), 32); // ident
  393. s.Insert (tsA); // tsA
  394. s.Insert (tsB); // tsB
  395. auto& keys = i2p::context.GetPrivateKeys ();
  396. auto signatureLen = keys.GetPublic ()->GetSignatureLen ();
  397. s.Sign (keys, m_ReceiveBuffer);
  398. size_t paddingSize = signatureLen & 0x0F; // %16
  399. if (paddingSize > 0) signatureLen += (16 - paddingSize);
  400. m_Encryption.Encrypt (m_ReceiveBuffer, signatureLen, m_ReceiveBuffer);
  401. boost::asio::async_write (m_Socket, boost::asio::buffer (m_ReceiveBuffer, signatureLen), boost::asio::transfer_all (),
  402. std::bind(&NTCPSession::HandlePhase4Sent, shared_from_this (), std::placeholders::_1, std::placeholders::_2));
  403. }
  404. void NTCPSession::HandlePhase4Sent (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  405. {
  406. (void) bytes_transferred;
  407. if (ecode)
  408. {
  409. LogPrint (eLogWarning, "NTCP: Couldn't send Phase 4 message: ", ecode.message ());
  410. if (ecode != boost::asio::error::operation_aborted)
  411. Terminate ();
  412. }
  413. else
  414. {
  415. LogPrint (eLogDebug, "NTCP: Server session from ", m_Socket.remote_endpoint (), " connected");
  416. m_Server.AddNTCPSession (shared_from_this ());
  417. Connected ();
  418. m_ReceiveBufferOffset = 0;
  419. m_NextMessage = nullptr;
  420. Receive ();
  421. }
  422. }
  423. void NTCPSession::HandlePhase4Received (const boost::system::error_code& ecode, std::size_t bytes_transferred, uint32_t tsA)
  424. {
  425. if (ecode)
  426. {
  427. LogPrint (eLogError, "NTCP: Phase 4 read error: ", ecode.message (), ". Check your clock");
  428. if (ecode != boost::asio::error::operation_aborted)
  429. {
  430. // this router doesn't like us
  431. i2p::data::netdb.SetUnreachable (GetRemoteIdentity ()->GetIdentHash (), true);
  432. Terminate ();
  433. }
  434. }
  435. else
  436. {
  437. m_Decryption.Decrypt(m_ReceiveBuffer, bytes_transferred, m_ReceiveBuffer);
  438. // check timestamp
  439. uint32_t tsB = bufbe32toh (m_Establisher->phase2.encrypted.timestamp);
  440. auto ts = i2p::util::GetSecondsSinceEpoch ();
  441. if (tsB < ts - NTCP_CLOCK_SKEW || tsB > ts + NTCP_CLOCK_SKEW)
  442. {
  443. LogPrint (eLogError, "NTCP: Phase4 time difference ", (int)(ts - tsB), " exceeds clock skew");
  444. Terminate ();
  445. return;
  446. }
  447. // verify signature
  448. SignedData s;
  449. s.Insert (m_Establisher->phase1.pubKey, 256); // x
  450. s.Insert (m_Establisher->phase2.pubKey, 256); // y
  451. s.Insert (i2p::context.GetIdentHash (), 32); // ident
  452. s.Insert (tsA); // tsA
  453. s.Insert (m_Establisher->phase2.encrypted.timestamp, 4); // tsB
  454. if (!s.Verify (m_RemoteIdentity, m_ReceiveBuffer))
  455. {
  456. LogPrint (eLogError, "NTCP: Phase 4 process error: signature verification failed");
  457. Terminate ();
  458. return;
  459. }
  460. LogPrint (eLogDebug, "NTCP: session to ", m_Socket.remote_endpoint (), " connected");
  461. Connected ();
  462. m_ReceiveBufferOffset = 0;
  463. m_NextMessage = nullptr;
  464. Receive ();
  465. }
  466. }
  467. void NTCPSession::Receive ()
  468. {
  469. m_Socket.async_read_some (boost::asio::buffer(m_ReceiveBuffer + m_ReceiveBufferOffset, NTCP_BUFFER_SIZE - m_ReceiveBufferOffset),
  470. std::bind(&NTCPSession::HandleReceived, shared_from_this (),
  471. std::placeholders::_1, std::placeholders::_2));
  472. }
  473. void NTCPSession::HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred)
  474. {
  475. if (ecode)
  476. {
  477. if (ecode != boost::asio::error::operation_aborted)
  478. LogPrint (eLogDebug, "NTCP: Read error: ", ecode.message ());
  479. //if (ecode != boost::asio::error::operation_aborted)
  480. Terminate ();
  481. }
  482. else
  483. {
  484. m_NumReceivedBytes += bytes_transferred;
  485. i2p::transport::transports.UpdateReceivedBytes (bytes_transferred);
  486. m_ReceiveBufferOffset += bytes_transferred;
  487. if (m_ReceiveBufferOffset >= 16)
  488. {
  489. // process received data
  490. uint8_t * nextBlock = m_ReceiveBuffer;
  491. while (m_ReceiveBufferOffset >= 16)
  492. {
  493. if (!DecryptNextBlock (nextBlock)) // 16 bytes
  494. {
  495. Terminate ();
  496. return;
  497. }
  498. nextBlock += 16;
  499. m_ReceiveBufferOffset -= 16;
  500. }
  501. if (m_ReceiveBufferOffset > 0)
  502. memcpy (m_ReceiveBuffer, nextBlock, m_ReceiveBufferOffset);
  503. }
  504. // read and process more is available
  505. boost::system::error_code ec;
  506. size_t moreBytes = m_Socket.available(ec);
  507. if (moreBytes && !ec)
  508. {
  509. uint8_t * buf = nullptr, * moreBuf = m_ReceiveBuffer;
  510. if (moreBytes + m_ReceiveBufferOffset > NTCP_BUFFER_SIZE)
  511. {
  512. buf = new uint8_t[moreBytes + m_ReceiveBufferOffset + 16];
  513. moreBuf = buf;
  514. uint8_t rem = ((size_t)buf) & 0x0f;
  515. if (rem) moreBuf += (16 - rem); // align 16
  516. if (m_ReceiveBufferOffset)
  517. memcpy (moreBuf, m_ReceiveBuffer, m_ReceiveBufferOffset);
  518. }
  519. moreBytes = m_Socket.read_some (boost::asio::buffer (moreBuf + m_ReceiveBufferOffset, moreBytes), ec);
  520. if (ec)
  521. {
  522. LogPrint (eLogInfo, "NTCP: Read more bytes error: ", ec.message ());
  523. delete[] buf;
  524. Terminate ();
  525. return;
  526. }
  527. m_ReceiveBufferOffset += moreBytes;
  528. m_NumReceivedBytes += moreBytes;
  529. i2p::transport::transports.UpdateReceivedBytes (moreBytes);
  530. // process more data
  531. uint8_t * nextBlock = moreBuf;
  532. while (m_ReceiveBufferOffset >= 16)
  533. {
  534. if (!DecryptNextBlock (nextBlock)) // 16 bytes
  535. {
  536. delete[] buf;
  537. Terminate ();
  538. return;
  539. }
  540. nextBlock += 16;
  541. m_ReceiveBufferOffset -= 16;
  542. }
  543. if (m_ReceiveBufferOffset > 0)
  544. memcpy (m_ReceiveBuffer, nextBlock, m_ReceiveBufferOffset); // nextBlock points to memory inside buf
  545. delete[] buf;
  546. }
  547. m_Handler.Flush ();
  548. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  549. Receive ();
  550. }
  551. }
  552. bool NTCPSession::DecryptNextBlock (const uint8_t * encrypted) // 16 bytes
  553. {
  554. if (!m_NextMessage) // new message, header expected
  555. {
  556. // decrypt header and extract length
  557. uint8_t buf[16];
  558. m_Decryption.Decrypt (encrypted, buf);
  559. uint16_t dataSize = bufbe16toh (buf);
  560. if (dataSize)
  561. {
  562. // new message
  563. if (dataSize + 16U + 15U > NTCP_MAX_MESSAGE_SIZE - 2) // + 6 + padding
  564. {
  565. LogPrint (eLogError, "NTCP: data size ", dataSize, " exceeds max size");
  566. return false;
  567. }
  568. m_NextMessage = (dataSize + 16U + 15U) <= I2NP_MAX_SHORT_MESSAGE_SIZE - 2 ? NewI2NPShortMessage () : NewI2NPMessage ();
  569. m_NextMessage->Align (16);
  570. m_NextMessage->offset += 2; // size field
  571. m_NextMessage->len = m_NextMessage->offset + dataSize;
  572. memcpy (m_NextMessage->GetBuffer () - 2, buf, 16);
  573. m_NextMessageOffset = 16;
  574. }
  575. else
  576. {
  577. // timestamp
  578. int diff = (int)bufbe32toh (buf + 2) - (int)i2p::util::GetSecondsSinceEpoch ();
  579. LogPrint (eLogInfo, "NTCP: Timestamp. Time difference ", diff, " seconds");
  580. return true;
  581. }
  582. }
  583. else // message continues
  584. {
  585. m_Decryption.Decrypt (encrypted, m_NextMessage->GetBuffer () - 2 + m_NextMessageOffset);
  586. m_NextMessageOffset += 16;
  587. }
  588. if (m_NextMessageOffset >= m_NextMessage->GetLength () + 2 + 4) // +checksum
  589. {
  590. // we have a complete I2NP message
  591. uint8_t checksum[4];
  592. htobe32buf (checksum, adler32 (adler32 (0, Z_NULL, 0), m_NextMessage->GetBuffer () - 2, m_NextMessageOffset - 4));
  593. if (!memcmp (m_NextMessage->GetBuffer () - 2 + m_NextMessageOffset - 4, checksum, 4))
  594. {
  595. if (!m_NextMessage->IsExpired ())
  596. {
  597. #ifdef WITH_EVENTS
  598. QueueIntEvent("transport.recvmsg", GetIdentHashBase64(), 1);
  599. #endif
  600. m_Handler.PutNextMessage (m_NextMessage);
  601. }
  602. else
  603. LogPrint (eLogInfo, "NTCP: message expired");
  604. }
  605. else
  606. LogPrint (eLogWarning, "NTCP: Incorrect adler checksum of message, dropped");
  607. m_NextMessage = nullptr;
  608. }
  609. return true;
  610. }
  611. void NTCPSession::Send (std::shared_ptr<i2p::I2NPMessage> msg)
  612. {
  613. m_IsSending = true;
  614. boost::asio::async_write (m_Socket, CreateMsgBuffer (msg), boost::asio::transfer_all (),
  615. std::bind(&NTCPSession::HandleSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, std::vector<std::shared_ptr<I2NPMessage> >{ msg }));
  616. }
  617. boost::asio::const_buffers_1 NTCPSession::CreateMsgBuffer (std::shared_ptr<I2NPMessage> msg)
  618. {
  619. uint8_t * sendBuffer;
  620. int len;
  621. if (msg)
  622. {
  623. // regular I2NP
  624. if (msg->offset < 2)
  625. LogPrint (eLogError, "NTCP: Malformed I2NP message"); // TODO:
  626. sendBuffer = msg->GetBuffer () - 2;
  627. len = msg->GetLength ();
  628. htobe16buf (sendBuffer, len);
  629. }
  630. else
  631. {
  632. // prepare timestamp
  633. sendBuffer = m_TimeSyncBuffer;
  634. len = 4;
  635. htobuf16(sendBuffer, 0);
  636. htobe32buf (sendBuffer + 2, i2p::util::GetSecondsSinceEpoch ());
  637. }
  638. int rem = (len + 6) & 0x0F; // %16
  639. int padding = 0;
  640. if (rem > 0) {
  641. padding = 16 - rem;
  642. // fill with random padding
  643. RAND_bytes(sendBuffer + len + 2, padding);
  644. }
  645. htobe32buf (sendBuffer + len + 2 + padding, adler32 (adler32 (0, Z_NULL, 0), sendBuffer, len + 2+ padding));
  646. int l = len + padding + 6;
  647. m_Encryption.Encrypt(sendBuffer, l, sendBuffer);
  648. return boost::asio::buffer ((const uint8_t *)sendBuffer, l);
  649. }
  650. void NTCPSession::Send (const std::vector<std::shared_ptr<I2NPMessage> >& msgs)
  651. {
  652. m_IsSending = true;
  653. std::vector<boost::asio::const_buffer> bufs;
  654. for (const auto& it: msgs)
  655. bufs.push_back (CreateMsgBuffer (it));
  656. boost::asio::async_write (m_Socket, bufs, boost::asio::transfer_all (),
  657. std::bind(&NTCPSession::HandleSent, shared_from_this (), std::placeholders::_1, std::placeholders::_2, msgs));
  658. }
  659. void NTCPSession::HandleSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs)
  660. {
  661. (void) msgs;
  662. m_IsSending = false;
  663. if (ecode)
  664. {
  665. LogPrint (eLogWarning, "NTCP: Couldn't send msgs: ", ecode.message ());
  666. // we shouldn't call Terminate () here, because HandleReceive takes care
  667. // TODO: 'delete this' statement in Terminate () must be eliminated later
  668. // Terminate ();
  669. }
  670. else
  671. {
  672. m_LastActivityTimestamp = i2p::util::GetSecondsSinceEpoch ();
  673. m_NumSentBytes += bytes_transferred;
  674. i2p::transport::transports.UpdateSentBytes (bytes_transferred);
  675. if (!m_SendQueue.empty())
  676. {
  677. Send (m_SendQueue);
  678. m_SendQueue.clear ();
  679. }
  680. }
  681. }
  682. void NTCPSession::SendTimeSyncMessage ()
  683. {
  684. Send (nullptr);
  685. }
  686. void NTCPSession::SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs)
  687. {
  688. m_Server.GetService ().post (std::bind (&NTCPSession::PostI2NPMessages, shared_from_this (), msgs));
  689. }
  690. void NTCPSession::PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs)
  691. {
  692. if (m_IsTerminated) return;
  693. if (m_IsSending)
  694. {
  695. if (m_SendQueue.size () < NTCP_MAX_OUTGOING_QUEUE_SIZE)
  696. {
  697. for (const auto& it: msgs)
  698. m_SendQueue.push_back (it);
  699. }
  700. else
  701. {
  702. LogPrint (eLogWarning, "NTCP: outgoing messages queue size exceeds ", NTCP_MAX_OUTGOING_QUEUE_SIZE);
  703. Terminate ();
  704. }
  705. }
  706. else
  707. Send (msgs);
  708. }
  709. //-----------------------------------------
  710. NTCPServer::NTCPServer (int workers):
  711. m_IsRunning (false), m_Thread (nullptr), m_Work (m_Service),
  712. m_TerminationTimer (m_Service), m_NTCPAcceptor (nullptr), m_NTCPV6Acceptor (nullptr),
  713. m_ProxyType(eNoProxy), m_Resolver(m_Service), m_ProxyEndpoint(nullptr),
  714. m_SoftLimit(0), m_HardLimit(0)
  715. {
  716. if(workers <= 0) workers = 1;
  717. m_CryptoPool = std::make_shared<Pool>(workers);
  718. }
  719. NTCPServer::~NTCPServer ()
  720. {
  721. Stop ();
  722. }
  723. void NTCPServer::Start ()
  724. {
  725. if (!m_IsRunning)
  726. {
  727. m_IsRunning = true;
  728. m_Thread = new std::thread (std::bind (&NTCPServer::Run, this));
  729. // we are using a proxy, don't create any acceptors
  730. if(UsingProxy())
  731. {
  732. // TODO: resolve proxy until it is resolved
  733. boost::asio::ip::tcp::resolver::query q(m_ProxyAddress, std::to_string(m_ProxyPort));
  734. boost::system::error_code e;
  735. auto itr = m_Resolver.resolve(q, e);
  736. if(e)
  737. {
  738. LogPrint(eLogError, "NTCP: Failed to resolve proxy ", e.message());
  739. }
  740. else
  741. {
  742. m_ProxyEndpoint = new boost::asio::ip::tcp::endpoint(*itr);
  743. }
  744. }
  745. else
  746. {
  747. // create acceptors
  748. auto& addresses = context.GetRouterInfo ().GetAddresses ();
  749. for (const auto& address: addresses)
  750. {
  751. if (!address) continue;
  752. if (address->transportStyle == i2p::data::RouterInfo::eTransportNTCP && !address->IsNTCP2 ())
  753. {
  754. if (address->host.is_v4())
  755. {
  756. try
  757. {
  758. m_NTCPAcceptor = new boost::asio::ip::tcp::acceptor (m_Service, boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), address->port));
  759. } catch ( std::exception & ex ) {
  760. /** fail to bind ip4 */
  761. LogPrint(eLogError, "NTCP: Failed to bind to ip4 port ",address->port, ex.what());
  762. continue;
  763. }
  764. LogPrint (eLogInfo, "NTCP: Start listening TCP port ", address->port);
  765. auto conn = std::make_shared<NTCPSession>(*this);
  766. m_NTCPAcceptor->async_accept(conn->GetSocket (), std::bind (&NTCPServer::HandleAccept, this, conn, std::placeholders::_1));
  767. }
  768. else if (address->host.is_v6() && context.SupportsV6 ())
  769. {
  770. m_NTCPV6Acceptor = new boost::asio::ip::tcp::acceptor (m_Service);
  771. try
  772. {
  773. m_NTCPV6Acceptor->open (boost::asio::ip::tcp::v6());
  774. m_NTCPV6Acceptor->set_option (boost::asio::ip::v6_only (true));
  775. m_NTCPV6Acceptor->set_option (boost::asio::socket_base::reuse_address (true));
  776. m_NTCPV6Acceptor->bind (boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v6(), address->port));
  777. m_NTCPV6Acceptor->listen ();
  778. LogPrint (eLogInfo, "NTCP: Start listening V6 TCP port ", address->port);
  779. auto conn = std::make_shared<NTCPSession> (*this);
  780. m_NTCPV6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCPServer::HandleAcceptV6, this, conn, std::placeholders::_1));
  781. } catch ( std::exception & ex ) {
  782. LogPrint(eLogError, "NTCP: failed to bind to ip6 port ", address->port);
  783. continue;
  784. }
  785. }
  786. }
  787. }
  788. }
  789. ScheduleTermination ();
  790. }
  791. }
  792. void NTCPServer::Stop ()
  793. {
  794. {
  795. // we have to copy it because Terminate changes m_NTCPSessions
  796. auto ntcpSessions = m_NTCPSessions;
  797. for (auto& it: ntcpSessions)
  798. it.second->Terminate ();
  799. for (auto& it: m_PendingIncomingSessions)
  800. it->Terminate ();
  801. }
  802. m_NTCPSessions.clear ();
  803. if (m_IsRunning)
  804. {
  805. m_IsRunning = false;
  806. m_TerminationTimer.cancel ();
  807. if (m_NTCPAcceptor)
  808. {
  809. delete m_NTCPAcceptor;
  810. m_NTCPAcceptor = nullptr;
  811. }
  812. if (m_NTCPV6Acceptor)
  813. {
  814. delete m_NTCPV6Acceptor;
  815. m_NTCPV6Acceptor = nullptr;
  816. }
  817. m_Service.stop ();
  818. if (m_Thread)
  819. {
  820. m_Thread->join ();
  821. delete m_Thread;
  822. m_Thread = nullptr;
  823. }
  824. if(m_ProxyEndpoint)
  825. {
  826. delete m_ProxyEndpoint;
  827. m_ProxyEndpoint = nullptr;
  828. }
  829. }
  830. }
  831. void NTCPServer::Run ()
  832. {
  833. while (m_IsRunning)
  834. {
  835. try
  836. {
  837. m_Service.run ();
  838. }
  839. catch (std::exception& ex)
  840. {
  841. LogPrint (eLogError, "NTCP: runtime exception: ", ex.what ());
  842. }
  843. }
  844. }
  845. bool NTCPServer::AddNTCPSession (std::shared_ptr<NTCPSession> session)
  846. {
  847. if (!session || !session->GetRemoteIdentity ()) return false;
  848. auto& ident = session->GetRemoteIdentity ()->GetIdentHash ();
  849. auto it = m_NTCPSessions.find (ident);
  850. if (it != m_NTCPSessions.end ())
  851. {
  852. LogPrint (eLogWarning, "NTCP: session to ", ident.ToBase64 (), " already exists");
  853. session->Terminate();
  854. return false;
  855. }
  856. m_NTCPSessions.insert (std::pair<i2p::data::IdentHash, std::shared_ptr<NTCPSession> >(ident, session));
  857. return true;
  858. }
  859. void NTCPServer::RemoveNTCPSession (std::shared_ptr<NTCPSession> session)
  860. {
  861. if (session && session->GetRemoteIdentity ())
  862. m_NTCPSessions.erase (session->GetRemoteIdentity ()->GetIdentHash ());
  863. }
  864. std::shared_ptr<NTCPSession> NTCPServer::FindNTCPSession (const i2p::data::IdentHash& ident)
  865. {
  866. auto it = m_NTCPSessions.find (ident);
  867. if (it != m_NTCPSessions.end ())
  868. return it->second;
  869. return nullptr;
  870. }
  871. void NTCPServer::HandleAccept (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error)
  872. {
  873. if (!error)
  874. {
  875. boost::system::error_code ec;
  876. auto ep = conn->GetSocket ().remote_endpoint(ec);
  877. if (!ec)
  878. {
  879. if(ShouldLimit())
  880. {
  881. // hit limit, close premature
  882. LogPrint(eLogWarning, "NTCP: limiting with backoff session from ", ep);
  883. conn->Terminate();
  884. return;
  885. }
  886. LogPrint (eLogDebug, "NTCP: Connected from ", ep);
  887. if (conn)
  888. {
  889. conn->ServerLogin ();
  890. m_PendingIncomingSessions.push_back (conn);
  891. }
  892. }
  893. else
  894. LogPrint (eLogError, "NTCP: Connected from error ", ec.message ());
  895. }
  896. if (error != boost::asio::error::operation_aborted)
  897. {
  898. conn = std::make_shared<NTCPSession> (*this);
  899. m_NTCPAcceptor->async_accept(conn->GetSocket (), std::bind (&NTCPServer::HandleAccept, this,
  900. conn, std::placeholders::_1));
  901. }
  902. }
  903. void NTCPServer::HandleAcceptV6 (std::shared_ptr<NTCPSession> conn, const boost::system::error_code& error)
  904. {
  905. if (!error)
  906. {
  907. boost::system::error_code ec;
  908. auto ep = conn->GetSocket ().remote_endpoint(ec);
  909. if (!ec)
  910. {
  911. if(ShouldLimit())
  912. {
  913. // hit limit, close premature
  914. LogPrint(eLogWarning, "NTCP: limiting with backoff on session from ", ep);
  915. conn->Terminate();
  916. return;
  917. }
  918. LogPrint (eLogDebug, "NTCP: Connected from ", ep);
  919. if (conn)
  920. {
  921. conn->ServerLogin ();
  922. m_PendingIncomingSessions.push_back (conn);
  923. }
  924. }
  925. else
  926. LogPrint (eLogError, "NTCP: Connected from error ", ec.message ());
  927. }
  928. if (error != boost::asio::error::operation_aborted)
  929. {
  930. conn = std::make_shared<NTCPSession> (*this);
  931. m_NTCPV6Acceptor->async_accept(conn->GetSocket (), std::bind (&NTCPServer::HandleAcceptV6, this,
  932. conn, std::placeholders::_1));
  933. }
  934. }
  935. void NTCPServer::Connect(const boost::asio::ip::address & address, uint16_t port, std::shared_ptr<NTCPSession> conn)
  936. {
  937. LogPrint (eLogDebug, "NTCP: Connecting to ", address ,":", port);
  938. m_Service.post([=]() {
  939. if (this->AddNTCPSession (conn))
  940. {
  941. auto timer = std::make_shared<boost::asio::deadline_timer>(m_Service);
  942. timer->expires_from_now (boost::posix_time::seconds(NTCP_CONNECT_TIMEOUT));
  943. timer->async_wait ([conn](const boost::system::error_code& ecode) {
  944. if (ecode != boost::asio::error::operation_aborted)
  945. {
  946. LogPrint (eLogInfo, "NTCP: Not connected in ", NTCP_CONNECT_TIMEOUT, " seconds");
  947. conn->Terminate ();
  948. }
  949. });
  950. conn->GetSocket ().async_connect (boost::asio::ip::tcp::endpoint (address, port), std::bind (&NTCPServer::HandleConnect, this, std::placeholders::_1, conn, timer));
  951. }
  952. });
  953. }
  954. void NTCPServer::ConnectWithProxy (const std::string& host, uint16_t port, RemoteAddressType addrtype, std::shared_ptr<NTCPSession> conn)
  955. {
  956. if(m_ProxyEndpoint == nullptr)
  957. {
  958. return;
  959. }
  960. m_Service.post([=]() {
  961. if (this->AddNTCPSession (conn))
  962. {
  963. auto timer = std::make_shared<boost::asio::deadline_timer>(m_Service);
  964. auto timeout = NTCP_CONNECT_TIMEOUT * 5;
  965. conn->SetTerminationTimeout(timeout * 2);
  966. timer->expires_from_now (boost::posix_time::seconds(timeout));
  967. timer->async_wait ([conn, timeout](const boost::system::error_code& ecode) {
  968. if (ecode != boost::asio::error::operation_aborted)
  969. {
  970. LogPrint (eLogInfo, "NTCP: Not connected in ", timeout, " seconds");
  971. i2p::data::netdb.SetUnreachable (conn->GetRemoteIdentity ()->GetIdentHash (), true);
  972. conn->Terminate ();
  973. }
  974. });
  975. conn->GetSocket ().async_connect (*m_ProxyEndpoint, std::bind (&NTCPServer::HandleProxyConnect, this, std::placeholders::_1, conn, timer, host, port, addrtype));
  976. }
  977. });
  978. }
  979. void NTCPServer::HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCPSession> conn, std::shared_ptr<boost::asio::deadline_timer> timer)
  980. {
  981. timer->cancel ();
  982. if (ecode)
  983. {
  984. LogPrint (eLogInfo, "NTCP: Connect error ", ecode.message ());
  985. if (ecode != boost::asio::error::operation_aborted)
  986. i2p::data::netdb.SetUnreachable (conn->GetRemoteIdentity ()->GetIdentHash (), true);
  987. conn->Terminate ();
  988. }
  989. else
  990. {
  991. LogPrint (eLogDebug, "NTCP: Connected to ", conn->GetSocket ().remote_endpoint ());
  992. conn->ClientLogin ();
  993. }
  994. }
  995. void NTCPServer::UseProxy(ProxyType proxytype, const std::string & addr, uint16_t port)
  996. {
  997. m_ProxyType = proxytype;
  998. m_ProxyAddress = addr;
  999. m_ProxyPort = port;
  1000. }
  1001. void NTCPServer::HandleProxyConnect(const boost::system::error_code& ecode, std::shared_ptr<NTCPSession> conn, std::shared_ptr<boost::asio::deadline_timer> timer, const std::string & host, uint16_t port, RemoteAddressType addrtype)
  1002. {
  1003. if(ecode)
  1004. {
  1005. LogPrint(eLogWarning, "NTCP: failed to connect to proxy ", ecode.message());
  1006. timer->cancel();
  1007. conn->Terminate();
  1008. return;
  1009. }
  1010. if(m_ProxyType == eSocksProxy)
  1011. {
  1012. // TODO: support username/password auth etc
  1013. uint8_t buff[3] = {0x05, 0x01, 0x00};
  1014. boost::asio::async_write(conn->GetSocket(), boost::asio::buffer(buff, 3), boost::asio::transfer_all(), [=] (const boost::system::error_code & ec, std::size_t transferred) {
  1015. (void) transferred;
  1016. if(ec)
  1017. {
  1018. LogPrint(eLogWarning, "NTCP: socks5 write error ", ec.message());
  1019. }
  1020. });
  1021. uint8_t readbuff[2];
  1022. boost::asio::async_read(conn->GetSocket(), boost::asio::buffer(readbuff, 2), [=](const boost::system::error_code & ec, std::size_t transferred) {
  1023. if(ec)
  1024. {
  1025. LogPrint(eLogError, "NTCP: socks5 read error ", ec.message());
  1026. timer->cancel();
  1027. conn->Terminate();
  1028. return;
  1029. }
  1030. else if(transferred == 2)
  1031. {
  1032. if(readbuff[1] == 0x00)
  1033. {
  1034. AfterSocksHandshake(conn, timer, host, port, addrtype);
  1035. return;
  1036. }
  1037. else if (readbuff[1] == 0xff)
  1038. {
  1039. LogPrint(eLogError, "NTCP: socks5 proxy rejected authentication");
  1040. timer->cancel();
  1041. conn->Terminate();
  1042. return;
  1043. }
  1044. }
  1045. LogPrint(eLogError, "NTCP: socks5 server gave invalid response");
  1046. timer->cancel();
  1047. conn->Terminate();
  1048. });
  1049. }
  1050. else if(m_ProxyType == eHTTPProxy)
  1051. {
  1052. i2p::http::HTTPReq req;
  1053. req.method = "CONNECT";
  1054. req.version ="HTTP/1.1";
  1055. if(addrtype == eIP6Address)
  1056. req.uri = "[" + host + "]:" + std::to_string(port);
  1057. else
  1058. req.uri = host + ":" + std::to_string(port);
  1059. boost::asio::streambuf writebuff;
  1060. std::ostream out(&writebuff);
  1061. out << req.to_string();
  1062. boost::asio::async_write(conn->GetSocket(), writebuff.data(), boost::asio::transfer_all(), [=](const boost::system::error_code & ec, std::size_t transferred) {
  1063. (void) transferred;
  1064. if(ec)
  1065. LogPrint(eLogError, "NTCP: http proxy write error ", ec.message());
  1066. });
  1067. boost::asio::streambuf * readbuff = new boost::asio::streambuf;
  1068. boost::asio::async_read_until(conn->GetSocket(), *readbuff, "\r\n\r\n", [=] (const boost::system::error_code & ec, std::size_t transferred) {
  1069. if(ec)
  1070. {
  1071. LogPrint(eLogError, "NTCP: http proxy read error ", ec.message());
  1072. timer->cancel();
  1073. conn->Terminate();
  1074. }
  1075. else
  1076. {
  1077. readbuff->commit(transferred);
  1078. i2p::http::HTTPRes res;
  1079. if(res.parse(boost::asio::buffer_cast<const char*>(readbuff->data()), readbuff->size()) > 0)
  1080. {
  1081. if(res.code == 200)
  1082. {
  1083. timer->cancel();
  1084. conn->ClientLogin();
  1085. delete readbuff;
  1086. return;
  1087. }
  1088. else
  1089. {
  1090. LogPrint(eLogError, "NTCP: http proxy rejected request ", res.code);
  1091. }
  1092. }
  1093. else
  1094. LogPrint(eLogError, "NTCP: http proxy gave malformed response");
  1095. timer->cancel();
  1096. conn->Terminate();
  1097. delete readbuff;
  1098. }
  1099. });
  1100. }
  1101. else
  1102. LogPrint(eLogError, "NTCP: unknown proxy type, invalid state");
  1103. }
  1104. void NTCPServer::AfterSocksHandshake(std::shared_ptr<NTCPSession> conn, std::shared_ptr<boost::asio::deadline_timer> timer, const std::string & host, uint16_t port, RemoteAddressType addrtype)
  1105. {
  1106. // build request
  1107. size_t sz = 0;
  1108. uint8_t buff[256];
  1109. uint8_t readbuff[256];
  1110. buff[0] = 0x05;
  1111. buff[1] = 0x01;
  1112. buff[2] = 0x00;
  1113. if(addrtype == eIP4Address)
  1114. {
  1115. buff[3] = 0x01;
  1116. auto addr = boost::asio::ip::address::from_string(host).to_v4();
  1117. auto addrbytes = addr.to_bytes();
  1118. auto addrsize = addrbytes.size();
  1119. memcpy(buff+4, addrbytes.data(), addrsize);
  1120. }
  1121. else if (addrtype == eIP6Address)
  1122. {
  1123. buff[3] = 0x04;
  1124. auto addr = boost::asio::ip::address::from_string(host).to_v6();
  1125. auto addrbytes = addr.to_bytes();
  1126. auto addrsize = addrbytes.size();
  1127. memcpy(buff+4, addrbytes.data(), addrsize);
  1128. }
  1129. else if (addrtype == eHostname)
  1130. {
  1131. buff[3] = 0x03;
  1132. size_t addrsize = host.size();
  1133. sz = addrsize + 1 + 4;
  1134. if (2 + sz > sizeof(buff))
  1135. {
  1136. // too big
  1137. return;
  1138. }
  1139. buff[4] = (uint8_t) addrsize;
  1140. memcpy(buff+5, host.c_str(), addrsize);
  1141. }
  1142. htobe16buf(buff+sz, port);
  1143. sz += 2;
  1144. boost::asio::async_write(conn->GetSocket(), boost::asio::buffer(buff, sz), boost::asio::transfer_all(), [=](const boost::system::error_code & ec, std::size_t written) {
  1145. if(ec)
  1146. {
  1147. LogPrint(eLogError, "NTCP: failed to write handshake to socks proxy ", ec.message());
  1148. return;
  1149. }
  1150. });
  1151. boost::asio::async_read(conn->GetSocket(), boost::asio::buffer(readbuff, 10), [=](const boost::system::error_code & e, std::size_t transferred) {
  1152. if(e)
  1153. {
  1154. LogPrint(eLogError, "NTCP: socks proxy read error ", e.message());
  1155. }
  1156. else if(transferred == sz)
  1157. {
  1158. if( readbuff[1] == 0x00)
  1159. {
  1160. timer->cancel();
  1161. conn->ClientLogin();
  1162. return;
  1163. }
  1164. }
  1165. if(!e)
  1166. i2p::data::netdb.SetUnreachable (conn->GetRemoteIdentity ()->GetIdentHash (), true);
  1167. timer->cancel();
  1168. conn->Terminate();
  1169. });
  1170. }
  1171. void NTCPServer::ScheduleTermination ()
  1172. {
  1173. m_TerminationTimer.expires_from_now (boost::posix_time::seconds(NTCP_TERMINATION_CHECK_TIMEOUT));
  1174. m_TerminationTimer.async_wait (std::bind (&NTCPServer::HandleTerminationTimer,
  1175. this, std::placeholders::_1));
  1176. }
  1177. void NTCPServer::HandleTerminationTimer (const boost::system::error_code& ecode)
  1178. {
  1179. if (ecode != boost::asio::error::operation_aborted)
  1180. {
  1181. auto ts = i2p::util::GetSecondsSinceEpoch ();
  1182. // established
  1183. for (auto& it: m_NTCPSessions)
  1184. if (it.second->IsTerminationTimeoutExpired (ts))
  1185. {
  1186. auto session = it.second;
  1187. // Terminate modifies m_NTCPSession, so we postpone it
  1188. m_Service.post ([session] {
  1189. LogPrint (eLogDebug, "NTCP: No activity for ", session->GetTerminationTimeout (), " seconds");
  1190. session->Terminate ();
  1191. });
  1192. }
  1193. // pending
  1194. for (auto it = m_PendingIncomingSessions.begin (); it != m_PendingIncomingSessions.end ();)
  1195. {
  1196. if ((*it)->IsEstablished () || (*it)->IsTerminated ())
  1197. it = m_PendingIncomingSessions.erase (it); // established or terminated
  1198. else if ((*it)->IsTerminationTimeoutExpired (ts))
  1199. {
  1200. (*it)->Terminate ();
  1201. it = m_PendingIncomingSessions.erase (it); // expired
  1202. }
  1203. else
  1204. it++;
  1205. }
  1206. ScheduleTermination ();
  1207. }
  1208. }
  1209. }
  1210. }