1 // SoftEther VPN Source Code - Stable Edition Repository
2 // Cedar Communication Module
3 //
4 // SoftEther VPN Server, Client and Bridge are free software under the Apache License, Version 2.0.
5 //
6 // Copyright (c) Daiyuu Nobori.
7 // Copyright (c) SoftEther VPN Project, University of Tsukuba, Japan.
8 // Copyright (c) SoftEther Corporation.
9 // Copyright (c) all contributors on SoftEther VPN project in GitHub.
10 //
11 // All Rights Reserved.
12 //
13 // http://www.softether.org/
14 //
15 // This stable branch is officially managed by Daiyuu Nobori, the owner of SoftEther VPN Project.
16 // Pull requests should be sent to the Developer Edition Master Repository on https://github.com/SoftEtherVPN/SoftEtherVPN
17 //
18 // License: The Apache License, Version 2.0
19 // https://www.apache.org/licenses/LICENSE-2.0
20 //
21 // DISCLAIMER
22 // ==========
23 //
24 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
25 // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
26 // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
27 // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
28 // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
29 // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
30 // SOFTWARE.
31 //
32 // THIS SOFTWARE IS DEVELOPED IN JAPAN, AND DISTRIBUTED FROM JAPAN, UNDER
33 // JAPANESE LAWS. YOU MUST AGREE IN ADVANCE TO USE, COPY, MODIFY, MERGE, PUBLISH,
34 // DISTRIBUTE, SUBLICENSE, AND/OR SELL COPIES OF THIS SOFTWARE, THAT ANY
35 // JURIDICAL DISPUTES WHICH ARE CONCERNED TO THIS SOFTWARE OR ITS CONTENTS,
36 // AGAINST US (SOFTETHER PROJECT, SOFTETHER CORPORATION, DAIYUU NOBORI OR OTHER
37 // SUPPLIERS), OR ANY JURIDICAL DISPUTES AGAINST US WHICH ARE CAUSED BY ANY KIND
38 // OF USING, COPYING, MODIFYING, MERGING, PUBLISHING, DISTRIBUTING, SUBLICENSING,
39 // AND/OR SELLING COPIES OF THIS SOFTWARE SHALL BE REGARDED AS BE CONSTRUED AND
40 // CONTROLLED BY JAPANESE LAWS, AND YOU MUST FURTHER CONSENT TO EXCLUSIVE
41 // JURISDICTION AND VENUE IN THE COURTS SITTING IN TOKYO, JAPAN. YOU MUST WAIVE
42 // ALL DEFENSES OF LACK OF PERSONAL JURISDICTION AND FORUM NON CONVENIENS.
43 // PROCESS MAY BE SERVED ON EITHER PARTY IN THE MANNER AUTHORIZED BY APPLICABLE
44 // LAW OR COURT RULE.
45 //
46 // USE ONLY IN JAPAN. DO NOT USE THIS SOFTWARE IN ANOTHER COUNTRY UNLESS YOU HAVE
47 // A CONFIRMATION THAT THIS SOFTWARE DOES NOT VIOLATE ANY CRIMINAL LAWS OR CIVIL
48 // RIGHTS IN THAT PARTICULAR COUNTRY. USING THIS SOFTWARE IN OTHER COUNTRIES IS
49 // COMPLETELY AT YOUR OWN RISK. THE SOFTETHER VPN PROJECT HAS DEVELOPED AND
50 // DISTRIBUTED THIS SOFTWARE TO COMPLY ONLY WITH THE JAPANESE LAWS AND EXISTING
51 // CIVIL RIGHTS INCLUDING PATENTS WHICH ARE SUBJECTS APPLY IN JAPAN. OTHER
52 // COUNTRIES' LAWS OR CIVIL RIGHTS ARE NONE OF OUR CONCERNS NOR RESPONSIBILITIES.
53 // WE HAVE NEVER INVESTIGATED ANY CRIMINAL REGULATIONS, CIVIL LAWS OR
54 // INTELLECTUAL PROPERTY RIGHTS INCLUDING PATENTS IN ANY OF OTHER 200+ COUNTRIES
55 // AND TERRITORIES. BY NATURE, THERE ARE 200+ REGIONS IN THE WORLD, WITH
56 // DIFFERENT LAWS. IT IS IMPOSSIBLE TO VERIFY EVERY COUNTRIES' LAWS, REGULATIONS
57 // AND CIVIL RIGHTS TO MAKE THE SOFTWARE COMPLY WITH ALL COUNTRIES' LAWS BY THE
58 // PROJECT. EVEN IF YOU WILL BE SUED BY A PRIVATE ENTITY OR BE DAMAGED BY A
59 // PUBLIC SERVANT IN YOUR COUNTRY, THE DEVELOPERS OF THIS SOFTWARE WILL NEVER BE
60 // LIABLE TO RECOVER OR COMPENSATE SUCH DAMAGES, CRIMINAL OR CIVIL
61 // RESPONSIBILITIES. NOTE THAT THIS LINE IS NOT LICENSE RESTRICTION BUT JUST A
62 // STATEMENT FOR WARNING AND DISCLAIMER.
63 //
64 // READ AND UNDERSTAND THE 'WARNING.TXT' FILE BEFORE USING THIS SOFTWARE.
65 // SOME SOFTWARE PROGRAMS FROM THIRD PARTIES ARE INCLUDED ON THIS SOFTWARE WITH
66 // LICENSE CONDITIONS WHICH ARE DESCRIBED ON THE 'THIRD_PARTY.TXT' FILE.
67 //
68 //
69 // SOURCE CODE CONTRIBUTION
70 // ------------------------
71 //
72 // Your contribution to SoftEther VPN Project is much appreciated.
73 // Please send patches to us through GitHub.
74 // Read the SoftEther VPN Patch Acceptance Policy in advance:
75 // http://www.softether.org/5-download/src/9.patch
76 //
77 //
78 // DEAR SECURITY EXPERTS
79 // ---------------------
80 //
81 // If you find a bug or a security vulnerability please kindly inform us
82 // about the problem immediately so that we can fix the security problem
83 // to protect a lot of users around the world as soon as possible.
84 //
85 // Our e-mail address for security reports is:
86 // softether-vpn-security [at] softether.org
87 //
88 // Please note that the above e-mail address is not a technical support
89 // inquiry address. If you need technical assistance, please visit
90 // http://www.softether.org/ and ask your question on the users forum.
91 //
92 // Thank you for your cooperation.
93 //
94 //
95 // NO MEMORY OR RESOURCE LEAKS
96 // ---------------------------
97 //
98 // The memory-leaks and resource-leaks verification under the stress
99 // test has been passed before release this source code.
100 
101 
102 // Connection.h
103 // Header of Connection.c
104 
105 #ifndef	CONNECTION_H
106 #define	CONNECTION_H
107 
108 // Magic number indicating that the packet is compressed
109 #define	CONNECTION_BULK_COMPRESS_SIGNATURE	0xDEADBEEFCAFEFACEULL
110 
111 #define	KEEP_ALIVE_STRING				"Internet Connection Keep Alive Packet"
112 
113 #define	UPDATE_LAST_COMM_TIME(v, n)		{if ((v) <= (n)) { v = (n); } }
114 
115 // KEEP CONNECT structure
116 struct KEEP
117 {
118 	LOCK *lock;										// Lock
119 	bool Server;									// Server mode
120 	volatile bool Halt;								// Stop flag
121 	bool Enable;									// Enable flag
122 	char ServerName[MAX_HOST_NAME_LEN + 1];			// Server name
123 	UINT ServerPort;								// Server port number
124 	bool UdpMode;									// UDP mode
125 	UINT Interval;									// Packet transmission interval
126 	THREAD *Thread;									// Connection thread
127 	EVENT *HaltEvent;								// Stop event
128 	CANCEL *Cancel;									// Cancel
129 };
130 
131 // SECURE_SIGN Structure
132 struct SECURE_SIGN
133 {
134 	char SecurePublicCertName[MAX_SECURE_DEVICE_FILE_LEN + 1];	// Secure device certificate name
135 	char SecurePrivateKeyName[MAX_SECURE_DEVICE_FILE_LEN + 1];	// Secure device secret key name
136 	X *ClientCert;					// Client certificate
137 	UCHAR Random[SHA1_SIZE];		// Random value for signature
138 	UCHAR Signature[4096 / 8];		// Signed data
139 	UINT UseSecureDeviceId;
140 	UINT BitmapId;					// Bitmap ID
141 };
142 
143 // Function type declaration
144 typedef bool (CHECK_CERT_PROC)(SESSION *s, CONNECTION *c, X *server_x, bool *expired);
145 typedef bool (SECURE_SIGN_PROC)(SESSION *s, CONNECTION *c, SECURE_SIGN *sign);
146 
147 // RC4 key pair
148 struct RC4_KEY_PAIR
149 {
150 	UCHAR ServerToClientKey[16];
151 	UCHAR ClientToServerKey[16];
152 };
153 
154 // Client Options
155 struct CLIENT_OPTION
156 {
157 	wchar_t AccountName[MAX_ACCOUNT_NAME_LEN + 1];	// Connection setting name
158 	char Hostname[MAX_HOST_NAME_LEN + 1];			// Host name
159 	UINT Port;										// Port number
160 	UINT PortUDP;									// UDP port number (0: Use only TCP)
161 	UINT ProxyType;									// Type of proxy
162 	char ProxyName[MAX_HOST_NAME_LEN + 1];			// Proxy server name
163 	UINT ProxyPort;									// Port number of the proxy server
164 	char ProxyUsername[MAX_PROXY_USERNAME_LEN + 1];	// Maximum user name length
165 	char ProxyPassword[MAX_PROXY_PASSWORD_LEN + 1];	// Maximum password length
166 	UINT NumRetry;									// Automatic retries
167 	UINT RetryInterval;								// Retry interval
168 	char HubName[MAX_HUBNAME_LEN + 1];				// HUB name
169 	UINT MaxConnection;								// Maximum number of concurrent TCP connections
170 	bool UseEncrypt;								// Use encrypted communication
171 	bool UseCompress;								// Use data compression
172 	bool HalfConnection;							// Use half connection in TCP
173 	bool NoRoutingTracking;							// Disable the routing tracking
174 	char DeviceName[MAX_DEVICE_NAME_LEN + 1];		// VLAN device name
175 	UINT AdditionalConnectionInterval;				// Connection attempt interval when additional connection establish
176 	UINT ConnectionDisconnectSpan;					// Disconnection interval
177 	bool HideStatusWindow;							// Hide the status window
178 	bool HideNicInfoWindow;							// Hide the NIC status window
179 	bool RequireMonitorMode;						// Monitor port mode
180 	bool RequireBridgeRoutingMode;					// Bridge or routing mode
181 	bool DisableQoS;								// Disable the VoIP / QoS function
182 	bool FromAdminPack;								// For Administration Pack
183 	bool NoTls1;									// Do not use TLS 1.0
184 	bool NoUdpAcceleration;							// Do not use UDP acceleration mode
185 	UCHAR HostUniqueKey[SHA1_SIZE];					// Host unique key
186 };
187 
188 // Client authentication data
189 struct CLIENT_AUTH
190 {
191 	UINT AuthType;									// Authentication type
192 	char Username[MAX_USERNAME_LEN + 1];			// User name
193 	UCHAR HashedPassword[SHA1_SIZE];				// Hashed passwords
194 	char PlainPassword[MAX_PASSWORD_LEN + 1];		// Password
195 	X *ClientX;										// Client certificate
196 	K *ClientK;										// Client private key
197 	char SecurePublicCertName[MAX_SECURE_DEVICE_FILE_LEN + 1];	// Secure device certificate name
198 	char SecurePrivateKeyName[MAX_SECURE_DEVICE_FILE_LEN + 1];	// Secure device secret key name
199 	CHECK_CERT_PROC *CheckCertProc;					// Server certificate confirmation procedure
200 	SECURE_SIGN_PROC *SecureSignProc;				// Security signing procedure
201 };
202 
203 // TCP socket data structure
204 struct TCPSOCK
205 {
206 	SOCK *Sock;						// Socket
207 	FIFO *RecvFifo;					// Reception buffer
208 	FIFO *SendFifo;					// Transmission buffer
209 	UINT Mode;						// Read mode
210 	UINT WantSize;					// Requested data size
211 	UINT NextBlockNum;				// Total number of blocks that can be read next
212 	UINT NextBlockSize;				// Block size that is planned to read next
213 	UINT CurrentPacketNum;			// Current packet number
214 	UINT64 LastCommTime;			// Last communicated time
215 	UINT64 LastRecvTime;			// Time the last data received
216 	UINT LateCount;					// The number of delay occurences
217 	UINT Direction;					// Direction
218 	UINT64 NextKeepAliveTime;		// Next time to send a KeepAlive packet
219 	RC4_KEY_PAIR Rc4KeyPair;		// RC4 key pair
220 	CRYPT *SendKey;					// Transmission key
221 	CRYPT *RecvKey;					// Reception key
222 	UINT64 DisconnectTick;			// Time to disconnect this connection
223 	UINT64 EstablishedTick;			// Establishment time
224 };
225 
226 // TCP communication data structure
227 struct TCP
228 {
229 	LIST *TcpSockList;				// TCP socket list
230 };
231 
232 // UDP communication data structure
233 struct UDP
234 {
235 	SOCK *s;						// UDP socket (for transmission)
236 	IP ip;							// Destination IP address
237 	UINT port;						// Destination port number
238 	UINT64 NextKeepAliveTime;		// Next time to send a KeepAlive packet
239 	UINT64 Seq;						// Packet sequence number
240 	UINT64 RecvSeq;
241 	QUEUE *BufferQueue;				// Queue of buffer to be sent
242 };
243 
244 // Data block
245 struct BLOCK
246 {
247 	BOOL Compressed;				// Compression flag
248 	UINT Size;						// Block size
249 	UINT SizeofData;				// Data size
250 	UCHAR *Buf;						// Buffer
251 	bool PriorityQoS;				// Priority packet for VoIP / QoS function
252 	UINT Ttl;						// TTL value (Used only in ICMP NAT of Virtual.c)
253 	UINT Param1;					// Parameter 1
254 	bool IsFlooding;				// Is flooding packet
255 	UCHAR RawFlagRetUdpAccel;		// Raw flag returned by UDP accel
256 };
257 
258 // Connection structure
259 struct CONNECTION
260 {
261 	LOCK *lock;						// Lock
262 	REF *ref;						// Reference counter
263 	CEDAR *Cedar;					// Cedar
264 	struct SESSION *Session;		// Session
265 	UINT Protocol;					// Protocol
266 	SOCK *FirstSock;				// Socket for negotiation
267 	SOCK *TubeSock;					// Socket for in-process communication
268 	TCP *Tcp;						// TCP communication data structure
269 	UDP *Udp;						// UDP communication data structure
270 	bool ServerMode;				// Server mode
271 	UINT Status;					// Status
272 	char *Name;						// Connection name
273 	THREAD *Thread;					// Thread
274 	volatile bool Halt;				// Stop flag
275 	UCHAR Random[SHA1_SIZE];		// Random number for Authentication
276 	UINT ServerVer;					// Server version
277 	UINT ServerBuild;				// Server build number
278 	UINT ClientVer;					// Client version
279 	UINT ClientBuild;				// Client build number
280 	char ServerStr[MAX_SERVER_STR_LEN + 1];	// Server string
281 	char ClientStr[MAX_CLIENT_STR_LEN + 1];	// Client string
282 	UINT Err;						// Error value
283 	bool ClientConnectError_NoSavePassword;	// Don't save the password for the specified user name
284 	QUEUE *ReceivedBlocks;			// Block queue that is received
285 	QUEUE *SendBlocks;				// Block queue planned to be sent
286 	QUEUE *SendBlocks2;				// Send queue (high priority)
287 	COUNTER *CurrentNumConnection;	// Counter of the number of current connections
288 	LIST *ConnectingThreads;		// List of connected threads
289 	LIST *ConnectingSocks;			// List of the connected sockets
290 	bool flag1;						// Flag 1
291 	UCHAR *RecvBuf;					// Receive buffer
292 	char ServerName[MAX_HOST_NAME_LEN + 1];	// Server name
293 	UINT ServerPort;				// Port number
294 	bool RestoreServerNameAndPort;	// Flag to restore the  server name and port number to original
295 	bool UseTicket;					// Ticket using flag
296 	UCHAR Ticket[SHA1_SIZE];		// Ticket
297 	UINT CurrentSendQueueSize;		// Total size of the transmission queue
298 	X *ServerX;						// Server certificate
299 	X *ClientX;						// Client certificate
300 	char *CipherName;				// Encryption algorithm name
301 	UINT64 ConnectedTick;			// Time it is connected
302 	IP ClientIp;					// Client IP address
303 	UINT ClientPort;				// Client Port number
304 	char ClientHostname[MAX_HOST_NAME_LEN + 1];	// Client host name
305 	UINT Type;						// Type
306 	bool DontUseTls1;				// Do not use TLS 1.0
307 	void *hWndForUI;				// Parent window
308 	bool IsInProc;					// In-process
309 	char InProcPrefix[64];			// Prefix
310 	UINT InProcLayer;				// InProc layer
311 	UINT AdditionalConnectionFailedCounter;		// Additional connection failure counter
312 	UINT64 LastCounterResetTick;	// Time the counter was reset finally
313 	bool WasSstp;					// Processed the SSTP
314 	bool WasDatProxy;				// DAT proxy processed
315 	UCHAR CToken_Hash[SHA1_SIZE];	// CTOKEN_HASH
316 	UINT LastTcpQueueSize;			// The last queue size of TCP sockets
317 	UINT LastPacketQueueSize;		// The last queue size of packets
318 	UINT LastRecvFifoTotalSize;		// The last RecvFifo total size
319 	UINT LastRecvBlocksNum;			// The last ReceivedBlocks num
320 	bool IsJsonRpc;					// Is JSON-RPC
321 	bool JsonRpcAuthed;				// JSON-RPC Authed
322 	LISTENER *Listener;				// Listener ref
323 };
324 
325 
326 
327 // Function prototypes
328 
329 CONNECTION *NewClientConnection(SESSION *s);
330 CONNECTION *NewClientConnectionEx(SESSION *s, char *client_str, UINT client_ver, UINT client_build);
331 CONNECTION *NewServerConnection(CEDAR *cedar, SOCK *s, THREAD *t);
332 void ReleaseConnection(CONNECTION *c);
333 void CleanupConnection(CONNECTION *c);
334 int CompareConnection(void *p1, void *p2);
335 void StopConnection(CONNECTION *c, bool no_wait);
336 void ConnectionAccept(CONNECTION *c);
337 void StartTunnelingMode(CONNECTION *c);
338 void EndTunnelingMode(CONNECTION *c);
339 void DisconnectTcpSockets(CONNECTION *c);
340 void ConnectionReceive(CONNECTION *c, CANCEL *c1, CANCEL *c2);
341 void ConnectionSend(CONNECTION *c, UINT64 now);
342 TCPSOCK *NewTcpSock(SOCK *s);
343 void FreeTcpSock(TCPSOCK *ts);
344 BLOCK *NewBlock(void *data, UINT size, int compress);
345 void FreeBlock(BLOCK *b);
346 void StopAllAdditionalConnectThread(CONNECTION *c);
347 UINT GenNextKeepAliveSpan(CONNECTION *c);
348 void SendKeepAlive(CONNECTION *c, TCPSOCK *ts);
349 void DisconnectUDPSockets(CONNECTION *c);
350 void PutUDPPacketData(CONNECTION *c, void *data, UINT size);
351 void SendDataWithUDP(SOCK *s, CONNECTION *c);
352 void InsertReveicedBlockToQueue(CONNECTION *c, BLOCK *block, bool no_lock);
353 void InitTcpSockRc4Key(TCPSOCK *ts, bool server_mode);
354 UINT TcpSockRecv(SESSION *s, TCPSOCK *ts, void *data, UINT size);
355 UINT TcpSockSend(SESSION *s, TCPSOCK *ts, void *data, UINT size);
356 void WriteSendFifo(SESSION *s, TCPSOCK *ts, void *data, UINT size);
357 void WriteRecvFifo(SESSION *s, TCPSOCK *ts, void *data, UINT size);
358 CLIENT_AUTH *CopyClientAuth(CLIENT_AUTH *a);
359 BUF *NewKeepPacket(bool server_mode);
360 void KeepThread(THREAD *thread, void *param);
361 KEEP *StartKeep();
362 void StopKeep(KEEP *k);
363 void InRpcSecureSign(SECURE_SIGN *t, PACK *p);
364 void OutRpcSecureSign(PACK *p, SECURE_SIGN *t);
365 void FreeRpcSecureSign(SECURE_SIGN *t);
366 void NormalizeEthMtu(BRIDGE *b, CONNECTION *c, UINT packet_size);
367 UINT GetMachineRand();
368 
369 
370 
371 #endif	// CONNECTION_H
372