1 /*
2 * Copyright (c) 2013-2021, 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 */
9 #ifndef NTCP2_H__
10 #define NTCP2_H__
11 
12 #include <inttypes.h>
13 #include <memory>
14 #include <list>
15 #include <map>
16 #include <array>
17 #include <openssl/bn.h>
18 #include <openssl/evp.h>
19 #include <boost/asio.hpp>
20 #include "Crypto.h"
21 #include "util.h"
22 #include "RouterInfo.h"
23 #include "TransportSession.h"
24 
25 namespace i2p
26 {
27 namespace transport
28 {
29 
30 	const size_t NTCP2_UNENCRYPTED_FRAME_MAX_SIZE = 65519;
31 	const size_t NTCP2_SESSION_REQUEST_MAX_SIZE = 287;
32 	const size_t NTCP2_SESSION_CREATED_MAX_SIZE = 287;
33 	const int NTCP2_MAX_PADDING_RATIO = 6; // in %
34 
35 	const int NTCP2_CONNECT_TIMEOUT = 5; // 5 seconds
36 	const int NTCP2_ESTABLISH_TIMEOUT = 10; // 10 seconds
37 	const int NTCP2_TERMINATION_TIMEOUT = 120; // 2 minutes
38 	const int NTCP2_TERMINATION_CHECK_TIMEOUT = 30; // 30 seconds
39 	const int NTCP2_RECEIVE_BUFFER_DELETION_TIMEOUT = 3; // 3 seconds
40 	const int NTCP2_ROUTERINFO_RESEND_INTERVAL = 25*60; // 25 minuntes in seconds
41 	const int NTCP2_ROUTERINFO_RESEND_INTERVAL_THRESHOLD = 25*60; // 25 minuntes
42 
43 	const int NTCP2_CLOCK_SKEW = 60; // in seconds
44 	const int NTCP2_MAX_OUTGOING_QUEUE_SIZE = 500; // how many messages we can queue up
45 
46 	enum NTCP2BlockType
47 	{
48 		eNTCP2BlkDateTime = 0,
49 		eNTCP2BlkOptions, // 1
50 		eNTCP2BlkRouterInfo, // 2
51 		eNTCP2BlkI2NPMessage, // 3
52 		eNTCP2BlkTermination, // 4
53 		eNTCP2BlkPadding = 254
54 	};
55 
56 	enum NTCP2TerminationReason
57 	{
58 		eNTCP2NormalClose = 0,
59 		eNTCP2TerminationReceived, // 1
60 		eNTCP2IdleTimeout, // 2
61 		eNTCP2RouterShutdown, // 3
62 		eNTCP2DataPhaseAEADFailure, // 4
63 		eNTCP2IncompatibleOptions, // 5
64 		eNTCP2IncompatibleSignatureType, // 6
65 		eNTCP2ClockSkew, // 7
66 		eNTCP2PaddingViolation, // 8
67 		eNTCP2AEADFramingError, // 9
68 		eNTCP2PayloadFormatError, // 10
69 		eNTCP2Message1Error, // 11
70 		eNTCP2Message2Error, // 12
71 		eNTCP2Message3Error, // 13
72 		eNTCP2IntraFrameReadTimeout, // 14
73 		eNTCP2RouterInfoSignatureVerificationFail, // 15
74 		eNTCP2IncorrectSParameter, // 16
75 		eNTCP2Banned, // 17
76 	};
77 
78 	// RouterInfo flags
79 	const uint8_t NTCP2_ROUTER_INFO_FLAG_REQUEST_FLOOD = 0x01;
80 
81 	struct NTCP2Establisher: private i2p::crypto::NoiseSymmetricState
82 	{
83 		NTCP2Establisher ();
84 		~NTCP2Establisher ();
85 
GetPubNTCP2Establisher86 		const uint8_t * GetPub () const { return m_EphemeralKeys->GetPublicKey (); };
GetRemotePubNTCP2Establisher87 		const uint8_t * GetRemotePub () const { return m_RemoteEphemeralPublicKey; }; // Y for Alice and X for Bob
GetRemotePubNTCP2Establisher88 		uint8_t * GetRemotePub () { return m_RemoteEphemeralPublicKey; }; // to set
89 
GetKNTCP2Establisher90 		const uint8_t * GetK () const { return m_CK + 32; };
GetCKNTCP2Establisher91 		const uint8_t * GetCK () const { return m_CK; };
GetHNTCP2Establisher92 		const uint8_t * GetH () const { return m_H; };
93 
94 		void KDF1Alice ();
95 		void KDF1Bob ();
96 		void KDF2Alice ();
97 		void KDF2Bob ();
98 		void KDF3Alice (); // for SessionConfirmed part 2
99 		void KDF3Bob ();
100 
101 		void KeyDerivationFunction1 (const uint8_t * pub, i2p::crypto::X25519Keys& priv, const uint8_t * rs, const uint8_t * epub); // for SessionRequest, (pub, priv) for DH
102 		void KeyDerivationFunction2 (const uint8_t * sessionRequest, size_t sessionRequestLen, const uint8_t * epub); // for SessionCreate
103 		void CreateEphemeralKey ();
104 
105 		void CreateSessionRequestMessage ();
106 		void CreateSessionCreatedMessage ();
107 		void CreateSessionConfirmedMessagePart1 (const uint8_t * nonce);
108 		void CreateSessionConfirmedMessagePart2 (const uint8_t * nonce);
109 
110 		bool ProcessSessionRequestMessage (uint16_t& paddingLen);
111 		bool ProcessSessionCreatedMessage (uint16_t& paddingLen);
112 		bool ProcessSessionConfirmedMessagePart1 (const uint8_t * nonce);
113 		bool ProcessSessionConfirmedMessagePart2 (const uint8_t * nonce, uint8_t * m3p2Buf);
114 
115 		std::shared_ptr<i2p::crypto::X25519Keys> m_EphemeralKeys;
116 		uint8_t m_RemoteEphemeralPublicKey[32]; // x25519
117 		uint8_t m_RemoteStaticKey[32], m_IV[16];
118 		i2p::data::IdentHash m_RemoteIdentHash;
119 		uint16_t m3p2Len;
120 
121 		uint8_t m_SessionRequestBuffer[NTCP2_SESSION_REQUEST_MAX_SIZE],
122 			m_SessionCreatedBuffer[NTCP2_SESSION_CREATED_MAX_SIZE], * m_SessionConfirmedBuffer;
123 		size_t m_SessionRequestBufferLen, m_SessionCreatedBufferLen;
124 
125 	};
126 
127 	class NTCP2Server;
128 	class NTCP2Session: public TransportSession, public std::enable_shared_from_this<NTCP2Session>
129 	{
130 		public:
131 
132 			NTCP2Session (NTCP2Server& server, std::shared_ptr<const i2p::data::RouterInfo> in_RemoteRouter = nullptr,
133 				std::shared_ptr<const i2p::data::RouterInfo::Address> addr = nullptr);
134 			~NTCP2Session ();
135 			void Terminate ();
136 			void TerminateByTimeout ();
137 			void Done ();
Close()138 			void Close () { m_Socket.close (); }; // for accept
139 			void DeleteNextReceiveBuffer (uint64_t ts);
140 
GetSocket()141 			boost::asio::ip::tcp::socket& GetSocket () { return m_Socket; };
GetRemoteEndpoint()142 			const boost::asio::ip::tcp::endpoint& GetRemoteEndpoint () { return m_RemoteEndpoint; };
SetRemoteEndpoint(const boost::asio::ip::tcp::endpoint & ep)143 			void SetRemoteEndpoint (const boost::asio::ip::tcp::endpoint& ep) { m_RemoteEndpoint = ep; };
144 
IsEstablished()145 			bool IsEstablished () const { return m_IsEstablished; };
IsTerminated()146 			bool IsTerminated () const { return m_IsTerminated; };
147 
148 			void ClientLogin (); // Alice
149 			void ServerLogin (); // Bob
150 
151 			void SendLocalRouterInfo (); // after handshake
152 			void SendI2NPMessages (const std::vector<std::shared_ptr<I2NPMessage> >& msgs);
153 
154 		private:
155 
156 			void Established ();
157 
158 			void CreateNonce (uint64_t seqn, uint8_t * nonce);
159 			void CreateNextReceivedBuffer (size_t size);
160 			void KeyDerivationFunctionDataPhase ();
161 			void SetSipKeys (const uint8_t * sendSipKey, const uint8_t * receiveSipKey);
162 
163 			// establish
164 			void SendSessionRequest ();
165 			void SendSessionCreated ();
166 			void SendSessionConfirmed ();
167 
168 			void HandleSessionRequestSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
169 			void HandleSessionRequestReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
170 			void HandleSessionRequestPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
171 			void HandleSessionCreatedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
172 			void HandleSessionCreatedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
173 			void HandleSessionCreatedPaddingReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
174 			void HandleSessionConfirmedSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
175 			void HandleSessionConfirmedReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
176 
177 			// data
178 			void ReceiveLength ();
179 			void HandleReceivedLength (const boost::system::error_code& ecode, std::size_t bytes_transferred);
180 			void Receive ();
181 			void HandleReceived (const boost::system::error_code& ecode, std::size_t bytes_transferred);
182 			void ProcessNextFrame (const uint8_t * frame, size_t len);
183 
184 			void SetNextSentFrameLength (size_t frameLen, uint8_t * lengthBuf);
185 			void SendI2NPMsgs (std::vector<std::shared_ptr<I2NPMessage> >& msgs);
186 			void HandleI2NPMsgsSent (const boost::system::error_code& ecode, std::size_t bytes_transferred, std::vector<std::shared_ptr<I2NPMessage> > msgs);
187 			void EncryptAndSendNextBuffer (size_t payloadLen);
188 			void HandleNextFrameSent (const boost::system::error_code& ecode, std::size_t bytes_transferred);
189 			size_t CreatePaddingBlock (size_t msgLen, uint8_t * buf, size_t len);
190 			void SendQueue ();
191 			void SendRouterInfo ();
192 			void SendTermination (NTCP2TerminationReason reason);
193 			void SendTerminationAndTerminate (NTCP2TerminationReason reason);
194 			void PostI2NPMessages (std::vector<std::shared_ptr<I2NPMessage> > msgs);
195 
196 		private:
197 
198 			NTCP2Server& m_Server;
199 			boost::asio::ip::tcp::socket m_Socket;
200 			boost::asio::ip::tcp::endpoint m_RemoteEndpoint;
201 			bool m_IsEstablished, m_IsTerminated;
202 
203 			std::unique_ptr<NTCP2Establisher> m_Establisher;
204 			// data phase
205 			uint8_t m_Kab[32], m_Kba[32], m_Sipkeysab[32], m_Sipkeysba[32];
206 			const uint8_t * m_SendKey, * m_ReceiveKey;
207 #if OPENSSL_SIPHASH
208 			EVP_MD_CTX * m_SendMDCtx, * m_ReceiveMDCtx;
209 #else
210 			const uint8_t * m_SendSipKey, * m_ReceiveSipKey;
211 #endif
212 			uint16_t m_NextReceivedLen;
213 			uint8_t * m_NextReceivedBuffer, * m_NextSendBuffer;
214 			size_t m_NextReceivedBufferSize;
215 			union
216 			{
217 				uint8_t buf[8];
218 				uint16_t key;
219 			} m_ReceiveIV, m_SendIV;
220 			uint64_t m_ReceiveSequenceNumber, m_SendSequenceNumber;
221 
222 			i2p::I2NPMessagesHandler m_Handler;
223 
224 			bool m_IsSending, m_IsReceiving;
225 			std::list<std::shared_ptr<I2NPMessage> > m_SendQueue;
226 			uint64_t m_NextRouterInfoResendTime; // seconds since epoch
227 
228 			uint16_t m_PaddingSizes[16];
229 			int m_NextPaddingSize;
230 	};
231 
232 	class NTCP2Server: private i2p::util::RunnableServiceWithWork
233 	{
234 		public:
235 
236 			enum ProxyType
237 			{
238 				eNoProxy,
239 				eSocksProxy,
240 				eHTTPProxy
241 			};
242 
243 			NTCP2Server ();
244 			~NTCP2Server ();
245 
246 			void Start ();
247 			void Stop ();
GetService()248 			boost::asio::io_service& GetService () { return GetIOService (); };
249 
250 			bool AddNTCP2Session (std::shared_ptr<NTCP2Session> session, bool incoming = false);
251 			void RemoveNTCP2Session (std::shared_ptr<NTCP2Session> session);
252 			std::shared_ptr<NTCP2Session> FindNTCP2Session (const i2p::data::IdentHash& ident);
253 
254 			void ConnectWithProxy (std::shared_ptr<NTCP2Session> conn);
255 			void Connect(std::shared_ptr<NTCP2Session> conn);
256 
UsingProxy()257 			bool UsingProxy() const { return m_ProxyType != eNoProxy; };
258 			void UseProxy(ProxyType proxy, const std::string& address, uint16_t port, const std::string& user, const std::string& pass);
259 
260 			void SetLocalAddress (const boost::asio::ip::address& localAddress);
261 
262 		private:
263 
264 			void HandleAccept (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error);
265 			void HandleAcceptV6 (std::shared_ptr<NTCP2Session> conn, const boost::system::error_code& error);
266 
267 			void HandleConnect (const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer);
268 			void HandleProxyConnect(const boost::system::error_code& ecode, std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer);
269 			void AfterSocksHandshake(std::shared_ptr<NTCP2Session> conn, std::shared_ptr<boost::asio::deadline_timer> timer);
270 
271 			// timer
272 			void ScheduleTermination ();
273 			void HandleTerminationTimer (const boost::system::error_code& ecode);
274 
275 		private:
276 
277 			boost::asio::deadline_timer m_TerminationTimer;
278 			std::unique_ptr<boost::asio::ip::tcp::acceptor> m_NTCP2Acceptor, m_NTCP2V6Acceptor;
279 			std::map<i2p::data::IdentHash, std::shared_ptr<NTCP2Session> > m_NTCP2Sessions;
280 			std::list<std::shared_ptr<NTCP2Session> > m_PendingIncomingSessions;
281 
282 			ProxyType m_ProxyType;
283 			std::string m_ProxyAddress, m_ProxyAuthorization;
284 			uint16_t m_ProxyPort;
285 			boost::asio::ip::tcp::resolver m_Resolver;
286 			std::unique_ptr<boost::asio::ip::tcp::endpoint> m_ProxyEndpoint;
287 			std::shared_ptr<boost::asio::ip::tcp::endpoint> m_Address4, m_Address6, m_YggdrasilAddress;
288 
289 		public:
290 
291 			// for HTTP/I2PControl
decltype(m_NTCP2Sessions)292 			const decltype(m_NTCP2Sessions)& GetNTCP2Sessions () const { return m_NTCP2Sessions; };
293 	};
294 }
295 }
296 
297 #endif
298