1/* (c) Magnus Auvinen. See licence.txt in the root of the distribution for more information. */
2/* If you are missing that file, acquire a complete release at teeworlds.com. */
3#include "config.h"
4#include "netban.h"
5#include "network.h"
6
7#include <base/dbg.h>
8#include <base/hash_ctxt.h>
9#include <base/math.h>
10#include <base/net.h>
11#include <base/secure.h>
12#include <base/time.h>
13
14#include <engine/shared/compression.h>
15#include <engine/shared/packer.h>
16#include <engine/shared/protocol.h>
17
18const int g_DummyMapCrc = 0x6AF73DAF;
19const unsigned char g_aDummyMapData[] = {
20 0x44, 0x41, 0x54, 0x41, 0x04, 0x00, 0x00, 0x00, 0x10, 0x01, 0x00, 0x00,
21 0xF4, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x03, 0x00, 0x00, 0x00,
22 0x02, 0x00, 0x00, 0x00, 0xAC, 0x00, 0x00, 0x00, 0x1C, 0x00, 0x00, 0x00,
23 0x04, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00,
24 0x05, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
25 0x00, 0x00, 0x00, 0x00, 0x24, 0x00, 0x00, 0x00, 0x68, 0x00, 0x00, 0x00,
26 0x00, 0x00, 0x00, 0x00, 0x0E, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00,
27 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x04, 0x00, 0x1C, 0x00, 0x00, 0x00,
28 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
29 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
30 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x05, 0x00, 0x3C, 0x00, 0x00, 0x00,
31 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
32 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
33 0x01, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
34 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF,
35 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
36 0x01, 0x00, 0x05, 0x00, 0x3C, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00,
38 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
39 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00, 0xFF, 0x00, 0x00, 0x00,
40 0xFF, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00,
41 0xFF, 0xFF, 0xFF, 0xFF, 0x01, 0x00, 0x00, 0x00, 0x78, 0x9C, 0x63, 0x64,
42 0x60, 0x60, 0x60, 0x44, 0xC2, 0x00, 0x00, 0x38, 0x00, 0x05, 0x78, 0x9C,
43 0x63, 0x64, 0x60, 0x60, 0x60, 0x44, 0xC2, 0x00, 0x00, 0x38, 0x00, 0x05};
44
45bool CNetServer::Open(NETADDR BindAddr, CNetBan *pNetBan, int MaxClients, int MaxClientsPerIp)
46{
47 // zero out the whole structure
48 this->~CNetServer();
49 new(this) CNetServer{};
50
51 // open socket
52 m_Socket = net_udp_create(bindaddr: BindAddr);
53 if(!m_Socket)
54 return false;
55
56 m_Address = BindAddr;
57 m_pNetBan = pNetBan;
58
59 m_MaxClients = std::clamp(val: MaxClients, lo: 1, hi: (int)NET_MAX_CLIENTS);
60 m_MaxClientsPerIp = MaxClientsPerIp;
61
62 m_VConnNum = 0;
63 m_VConnFirst = 0;
64
65 secure_random_fill(bytes: m_aSecurityTokenSeed, length: sizeof(m_aSecurityTokenSeed));
66
67 for(auto &Slot : m_aSlots)
68 Slot.m_Connection.Init(Socket: m_Socket, BlockCloseMsg: true);
69
70 return true;
71}
72
73int CNetServer::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_DELCLIENT pfnDelClient, void *pUser)
74{
75 m_pfnNewClient = pfnNewClient;
76 m_pfnDelClient = pfnDelClient;
77 m_pUser = pUser;
78 return 0;
79}
80
81int CNetServer::SetCallbacks(NETFUNC_NEWCLIENT pfnNewClient, NETFUNC_NEWCLIENT_NOAUTH pfnNewClientNoAuth, NETFUNC_CLIENTREJOIN pfnClientRejoin, NETFUNC_DELCLIENT pfnDelClient, void *pUser)
82{
83 m_pfnNewClient = pfnNewClient;
84 m_pfnNewClientNoAuth = pfnNewClientNoAuth;
85 m_pfnClientRejoin = pfnClientRejoin;
86 m_pfnDelClient = pfnDelClient;
87 m_pUser = pUser;
88 return 0;
89}
90
91void CNetServer::Close()
92{
93 if(!m_Socket)
94 {
95 return;
96 }
97 net_udp_close(sock: m_Socket);
98 m_Socket = nullptr;
99}
100
101void CNetServer::Drop(int ClientId, const char *pReason)
102{
103 // TODO: insert lots of checks here
104
105 if(m_pfnDelClient)
106 m_pfnDelClient(ClientId, pReason, m_pUser);
107
108 m_aSlots[ClientId].m_Connection.Disconnect(pReason);
109}
110
111void CNetServer::Update()
112{
113 m_NumRecvPackets = 0;
114
115 const int64_t Now = time_get();
116 if(Now > m_BudgetStart + time_freq())
117 {
118 m_BudgetStart = Now;
119 m_NumPreConnDecompress = 0;
120 m_NumBanReplies = 0;
121 }
122
123 for(int i = 0; i < MaxClients(); i++)
124 {
125 m_aSlots[i].m_Connection.Update();
126 if(m_aSlots[i].m_Connection.State() == CNetConnection::EState::ERROR &&
127 (!m_aSlots[i].m_Connection.m_TimeoutProtected ||
128 !m_aSlots[i].m_Connection.m_TimeoutSituation))
129 {
130 Drop(ClientId: i, pReason: m_aSlots[i].m_Connection.ErrorString());
131 }
132 }
133}
134
135void CNetServer::EndFlushBatch()
136{
137 m_FlushBatch = false;
138 for(int ClientId = 0; ClientId < MaxClients(); ClientId++)
139 {
140 if(!m_aFlushPending[ClientId])
141 continue;
142 m_aFlushPending[ClientId] = false;
143 if(m_aSlots[ClientId].m_Connection.State() == CNetConnection::EState::ONLINE)
144 m_aSlots[ClientId].m_Connection.Flush();
145 }
146}
147
148SECURITY_TOKEN CNetServer::GetGlobalToken()
149{
150 static const NETADDR NULL_ADDR = {.type: 0};
151 return GetToken(Addr: NULL_ADDR);
152}
153SECURITY_TOKEN CNetServer::GetToken(const NETADDR &Addr)
154{
155 SHA256_CTX Sha256;
156 sha256_init(ctxt: &Sha256);
157 sha256_update(ctxt: &Sha256, data: (unsigned char *)m_aSecurityTokenSeed, data_len: sizeof(m_aSecurityTokenSeed));
158 sha256_update(ctxt: &Sha256, data: (unsigned char *)&Addr, data_len: 20); // omit port, bad idea!
159
160 SECURITY_TOKEN SecurityToken = ToSecurityToken(pData: sha256_finish(ctxt: &Sha256).data);
161
162 if(SecurityToken == NET_SECURITY_TOKEN_UNKNOWN ||
163 SecurityToken == NET_SECURITY_TOKEN_UNSUPPORTED)
164 SecurityToken = 1;
165
166 return SecurityToken;
167}
168
169SECURITY_TOKEN CNetServer::GetVanillaToken(const NETADDR &Addr)
170{
171 // vanilla token/gametick shouldn't be negative
172 return absolute(a: GetToken(Addr));
173}
174
175void CNetServer::SendControl(NETADDR &Addr, int ControlMsg, const void *pExtra, int ExtraSize, SECURITY_TOKEN SecurityToken)
176{
177 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg, pExtra, ExtraSize, SecurityToken);
178}
179
180int CNetServer::NumClientsWithAddr(NETADDR Addr)
181{
182 int FoundAddr = 0;
183 for(int i = 0; i < MaxClients(); ++i)
184 {
185 if(m_aSlots[i].m_Connection.State() == CNetConnection::EState::OFFLINE ||
186 (m_aSlots[i].m_Connection.State() == CNetConnection::EState::ERROR &&
187 (!m_aSlots[i].m_Connection.m_TimeoutProtected ||
188 !m_aSlots[i].m_Connection.m_TimeoutSituation)))
189 continue;
190
191 if(!net_addr_comp_noport(a: &Addr, b: m_aSlots[i].m_Connection.PeerAddress()))
192 FoundAddr++;
193 }
194
195 return FoundAddr;
196}
197
198bool CNetServer::HasTimedOutClientWithAddr(NETADDR Addr)
199{
200 for(int i = 0; i < MaxClients(); ++i)
201 {
202 if(m_aSlots[i].m_Connection.State() == CNetConnection::EState::ERROR &&
203 m_aSlots[i].m_Connection.m_TimeoutProtected &&
204 m_aSlots[i].m_Connection.m_TimeoutSituation &&
205 !net_addr_comp_noport(a: &Addr, b: m_aSlots[i].m_Connection.PeerAddress()))
206 {
207 return true;
208 }
209 }
210 return false;
211}
212
213bool CNetServer::Connlimit(NETADDR Addr)
214{
215 int64_t Now = time_get();
216 int Oldest = 0;
217
218 for(int i = 0; i < NET_CONNLIMIT_IPS; ++i)
219 {
220 if(!net_addr_comp_noport(a: &m_aSpamConns[i].m_Addr, b: &Addr))
221 {
222 m_aSpamConns[i].m_LastSeen = Now;
223 if(m_aSpamConns[i].m_Time > Now - time_freq() * g_Config.m_SvConnlimitTime)
224 {
225 if(m_aSpamConns[i].m_Conns >= g_Config.m_SvConnlimit)
226 return true;
227 }
228 else
229 {
230 m_aSpamConns[i].m_Time = Now;
231 m_aSpamConns[i].m_Conns = 0;
232 }
233 m_aSpamConns[i].m_Conns++;
234 return false;
235 }
236
237 if(m_aSpamConns[i].m_LastSeen < m_aSpamConns[Oldest].m_LastSeen)
238 Oldest = i;
239 }
240
241 m_aSpamConns[Oldest].m_Addr = Addr;
242 m_aSpamConns[Oldest].m_Time = Now;
243 m_aSpamConns[Oldest].m_LastSeen = Now;
244 m_aSpamConns[Oldest].m_Conns = 1;
245 return false;
246}
247
248int CNetServer::TryAcceptClient(NETADDR &Addr, SECURITY_TOKEN SecurityToken, int Slot, bool VanillaAuth, bool Sixup, SECURITY_TOKEN Token)
249{
250 if(Sixup && !g_Config.m_SvSixup)
251 {
252 const char aMsg[] = "0.7 connections are not accepted at this time";
253 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: NET_CTRLMSG_CLOSE, pExtra: aMsg, ExtraSize: sizeof(aMsg), SecurityToken, Sixup);
254 return -1; // failed to add client?
255 }
256
257 const bool Reconnect = Slot != -1;
258
259 if(Connlimit(Addr))
260 {
261 if(!Reconnect)
262 {
263 const char aMsg[] = "Too many connections in a short time";
264 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: NET_CTRLMSG_CLOSE, pExtra: aMsg, ExtraSize: sizeof(aMsg), SecurityToken, Sixup);
265 }
266 return -1; // failed to add client
267 }
268
269 if(Reconnect)
270 {
271 if(g_Config.m_Debug)
272 dbg_msg(sys: "security", fmt: "client %d reconnect", Slot);
273 }
274 else
275 {
276 // check for sv_max_clients_per_ip
277 if(NumClientsWithAddr(Addr) + 1 > m_MaxClientsPerIp + (HasTimedOutClientWithAddr(Addr) ? 1 : 0))
278 {
279 char aBuf[128];
280 str_format(buffer: aBuf, buffer_size: sizeof(aBuf), format: "Only %d players with the same IP are allowed", m_MaxClientsPerIp);
281 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: NET_CTRLMSG_CLOSE, pExtra: aBuf, ExtraSize: str_length(str: aBuf) + 1, SecurityToken, Sixup);
282 return -1; // failed to add client
283 }
284
285 Slot = -1;
286 for(int i = 0; i < MaxClients(); i++)
287 {
288 if(m_aSlots[i].m_Connection.State() == CNetConnection::EState::OFFLINE)
289 {
290 Slot = i;
291 break;
292 }
293 }
294
295 if(Slot == -1)
296 {
297 const char aFullMsg[] = "This server is full";
298 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: NET_CTRLMSG_CLOSE, pExtra: aFullMsg, ExtraSize: sizeof(aFullMsg), SecurityToken, Sixup);
299
300 return -1; // failed to add client
301 }
302 }
303
304 // init connection slot
305 m_aSlots[Slot].m_Connection.DirectInit(Addr, SecurityToken, Token, Sixup);
306
307 if(VanillaAuth)
308 {
309 // client sequence is unknown if the auth was done
310 // connection-less
311 m_aSlots[Slot].m_Connection.SetUnknownSeq();
312 // correct sequence
313 m_aSlots[Slot].m_Connection.SetSequence(6);
314 }
315
316 if(g_Config.m_Debug)
317 {
318 dbg_msg(sys: "security", fmt: "client accepted %s", m_aSlots[Slot].m_Connection.PeerAddressString(IncludePort: true).data());
319 }
320
321 if(Reconnect)
322 m_pfnClientRejoin(Slot, m_pUser, Sixup, VanillaAuth);
323 else if(VanillaAuth)
324 m_pfnNewClientNoAuth(Slot, m_pUser);
325 else
326 m_pfnNewClient(Slot, m_pUser, Sixup);
327
328 return Slot; // done
329}
330
331void CNetServer::SendMsgs(NETADDR &Addr, const CPacker **ppMsgs, int Num)
332{
333 dbg_assert(Num > 0 && Num <= NET_MAX_PACKET_CHUNKS, "Number of messages invalid: %d", Num);
334
335 CNetPacketConstruct Construct;
336 mem_zero(block: &Construct, size: sizeof(Construct));
337 unsigned char *pChunkData = &Construct.m_aChunkData[Construct.m_DataSize];
338
339 for(int i = 0; i < Num; i++)
340 {
341 const CPacker *pMsg = ppMsgs[i];
342 CNetChunkHeader Header;
343 Header.m_Flags = NET_CHUNKFLAG_VITAL;
344 Header.m_Size = pMsg->Size();
345 Header.m_Sequence = i + 1;
346 pChunkData = Header.Pack(pData: pChunkData);
347 mem_copy(dest: pChunkData, source: pMsg->Data(), size: pMsg->Size());
348 pChunkData += pMsg->Size();
349 Construct.m_NumChunks++;
350 }
351
352 Construct.m_DataSize = (int)(pChunkData - Construct.m_aChunkData);
353 CNetBase::SendPacket(Socket: m_Socket, pAddr: &Addr, pPacket: &Construct, SecurityToken: NET_SECURITY_TOKEN_UNSUPPORTED);
354}
355
356// connection-less msg packet without token-support
357void CNetServer::OnPreConnMsg(NETADDR &Addr, CNetPacketConstruct &Packet, int Slot)
358{
359 bool IsCtrl = Packet.m_Flags & NET_PACKETFLAG_CONTROL;
360 int CtrlMsg = Packet.m_aChunkData[0];
361 const bool NewAuthOrRejoin = Slot == -1 || m_aSlots[Slot].m_Connection.SecurityToken() == NET_SECURITY_TOKEN_UNKNOWN ||
362 (IsCtrl && m_aSlots[Slot].m_Connection.SecurityToken() == NET_SECURITY_TOKEN_UNSUPPORTED);
363 if(!NewAuthOrRejoin)
364 return;
365
366 if(IsCtrl && CtrlMsg == NET_CTRLMSG_CONNECT)
367 {
368 if(g_Config.m_SvVanillaAntiSpoof && g_Config.m_Password[0] == '\0')
369 {
370 const int64_t Now = time_get();
371 if(Now > m_VConnFirst + time_freq())
372 {
373 m_VConnFirst = Now;
374 m_VConnNum = 0;
375 }
376 m_VConnNum++;
377
378 // The handshake below goes to an address that is not verified yet and is
379 // larger than the connect asking for it.
380 if(g_Config.m_SvVanConnRepliesPerSecond != 0 &&
381 m_VConnNum > g_Config.m_SvVanConnRepliesPerSecond)
382 {
383 return;
384 }
385
386 // detect flooding
387 const bool Flooding = g_Config.m_SvVanConnPerSecond != 0 &&
388 m_VConnNum > g_Config.m_SvVanConnPerSecond;
389 if(g_Config.m_Debug && Flooding)
390 {
391 dbg_msg(sys: "security", fmt: "vanilla connection flooding detected");
392 }
393
394 if(Slot != -1)
395 {
396 if(g_Config.m_Debug)
397 dbg_msg(sys: "security", fmt: "client %d wants to reconnect (vanilla)", Slot);
398
399 // Invalidate token for this connection to accept token in `NETMSG_INPUT` later
400 m_aSlots[Slot].m_Connection.m_SecurityToken = NET_SECURITY_TOKEN_UNKNOWN;
401 }
402
403 // simulate accept
404 SendControl(Addr, ControlMsg: NET_CTRLMSG_CONNECTACCEPT, pExtra: nullptr, ExtraSize: 0, SecurityToken: NET_SECURITY_TOKEN_UNSUPPORTED);
405
406 // Begin vanilla compatible token handshake
407 // The idea is to pack a security token in the gametick
408 // parameter of NETMSG_SNAPEMPTY. The Client then will
409 // return the token/gametick in NETMSG_INPUT, allowing
410 // us to validate the token.
411 // https://github.com/eeeee/ddnet/commit/b8e40a244af4e242dc568aa34854c5754c75a39a
412
413 // Before we can send NETMSG_SNAPEMPTY, the client needs
414 // to load a map, otherwise it might crash. The map
415 // should be as small as is possible and directly available
416 // to the client. Therefore a dummy map is sent in the same
417 // packet. To reduce the traffic we'll fallback to a default
418 // map if there are too many connection attempts at once.
419
420 // send mapchange + map data + con_ready + 3 x empty snap (with token)
421 CPacker MapChangeMsg;
422 MapChangeMsg.Reset();
423 MapChangeMsg.AddInt(i: (NETMSG_MAP_CHANGE << 1) | 1);
424 if(Flooding)
425 {
426 // Fallback to dm1
427 MapChangeMsg.AddString(pStr: "dm1", Limit: 0);
428 MapChangeMsg.AddInt(i: 0xf2159e6e);
429 MapChangeMsg.AddInt(i: 5805);
430 }
431 else
432 {
433 // dummy map
434 MapChangeMsg.AddString(pStr: "dummy", Limit: 0);
435 MapChangeMsg.AddInt(i: g_DummyMapCrc);
436 MapChangeMsg.AddInt(i: sizeof(g_aDummyMapData));
437 }
438
439 CPacker MapDataMsg;
440 MapDataMsg.Reset();
441 MapDataMsg.AddInt(i: (NETMSG_MAP_DATA << 1) | 1);
442 if(Flooding)
443 {
444 // send empty map data to keep 0.6.4 support
445 MapDataMsg.AddInt(i: 1); // last chunk
446 MapDataMsg.AddInt(i: 0); // crc
447 MapDataMsg.AddInt(i: 0); // chunk index
448 MapDataMsg.AddInt(i: 0); // map size
449 // no map data
450 }
451 else
452 {
453 // send dummy map data
454 MapDataMsg.AddInt(i: 1); // last chunk
455 MapDataMsg.AddInt(i: g_DummyMapCrc); // crc
456 MapDataMsg.AddInt(i: 0); // chunk index
457 MapDataMsg.AddInt(i: sizeof(g_aDummyMapData)); // map size
458 MapDataMsg.AddRaw(pData: g_aDummyMapData, Size: sizeof(g_aDummyMapData)); // map data
459 }
460
461 CPacker ConReadyMsg;
462 ConReadyMsg.Reset();
463 ConReadyMsg.AddInt(i: (NETMSG_CON_READY << 1) | 1);
464
465 CPacker SnapEmptyMsg;
466 SnapEmptyMsg.Reset();
467 SnapEmptyMsg.AddInt(i: (NETMSG_SNAPEMPTY << 1) | 1);
468 SECURITY_TOKEN SecurityToken = GetVanillaToken(Addr);
469 SnapEmptyMsg.AddInt(i: SecurityToken);
470 SnapEmptyMsg.AddInt(i: SecurityToken + 1);
471
472 // send all chunks/msgs in one packet
473 const CPacker *apMsgs[] = {&MapChangeMsg, &MapDataMsg, &ConReadyMsg,
474 &SnapEmptyMsg, &SnapEmptyMsg, &SnapEmptyMsg};
475 SendMsgs(Addr, ppMsgs: apMsgs, Num: std::size(apMsgs));
476 }
477 else
478 {
479 // accept client directly
480 SendControl(Addr, ControlMsg: NET_CTRLMSG_CONNECTACCEPT, pExtra: nullptr, ExtraSize: 0, SecurityToken: NET_SECURITY_TOKEN_UNSUPPORTED);
481
482 TryAcceptClient(Addr, SecurityToken: NET_SECURITY_TOKEN_UNSUPPORTED, Slot);
483 }
484 }
485 else if(!IsCtrl && g_Config.m_SvVanillaAntiSpoof && g_Config.m_Password[0] == '\0')
486 {
487 // the chunk header is two bytes, three for vital chunks
488 if(Packet.m_DataSize < 2)
489 {
490 return;
491 }
492 CNetChunkHeader Header;
493 unsigned char *pData = Header.Unpack(pData: Packet.m_aChunkData);
494 const int Remaining = Packet.m_DataSize - (int)(pData - Packet.m_aChunkData);
495 if(Remaining < 0)
496 {
497 return;
498 }
499 CUnpacker Unpacker;
500 Unpacker.Reset(pData, Size: std::min(a: Header.m_Size, b: Remaining));
501 int Msg = Unpacker.GetInt() >> 1;
502
503 if(Msg == NETMSG_INPUT)
504 {
505 SECURITY_TOKEN SecurityToken = Unpacker.GetInt();
506 if(SecurityToken == GetVanillaToken(Addr))
507 {
508 if(g_Config.m_Debug)
509 dbg_msg(sys: "security", fmt: "new client (vanilla handshake)");
510 // try to accept client skipping auth state
511 TryAcceptClient(Addr, SecurityToken: NET_SECURITY_TOKEN_UNSUPPORTED, Slot, VanillaAuth: true);
512 }
513 else if(g_Config.m_Debug)
514 {
515 dbg_msg(sys: "security", fmt: "invalid token (vanilla handshake)");
516 }
517 }
518 else
519 {
520 if(g_Config.m_Debug)
521 {
522 dbg_msg(sys: "security", fmt: "invalid preconn msg %d", Msg);
523 }
524 }
525 }
526}
527
528void CNetServer::OnTokenCtrlMsg(NETADDR &Addr, int ControlMsg, const CNetPacketConstruct &Packet, int Slot)
529{
530 if(ControlMsg == NET_CTRLMSG_CONNECT)
531 {
532 // response connection request with token
533 SECURITY_TOKEN Token = GetToken(Addr);
534 SendControl(Addr, ControlMsg: NET_CTRLMSG_CONNECTACCEPT, pExtra: SECURITY_TOKEN_MAGIC, ExtraSize: sizeof(SECURITY_TOKEN_MAGIC), SecurityToken: Token);
535
536 if(g_Config.m_Debug && Slot != -1)
537 dbg_msg(sys: "security", fmt: "client %d wants to reconnect (ddnet)", Slot);
538 }
539 else if(ControlMsg == NET_CTRLMSG_ACCEPT)
540 {
541 SECURITY_TOKEN Token = ToSecurityToken(pData: &Packet.m_aChunkData[1]);
542 if(Token == GetToken(Addr))
543 {
544 // correct token
545 // try to accept client
546 if(g_Config.m_Debug)
547 dbg_msg(sys: "security", fmt: "new client (ddnet token)");
548 TryAcceptClient(Addr, SecurityToken: Token, Slot);
549 }
550 else
551 {
552 // invalid token
553 if(g_Config.m_Debug)
554 dbg_msg(sys: "security", fmt: "invalid token");
555 }
556 }
557}
558
559int CNetServer::OnSixupCtrlMsg(NETADDR &Addr, CNetChunk *pChunk, int ControlMsg, const CNetPacketConstruct &Packet, SECURITY_TOKEN &ResponseToken, SECURITY_TOKEN Token, int Slot)
560{
561 if(Packet.m_DataSize < 1 + (int)sizeof(SECURITY_TOKEN))
562 return 0; // silently ignore
563
564 ResponseToken = ToSecurityToken(pData: Packet.m_aChunkData + 1);
565
566 if(ControlMsg == protocol7::NET_CTRLMSG_TOKEN)
567 {
568 if(g_Config.m_Debug && Slot != -1)
569 dbg_msg(sys: "security", fmt: "client %d wants to reconnect (0.7)", Slot);
570
571 if(Packet.m_DataSize >= (int)NET_TOKENREQUEST_DATASIZE)
572 {
573 SendTokenSixup(Addr, Token: ResponseToken);
574 return 0;
575 }
576
577 // Is this behaviour safe to rely on?
578 pChunk->m_Flags = 0;
579 pChunk->m_ClientId = -1;
580 pChunk->m_Address = Addr;
581 pChunk->m_DataSize = 0;
582 return 1;
583 }
584 else if(ControlMsg == NET_CTRLMSG_CONNECT)
585 {
586 SECURITY_TOKEN MyToken = GetToken(Addr);
587 unsigned char aToken[sizeof(SECURITY_TOKEN)];
588 mem_copy(dest: aToken, source: &MyToken, size: sizeof(aToken));
589
590 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: NET_CTRLMSG_CONNECTACCEPT, pExtra: aToken, ExtraSize: sizeof(aToken), SecurityToken: ResponseToken, Sixup: true);
591 if(Token == MyToken)
592 TryAcceptClient(Addr, SecurityToken: ResponseToken, Slot, VanillaAuth: false, Sixup: true, Token);
593 }
594
595 return 0;
596}
597
598int CNetServer::GetClientSlot(const NETADDR &Addr)
599{
600 for(int i = 0; i < MaxClients(); i++)
601 {
602 if(m_aSlots[i].m_Connection.State() != CNetConnection::EState::OFFLINE &&
603 m_aSlots[i].m_Connection.State() != CNetConnection::EState::ERROR &&
604 net_addr_comp(a: m_aSlots[i].m_Connection.PeerAddress(), b: &Addr) == 0)
605 {
606 return i;
607 }
608 }
609 return -1;
610}
611
612static bool IsDDNetControlMsg(const CNetPacketConstruct *pPacket)
613{
614 if(!(pPacket->m_Flags & NET_PACKETFLAG_CONTROL) || pPacket->m_DataSize < 1)
615 {
616 return false;
617 }
618 if(pPacket->m_aChunkData[0] == NET_CTRLMSG_CONNECT && pPacket->m_DataSize >= (int)(1 + sizeof(SECURITY_TOKEN_MAGIC) + sizeof(SECURITY_TOKEN)) && mem_comp(a: &pPacket->m_aChunkData[1], b: SECURITY_TOKEN_MAGIC, size: sizeof(SECURITY_TOKEN_MAGIC)) == 0)
619 {
620 // DDNet CONNECT
621 return true;
622 }
623 if(pPacket->m_aChunkData[0] == NET_CTRLMSG_ACCEPT && pPacket->m_DataSize >= 1 + (int)sizeof(SECURITY_TOKEN))
624 {
625 // DDNet ACCEPT
626 return true;
627 }
628 return false;
629}
630
631/*
632 TODO: chopp up this function into smaller working parts
633*/
634int CNetServer::Recv(CNetChunk *pChunk, SECURITY_TOKEN *pResponseToken)
635{
636 while(true)
637 {
638 // Unpack next chunk from stored packet if available
639 if(m_PacketChunkUnpacker.UnpackNextChunk(pChunk))
640 {
641 // Only return the pending packet if the client is
642 // still available, the caller might have dropped them
643 // in response to the previous chunk.
644 if(m_aSlots[pChunk->m_ClientId].m_Connection.State() != CNetConnection::EState::OFFLINE)
645 {
646 return 1;
647 }
648 else
649 {
650 m_PacketChunkUnpacker.Reset();
651 }
652 }
653
654 // Stop draining the socket once this batch's budget is used up, otherwise traffic
655 // arriving faster than it can be processed keeps this loop from ever returning.
656 if(g_Config.m_SvMaxPacketsPerRecv != 0 && m_NumRecvPackets >= g_Config.m_SvMaxPacketsPerRecv)
657 {
658 break;
659 }
660
661 // TODO: empty the recvinfo
662 NETADDR Addr;
663 unsigned char *pData;
664 int Bytes = net_udp_recv(sock: m_Socket, addr: &Addr, data: &pData);
665
666 // no more packets for now
667 if(Bytes <= 0)
668 break;
669 m_NumRecvPackets++;
670
671 // check if we just should drop the packet
672 char aBuf[128];
673 if(NetBan() && NetBan()->IsBanned(pOrigAddr: &Addr, pBuf: aBuf, BufferSize: sizeof(aBuf)))
674 {
675 // Banned, reply with a message. Rate limited, unlimited replies would
676 // make a banned flooder cost more to handle than an unbanned one.
677 if(g_Config.m_SvBanRepliesPerSecond == 0 || m_NumBanReplies < g_Config.m_SvBanRepliesPerSecond)
678 {
679 m_NumBanReplies++;
680 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: NET_CTRLMSG_CLOSE, pExtra: aBuf, ExtraSize: str_length(str: aBuf) + 1, SecurityToken: NET_SECURITY_TOKEN_UNSUPPORTED);
681 }
682 continue;
683 }
684
685 // Check size and unpack packet flags early so we can determine the sixup
686 // state correctly for connection-oriented packets before unpacking them.
687 std::optional<int> Flags = CNetBase::UnpackPacketFlags(pBuffer: pData, Size: Bytes);
688 if(!Flags)
689 {
690 continue;
691 }
692
693 SECURITY_TOKEN Token;
694 int Slot = (*Flags & NET_PACKETFLAG_CONNLESS) == 0 ? GetClientSlot(Addr) : -1;
695 bool Sixup = Slot != -1 && m_aSlots[Slot].m_Connection.m_Sixup;
696
697 // Decompressing costs far more than everything else done per packet, so only do it
698 // for packets that can still turn out to be authentic. In 0.7 the security token is
699 // in the packet header and is compared first. In 0.6 it is inside the payload, so
700 // packets from addresses without a connection can only be attributed after decoding;
701 // the vanilla anti-spoof handshake is the only legitimate one and gets a budget.
702 bool AllowDecompression;
703 if(Slot == -1)
704 {
705 AllowDecompression =
706 g_Config.m_SvVanillaAntiSpoof &&
707 g_Config.m_Password[0] == '\0' &&
708 (g_Config.m_SvPreConnDecompressPerSecond == 0 ||
709 m_NumPreConnDecompress < g_Config.m_SvPreConnDecompressPerSecond);
710 }
711 else if(Sixup)
712 {
713 AllowDecompression =
714 Bytes >= NET_PACKETHEADERSIZE + (int)sizeof(SECURITY_TOKEN) &&
715 ToSecurityToken(pData: pData + NET_PACKETHEADERSIZE) == m_aSlots[Slot].m_Connection.m_Token;
716 }
717 else
718 {
719 AllowDecompression = true;
720 }
721
722 bool Decompressed = false;
723 const int UnpackResult = CNetBase::UnpackPacket(pBuffer: pData, Size: Bytes, pPacket: &m_RecvBuffer, Sixup, AllowDecompression, pSecurityToken: &Token, pResponseToken, pDecompressed: &Decompressed);
724 if(Slot == -1 && Decompressed)
725 {
726 m_NumPreConnDecompress++;
727 }
728
729 if(UnpackResult != 0)
730 {
731 continue;
732 }
733
734 if(m_RecvBuffer.m_Flags & NET_PACKETFLAG_CONNLESS)
735 {
736 if(Sixup && Token != GetToken(Addr) && Token != GetGlobalToken())
737 {
738 continue;
739 }
740
741 pChunk->m_Flags = NETSENDFLAG_CONNLESS;
742 pChunk->m_ClientId = -1;
743 pChunk->m_Address = Addr;
744 pChunk->m_DataSize = m_RecvBuffer.m_DataSize;
745 pChunk->m_pData = m_RecvBuffer.m_aChunkData;
746 if(m_RecvBuffer.m_Flags & NET_PACKETFLAG_EXTENDED)
747 {
748 pChunk->m_Flags |= NETSENDFLAG_EXTENDED;
749 mem_copy(dest: pChunk->m_aExtraData, source: m_RecvBuffer.m_aExtraData, size: sizeof(pChunk->m_aExtraData));
750 }
751 return 1;
752 }
753 else // connection-oriented packet
754 {
755 const bool Control = (m_RecvBuffer.m_Flags & NET_PACKETFLAG_CONTROL) != 0;
756 if(Sixup && Control)
757 {
758 // got 0.7 control msg
759 if(OnSixupCtrlMsg(Addr, pChunk, ControlMsg: m_RecvBuffer.m_aChunkData[0], Packet: m_RecvBuffer, ResponseToken&: *pResponseToken, Token, Slot) == 1)
760 return 1;
761 }
762 else if(IsDDNetControlMsg(pPacket: &m_RecvBuffer) && Control)
763 {
764 // got ddnet control msg
765 OnTokenCtrlMsg(Addr, ControlMsg: m_RecvBuffer.m_aChunkData[0], Packet: m_RecvBuffer, Slot);
766 }
767 else
768 {
769 // got connection-less ctrl or sys msg
770 OnPreConnMsg(Addr, Packet&: m_RecvBuffer, Slot);
771 }
772
773 if(Slot != -1 && m_aSlots[Slot].m_Connection.Feed(pPacket: &m_RecvBuffer, pAddr: &Addr, SecurityToken: Token, ResponseToken: *pResponseToken))
774 {
775 if(!Control && m_RecvBuffer.m_DataSize > 0 && m_RecvBuffer.m_NumChunks > 0)
776 {
777 m_PacketChunkUnpacker.FeedPacket(Addr, Packet: m_RecvBuffer, pConnection: &m_aSlots[Slot].m_Connection, ClientId: Slot);
778 }
779 }
780 }
781 }
782 return 0;
783}
784
785int CNetServer::Send(CNetChunk *pChunk)
786{
787 pChunk->AssertSizeSanity();
788
789 if(pChunk->m_Flags & NETSENDFLAG_CONNLESS)
790 {
791 // send connectionless packet
792 CNetBase::SendPacketConnless(Socket: m_Socket, pAddr: &pChunk->m_Address, pData: pChunk->m_pData, DataSize: pChunk->m_DataSize,
793 Extended: pChunk->m_Flags & NETSENDFLAG_EXTENDED, aExtra: pChunk->m_aExtraData);
794 }
795 else
796 {
797 int Flags = 0;
798 dbg_assert(
799 pChunk->m_ClientId >= 0 && pChunk->m_ClientId < MaxClients(),
800 "Invalid pChunk->m_ClientId: %d",
801 pChunk->m_ClientId);
802
803 if(pChunk->m_Flags & NETSENDFLAG_VITAL)
804 Flags = NET_CHUNKFLAG_VITAL;
805
806 if(m_aSlots[pChunk->m_ClientId].m_Connection.QueueChunk(Flags, DataSize: pChunk->m_DataSize, pData: pChunk->m_pData) == 0)
807 {
808 if(pChunk->m_Flags & NETSENDFLAG_FLUSH)
809 {
810 if(m_FlushBatch)
811 m_aFlushPending[pChunk->m_ClientId] = true;
812 else
813 m_aSlots[pChunk->m_ClientId].m_Connection.Flush();
814 }
815 }
816 }
817 return 0;
818}
819
820void CNetServer::SendTokenSixup(NETADDR &Addr, SECURITY_TOKEN Token)
821{
822 unsigned char aRequestTokenBuf[NET_TOKENREQUEST_DATASIZE] = {};
823 WriteSecurityToken(pData: aRequestTokenBuf, Token: GetToken(Addr));
824 const int Size = Token == NET_SECURITY_TOKEN_UNKNOWN ? sizeof(aRequestTokenBuf) : sizeof(SECURITY_TOKEN);
825 CNetBase::SendControlMsg(Socket: m_Socket, pAddr: &Addr, Ack: 0, ControlMsg: protocol7::NET_CTRLMSG_TOKEN, pExtra: aRequestTokenBuf, ExtraSize: Size, SecurityToken: Token, Sixup: true);
826}
827
828void CNetServer::SetMaxClientsPerIp(int Max)
829{
830 m_MaxClientsPerIp = std::clamp<int>(val: Max, lo: 1, hi: NET_MAX_CLIENTS);
831}
832
833bool CNetServer::HasErrored(int ClientId)
834{
835 return m_aSlots[ClientId].m_Connection.State() == CNetConnection::EState::ERROR;
836}
837
838void CNetServer::ResumeOldConnection(int ClientId, int OrigId)
839{
840 m_aSlots[ClientId].m_Connection.ResumeConnection(pAddr: ClientAddr(ClientId: OrigId), Sequence: m_aSlots[OrigId].m_Connection.SeqSequence(), Ack: m_aSlots[OrigId].m_Connection.AckSequence(), SecurityToken: m_aSlots[OrigId].m_Connection.SecurityToken(), pResendBuffer: m_aSlots[OrigId].m_Connection.ResendBuffer(), Sixup: m_aSlots[OrigId].m_Connection.m_Sixup);
841 m_aSlots[OrigId].m_Connection.Reset();
842}
843
844void CNetServer::IgnoreTimeouts(int ClientId)
845{
846 m_aSlots[ClientId].m_Connection.m_TimeoutProtected = true;
847}
848
849void CNetServer::ResetErrorString(int ClientId)
850{
851 m_aSlots[ClientId].m_Connection.ResetErrorString();
852}
853
854const char *CNetServer::ErrorString(int ClientId)
855{
856 return m_aSlots[ClientId].m_Connection.ErrorString();
857}
858