NTCP2.h 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  1. /*
  2. * Copyright (c) 2013-2018, The PurpleI2P Project
  3. *
  4. * This file is part of Purple i2pd project and licensed under BSD3
  5. *
  6. * See full license text in LICENSE file at top of project tree
  7. *
  8. * Kovri go write your own code
  9. *
  10. */
  11. #ifndef NTCP2_H__
  12. #define NTCP2_H__
  13. #include <inttypes.h>
  14. #include <memory>
  15. #include <thread>
  16. #include <list>
  17. #include <map>
  18. #include <array>
  19. #include <openssl/bn.h>
  20. #include <openssl/evp.h>
  21. #include <boost/asio.hpp>
  22. #include "Crypto.h"
  23. #include "util.h"
  24. #include "RouterInfo.h"
  25. #include "TransportSession.h"
  26. namespace i2p
  27. {
  28. namespace transport
  29. {
  30. const size_t NTCP2_UNENCRYPTED_FRAME_MAX_SIZE = 65519;
  31. const int NTCP2_MAX_PADDING_RATIO = 6; // in %
  32. const int NTCP2_CONNECT_TIMEOUT = 5; // 5 seconds
  33. const int NTCP2_ESTABLISH_TIMEOUT = 10; // 10 seconds
  34. const int NTCP2_TERMINATION_TIMEOUT = 120; // 2 minutes
  35. const int NTCP2_TERMINATION_CHECK_TIMEOUT = 30; // 30 seconds
  36. const int NTCP2_CLOCK_SKEW = 60; // in seconds
  37. const int NTCP2_MAX_OUTGOING_QUEUE_SIZE = 500; // how many messages we can queue up
  38. enum NTCP2BlockType
  39. {
  40. eNTCP2BlkDateTime = 0,
  41. eNTCP2BlkOptions, // 1
  42. eNTCP2BlkRouterInfo, // 2
  43. eNTCP2BlkI2NPMessage, // 3
  44. eNTCP2BlkTermination, // 4
  45. eNTCP2BlkPadding = 254
  46. };
  47. enum NTCP2TerminationReason
  48. {
  49. eNTCP2NormalClose = 0,
  50. eNTCP2TerminationReceived, // 1
  51. eNTCP2IdleTimeout, // 2
  52. eNTCP2RouterShutdown, // 3
  53. eNTCP2DataPhaseAEADFailure, // 4
  54. eNTCP2IncompatibleOptions, // 5
  55. eNTCP2IncompatibleSignatureType, // 6
  56. eNTCP2ClockSkew, // 7
  57. eNTCP2PaddingViolation, // 8
  58. eNTCP2AEADFramingError, // 9
  59. eNTCP2PayloadFormatError, // 10
  60. eNTCP2Message1Error, // 11
  61. eNTCP2Message2Error, // 12
  62. eNTCP2Message3Error, // 13
  63. eNTCP2IntraFrameReadTimeout, // 14
  64. eNTCP2RouterInfoSignatureVerificationFail, // 15
  65. eNTCP2IncorrectSParameter, // 16
  66. eNTCP2Banned, // 17
  67. };
  68. // RouterInfo flags
  69. const uint8_t NTCP2_ROUTER_INFO_FLAG_REQUEST_FLOOD = 0x01;
  70. struct NTCP2Establisher
  71. {
  72. NTCP2Establisher ();
  73. ~NTCP2Establisher ();
  74. const uint8_t * GetPub () const { return m_EphemeralKeys.GetPublicKey (); };
  75. const uint8_t * GetRemotePub () const { return m_RemoteEphemeralPublicKey; }; // Y for Alice and X for Bob
  76. uint8_t * GetRemotePub () { return m_RemoteEphemeralPublicKey; }; // to set
  77. const uint8_t * GetK () const { return m_K; };
  78. const uint8_t * GetCK () const { return m_CK; };
  79. const uint8_t * GetH () const { return m_H; };
  80. void KDF1Alice ();
  81. void KDF1Bob ();
  82. void KDF2Alice ();
  83. void KDF2Bob ();
  84. void KDF3Alice (); // for SessionConfirmed part 2
  85. void KDF3Bob ();
  86. void MixKey (const uint8_t * inputKeyMaterial);
  87. void MixHash (const uint8_t * buf, size_t len);
  88. void KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub); // for SessionRequest, (pub, priv) for DH
  89. void KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub); // for SessionCreate
  90. void CreateEphemeralKey ();
  91. void CreateSessionRequestMessage ();
  92. void CreateSessionCreatedMessage ();
  93. void CreateSessionConfirmedMessagePart1 (const uint8_t * nonce);
  94. void CreateSessionConfirmedMessagePart2 (const uint8_t * nonce);
  95. bool ProcessSessionRequestMessage (uint16_t& paddingLen);
  96. bool ProcessSessionCreatedMessage (uint16_t& paddingLen);
  97. bool ProcessSessionConfirmedMessagePart1 (const uint8_t * nonce);
  98. bool ProcessSessionConfirmedMessagePart2 (const uint8_t * nonce, uint8_t * m3p2Buf);
  99. i2p::crypto::X25519Keys m_EphemeralKeys;
  100. uint8_t m_RemoteEphemeralPublicKey[32]; // x25519
  101. uint8_t m_RemoteStaticKey[32], m_IV[16], m_H[32] /*h*/, m_CK[33] /*ck*/, m_K[32] /*k*/;
  102. i2p::data::IdentHash m_RemoteIdentHash;
  103. uint16_t m3p2Len;
  104. uint8_t * m_SessionRequestBuffer, * m_SessionCreatedBuffer, * m_SessionConfirmedBuffer;
  105. size_t m_SessionRequestBufferLen, m_SessionCreatedBufferLen;
  106. };
  107. class NTCP2Server;
  108. class NTCP2Session: public TransportSession, public std::enable_shared_from_this<NTCP2Session>
  109. {
  110. public:
  111. NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter = nullptr);
  112. ~NTCP2Session ();
  113. void Terminate ();
  114. void TerminateByTimeout ();
  115. void Done ();
  116. boost::asio::ip::tcp::socket& GetSocket () { return m_Socket; };
  117. bool IsEstablished () const { return m_IsEstablished; };
  118. bool IsTerminated () const { return m_IsTerminated; };
  119. void ClientLogin (); // Alice
  120. void ServerLogin (); // Bob
  121. void SendLocalRouterInfo (); // after handshake
  122. void SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs);
  123. private:
  124. void Established ();
  125. void CreateNonce (uint64_t seqn, uint8_t * nonce);
  126. void KeyDerivationFunctionDataPhase ();
  127. void SetSipKeys (const uint8_t * sendSipKey, const uint8_t * receiveSipKey);
  128. // establish
  129. void SendSessionRequest ();
  130. void SendSessionCreated ();
  131. void SendSessionConfirmed ();
  132. void HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  133. void HandleSessionRequestReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  134. void HandleSessionRequestPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  135. void HandleSessionCreatedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  136. void HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  137. void HandleSessionCreatedPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  138. void HandleSessionConfirmedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  139. void HandleSessionConfirmedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  140. // data
  141. void ReceiveLength ();
  142. void HandleReceivedLength (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  143. void Receive ();
  144. void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  145. void ProcessNextFrame (const uint8_t * frame, size_t len);
  146. void SetNextSentFrameLength (size_t frameLen, uint8_t * lengthBuf);
  147. void SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs);
  148. void HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs);
  149. void EncryptAndSendNextBuffer (size_t payloadLen);
  150. void HandleNextFrameSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
  151. size_t CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len);
  152. void SendQueue ();
  153. void SendRouterInfo ();
  154. void SendTermination (NTCP2TerminationReason reason);
  155. void SendTerminationAndTerminate (NTCP2TerminationReason reason);
  156. void PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs);
  157. private:
  158. NTCP2Server& m_Server;
  159. boost::asio::ip::tcp::socket m_Socket;
  160. bool m_IsEstablished, m_IsTerminated;
  161. std::unique_ptr<NTCP2Establisher> m_Establisher;
  162. // data phase
  163. uint8_t m_Kab[33], m_Kba[32], m_Sipkeysab[33], m_Sipkeysba[32];
  164. const uint8_t * m_SendKey, * m_ReceiveKey;
  165. #if OPENSSL_SIPHASH
  166. EVP_PKEY * m_SendSipKey, * m_ReceiveSipKey;
  167. EVP_MD_CTX * m_SendMDCtx, * m_ReceiveMDCtx;
  168. #else
  169. const uint8_t * m_SendSipKey, * m_ReceiveSipKey;
  170. #endif
  171. uint16_t m_NextReceivedLen;
  172. uint8_t * m_NextReceivedBuffer, * m_NextSendBuffer;
  173. union
  174. {
  175. uint8_t buf[8];
  176. uint16_t key;
  177. } m_ReceiveIV, m_SendIV;
  178. uint64_t m_ReceiveSequenceNumber, m_SendSequenceNumber;
  179. i2p::I2NPMessagesHandler m_Handler;
  180. bool m_IsSending;
  181. std::list<std::shared_ptr<I2NPMessage> > m_SendQueue;
  182. };
  183. class NTCP2Server
  184. {
  185. public:
  186. NTCP2Server ();
  187. ~NTCP2Server ();
  188. void Start ();
  189. void Stop ();
  190. bool AddNTCP2Session (std::shared_ptr<NTCP2Session> session);
  191. void RemoveNTCP2Session (std::shared_ptr<NTCP2Session> session);
  192. std::shared_ptr<NTCP2Session> FindNTCP2Session (const i2p::data::IdentHash& ident);
  193. boost::asio::io_service& GetService () { return m_Service; };
  194. void Connect(const boost::asio::ip::address & address, uint16_t port, std::shared_ptr<NTCP2Session> conn);
  195. private:
  196. void Run ();
  197. void HandleAccept (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error);
  198. void HandleAcceptV6 (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error);
  199. void HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer);
  200. // timer
  201. void ScheduleTermination ();
  202. void HandleTerminationTimer (const boost::system::error_code& ecode);
  203. private:
  204. bool m_IsRunning;
  205. std::thread * m_Thread;
  206. boost::asio::io_service m_Service;
  207. boost::asio::io_service::work m_Work;
  208. boost::asio::deadline_timer m_TerminationTimer;
  209. std::unique_ptr<boost::asio::ip::tcp::acceptor> m_NTCP2Acceptor, m_NTCP2V6Acceptor;
  210. std::map<i2p::data::IdentHash, std::shared_ptr<NTCP2Session> > m_NTCP2Sessions;
  211. std::list<std::shared_ptr<NTCP2Session> > m_PendingIncomingSessions;
  212. public:
  213. // for HTTP/I2PControl
  214. const decltype(m_NTCP2Sessions)& GetNTCP2Sessions () const { return m_NTCP2Sessions; };
  215. };
  216. }
  217. }
  218. #endif