TunnelEndpoint.cpp 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. #include "I2PEndian.h"
  2. #include <string.h>
  3. #include "Crypto.h"
  4. #include "Log.h"
  5. #include "NetDb.hpp"
  6. #include "I2NPProtocol.h"
  7. #include "Transports.h"
  8. #include "RouterContext.h"
  9. #include "Timestamp.h"
  10. #include "TunnelEndpoint.h"
  11. namespace i2p
  12. {
  13. namespace tunnel
  14. {
  15. TunnelEndpoint::~TunnelEndpoint ()
  16. {
  17. }
  18. void TunnelEndpoint::HandleDecryptedTunnelDataMsg (std::shared_ptr<I2NPMessage> msg)
  19. {
  20. m_NumReceivedBytes += TUNNEL_DATA_MSG_SIZE;
  21. uint8_t * decrypted = msg->GetPayload () + 20; // 4 + 16
  22. uint8_t * zero = (uint8_t *)memchr (decrypted + 4, 0, TUNNEL_DATA_ENCRYPTED_SIZE - 4); // witout 4-byte checksum
  23. if (zero)
  24. {
  25. uint8_t * fragment = zero + 1;
  26. // verify checksum
  27. memcpy (msg->GetPayload () + TUNNEL_DATA_MSG_SIZE, msg->GetPayload () + 4, 16); // copy iv to the end
  28. uint8_t hash[32];
  29. SHA256(fragment, TUNNEL_DATA_MSG_SIZE -(fragment - msg->GetPayload ()) + 16, hash); // payload + iv
  30. if (memcmp (hash, decrypted, 4))
  31. {
  32. LogPrint (eLogError, "TunnelMessage: checksum verification failed");
  33. return;
  34. }
  35. // process fragments
  36. while (fragment < decrypted + TUNNEL_DATA_ENCRYPTED_SIZE)
  37. {
  38. uint8_t flag = fragment[0];
  39. fragment++;
  40. bool isFollowOnFragment = flag & 0x80, isLastFragment = true;
  41. uint32_t msgID = 0;
  42. int fragmentNum = 0;
  43. TunnelMessageBlockEx m;
  44. if (!isFollowOnFragment)
  45. {
  46. // first fragment
  47. m.deliveryType = (TunnelDeliveryType)((flag >> 5) & 0x03);
  48. switch (m.deliveryType)
  49. {
  50. case eDeliveryTypeLocal: // 0
  51. break;
  52. case eDeliveryTypeTunnel: // 1
  53. m.tunnelID = bufbe32toh (fragment);
  54. fragment += 4; // tunnelID
  55. m.hash = i2p::data::IdentHash (fragment);
  56. fragment += 32; // hash
  57. break;
  58. case eDeliveryTypeRouter: // 2
  59. m.hash = i2p::data::IdentHash (fragment);
  60. fragment += 32; // to hash
  61. break;
  62. default:
  63. ;
  64. }
  65. bool isFragmented = flag & 0x08;
  66. if (isFragmented)
  67. {
  68. // Message ID
  69. msgID = bufbe32toh (fragment);
  70. fragment += 4;
  71. isLastFragment = false;
  72. }
  73. }
  74. else
  75. {
  76. // follow on
  77. msgID = bufbe32toh (fragment); // MessageID
  78. fragment += 4;
  79. fragmentNum = (flag >> 1) & 0x3F; // 6 bits
  80. isLastFragment = flag & 0x01;
  81. }
  82. uint16_t size = bufbe16toh (fragment);
  83. fragment += 2;
  84. msg->offset = fragment - msg->buf;
  85. msg->len = msg->offset + size;
  86. if (msg->len > msg->maxLen)
  87. {
  88. LogPrint (eLogError, "TunnelMessage: fragment is too long ", (int)size);
  89. return;
  90. }
  91. if (fragment + size < decrypted + TUNNEL_DATA_ENCRYPTED_SIZE)
  92. {
  93. // this is not last message. we have to copy it
  94. m.data = NewI2NPTunnelMessage ();
  95. m.data->offset += TUNNEL_GATEWAY_HEADER_SIZE; // reserve room for TunnelGateway header
  96. m.data->len += TUNNEL_GATEWAY_HEADER_SIZE;
  97. *(m.data) = *msg;
  98. }
  99. else
  100. m.data = msg;
  101. if (!isFollowOnFragment && isLastFragment)
  102. HandleNextMessage (m);
  103. else
  104. {
  105. if (msgID) // msgID is presented, assume message is fragmented
  106. {
  107. if (!isFollowOnFragment) // create new incomlete message
  108. {
  109. m.nextFragmentNum = 1;
  110. m.receiveTime = i2p::util::GetMillisecondsSinceEpoch ();
  111. auto ret = m_IncompleteMessages.insert (std::pair<uint32_t, TunnelMessageBlockEx>(msgID, m));
  112. if (ret.second)
  113. HandleOutOfSequenceFragments (msgID, ret.first->second);
  114. else
  115. LogPrint (eLogError, "TunnelMessage: Incomplete message ", msgID, " already exists");
  116. }
  117. else
  118. {
  119. m.nextFragmentNum = fragmentNum;
  120. HandleFollowOnFragment (msgID, isLastFragment, m);
  121. }
  122. }
  123. else
  124. LogPrint (eLogError, "TunnelMessage: Message is fragmented, but msgID is not presented");
  125. }
  126. fragment += size;
  127. }
  128. }
  129. else
  130. LogPrint (eLogError, "TunnelMessage: zero not found");
  131. }
  132. void TunnelEndpoint::HandleFollowOnFragment (uint32_t msgID, bool isLastFragment, const TunnelMessageBlockEx& m)
  133. {
  134. auto fragment = m.data->GetBuffer ();
  135. auto size = m.data->GetLength ();
  136. auto it = m_IncompleteMessages.find (msgID);
  137. if (it != m_IncompleteMessages.end())
  138. {
  139. auto& msg = it->second;
  140. if (m.nextFragmentNum == msg.nextFragmentNum)
  141. {
  142. if (msg.data->len + size < I2NP_MAX_MESSAGE_SIZE) // check if message is not too long
  143. {
  144. if (msg.data->len + size > msg.data->maxLen)
  145. {
  146. // LogPrint (eLogWarning, "TunnelMessage: I2NP message size ", msg.data->maxLen, " is not enough");
  147. auto newMsg = NewI2NPMessage ();
  148. *newMsg = *(msg.data);
  149. msg.data = newMsg;
  150. }
  151. if (msg.data->Concat (fragment, size) < size) // concatenate fragment
  152. LogPrint (eLogError, "TunnelMessage: I2NP buffer overflow ", msg.data->maxLen);
  153. if (isLastFragment)
  154. {
  155. // message complete
  156. HandleNextMessage (msg);
  157. m_IncompleteMessages.erase (it);
  158. }
  159. else
  160. {
  161. msg.nextFragmentNum++;
  162. HandleOutOfSequenceFragments (msgID, msg);
  163. }
  164. }
  165. else
  166. {
  167. LogPrint (eLogError, "TunnelMessage: Fragment ", m.nextFragmentNum, " of message ", msgID, "exceeds max I2NP message size, message dropped");
  168. m_IncompleteMessages.erase (it);
  169. }
  170. }
  171. else
  172. {
  173. LogPrint (eLogWarning, "TunnelMessage: Unexpected fragment ", (int)m.nextFragmentNum, " instead ", (int)msg.nextFragmentNum, " of message ", msgID, ", saved");
  174. AddOutOfSequenceFragment (msgID, m.nextFragmentNum, isLastFragment, m.data);
  175. }
  176. }
  177. else
  178. {
  179. LogPrint (eLogWarning, "TunnelMessage: First fragment of message ", msgID, " not found, saved");
  180. AddOutOfSequenceFragment (msgID, m.nextFragmentNum, isLastFragment, m.data);
  181. }
  182. }
  183. void TunnelEndpoint::AddOutOfSequenceFragment (uint32_t msgID, uint8_t fragmentNum, bool isLastFragment, std::shared_ptr<I2NPMessage> data)
  184. {
  185. if (!m_OutOfSequenceFragments.insert ({{msgID, fragmentNum}, {isLastFragment, data, i2p::util::GetMillisecondsSinceEpoch () }}).second)
  186. LogPrint (eLogInfo, "TunnelMessage: duplicate out-of-sequence fragment ", fragmentNum, " of message ", msgID);
  187. }
  188. void TunnelEndpoint::HandleOutOfSequenceFragments (uint32_t msgID, TunnelMessageBlockEx& msg)
  189. {
  190. while (ConcatNextOutOfSequenceFragment (msgID, msg))
  191. {
  192. if (!msg.nextFragmentNum) // message complete
  193. {
  194. HandleNextMessage (msg);
  195. m_IncompleteMessages.erase (msgID);
  196. break;
  197. }
  198. }
  199. }
  200. bool TunnelEndpoint::ConcatNextOutOfSequenceFragment (uint32_t msgID, TunnelMessageBlockEx& msg)
  201. {
  202. auto it = m_OutOfSequenceFragments.find ({msgID, msg.nextFragmentNum});
  203. if (it != m_OutOfSequenceFragments.end ())
  204. {
  205. LogPrint (eLogDebug, "TunnelMessage: Out-of-sequence fragment ", (int)msg.nextFragmentNum, " of message ", msgID, " found");
  206. size_t size = it->second.data->GetLength ();
  207. if (msg.data->len + size > msg.data->maxLen)
  208. {
  209. LogPrint (eLogWarning, "TunnelMessage: Tunnel endpoint I2NP message size ", msg.data->maxLen, " is not enough");
  210. auto newMsg = NewI2NPMessage ();
  211. *newMsg = *(msg.data);
  212. msg.data = newMsg;
  213. }
  214. if (msg.data->Concat (it->second.data->GetBuffer (), size) < size) // concatenate out-of-sync fragment
  215. LogPrint (eLogError, "TunnelMessage: Tunnel endpoint I2NP buffer overflow ", msg.data->maxLen);
  216. if (it->second.isLastFragment)
  217. // message complete
  218. msg.nextFragmentNum = 0;
  219. else
  220. msg.nextFragmentNum++;
  221. m_OutOfSequenceFragments.erase (it);
  222. return true;
  223. }
  224. return false;
  225. }
  226. void TunnelEndpoint::HandleNextMessage (const TunnelMessageBlock& msg)
  227. {
  228. if (!m_IsInbound && msg.data->IsExpired ())
  229. {
  230. LogPrint (eLogInfo, "TunnelMessage: message expired");
  231. return;
  232. }
  233. uint8_t typeID = msg.data->GetTypeID ();
  234. LogPrint (eLogDebug, "TunnelMessage: handle fragment of ", msg.data->GetLength (), " bytes, msg type ", (int)typeID);
  235. // catch RI or reply with new list of routers
  236. if ((IsRouterInfoMsg (msg.data) || typeID == eI2NPDatabaseSearchReply) &&
  237. !m_IsInbound && msg.deliveryType != eDeliveryTypeLocal)
  238. i2p::data::netdb.PostI2NPMsg (CopyI2NPMessage (msg.data));
  239. switch (msg.deliveryType)
  240. {
  241. case eDeliveryTypeLocal:
  242. i2p::HandleI2NPMessage (msg.data);
  243. break;
  244. case eDeliveryTypeTunnel:
  245. if (!m_IsInbound) // outbound transit tunnel
  246. i2p::transport::transports.SendMessage (msg.hash, i2p::CreateTunnelGatewayMsg (msg.tunnelID, msg.data));
  247. else
  248. LogPrint (eLogError, "TunnelMessage: Delivery type 'tunnel' arrived from an inbound tunnel, dropped");
  249. break;
  250. case eDeliveryTypeRouter:
  251. if (!m_IsInbound) // outbound transit tunnel
  252. i2p::transport::transports.SendMessage (msg.hash, msg.data);
  253. else // we shouldn't send this message. possible leakage
  254. LogPrint (eLogError, "TunnelMessage: Delivery type 'router' arrived from an inbound tunnel, dropped");
  255. break;
  256. default:
  257. LogPrint (eLogError, "TunnelMessage: Unknown delivery type ", (int)msg.deliveryType);
  258. };
  259. }
  260. void TunnelEndpoint::Cleanup ()
  261. {
  262. auto ts = i2p::util::GetMillisecondsSinceEpoch ();
  263. // out-of-sequence fragments
  264. for (auto it = m_OutOfSequenceFragments.begin (); it != m_OutOfSequenceFragments.end ();)
  265. {
  266. if (ts > it->second.receiveTime + i2p::I2NP_MESSAGE_EXPIRATION_TIMEOUT)
  267. it = m_OutOfSequenceFragments.erase (it);
  268. else
  269. ++it;
  270. }
  271. // incomplete messages
  272. for (auto it = m_IncompleteMessages.begin (); it != m_IncompleteMessages.end ();)
  273. {
  274. if (ts > it->second.receiveTime + i2p::I2NP_MESSAGE_EXPIRATION_TIMEOUT)
  275. it = m_IncompleteMessages.erase (it);
  276. else
  277. ++it;
  278. }
  279. }
  280. }
  281. }