diff --git a/src/common/network/IpConnectionLimit.h b/src/common/network/IpConnectionLimit.h
new file mode 100644
index 0000000000..2e9aafebd9
--- /dev/null
+++ b/src/common/network/IpConnectionLimit.h
@@ -0,0 +1,91 @@
+/*
+ * This file is part of the TrinityCore Project. See AUTHORS file for Copyright information
+ *
+ * This program is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License as published by the
+ * Free Software Foundation; either version 2 of the License, or (at your
+ * option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
+ * more details.
+ *
+ * You should have received a copy of the GNU General Public License along
+ * with this program. If not, see .
+ */
+
+#ifndef TRINITYCORE_IP_CONNECTION_LIMIT_H
+#define TRINITYCORE_IP_CONNECTION_LIMIT_H
+
+#include "Define.h"
+#include
+#include
+#include
+#include
+
+namespace Trinity::Net
+{
+// Open connections per remote address on one listener. A socket holds its Slot for as long as it lives and the count drops
+// when the Slot goes. A limit of 0 and the server's own PC (loopback, where a local launcher or bridge connects from) are
+// never limited.
+class IpConnectionLimit
+{
+public:
+ class Slot
+ {
+ public:
+ Slot(IpConnectionLimit* owner, std::string key) : _owner(owner), _key(std::move(key)) { }
+ Slot(Slot const&) = delete;
+ Slot& operator=(Slot const&) = delete;
+ ~Slot() { if (_owner) _owner->Release(_key); }
+
+ private:
+ IpConnectionLimit* _owner;
+ std::string _key;
+ };
+
+ // nullptr: the address already has `limit` open connections
+ std::unique_ptr TryAcquire(std::string const& address, bool isLoopback, uint32 limit)
+ {
+ if (!limit || isLoopback)
+ return std::make_unique(nullptr, std::string());
+
+ std::scoped_lock lock(_lock);
+ uint32& count = _counts[address];
+ if (count >= limit)
+ {
+ if (!count)
+ _counts.erase(address);
+ return nullptr;
+ }
+
+ ++count;
+ return std::make_unique(this, address);
+ }
+
+ uint32 GetCount(std::string const& address) const
+ {
+ std::scoped_lock lock(_lock);
+ auto itr = _counts.find(address);
+ return itr != _counts.end() ? itr->second : 0;
+ }
+
+private:
+ void Release(std::string const& address)
+ {
+ std::scoped_lock lock(_lock);
+ auto itr = _counts.find(address);
+ if (itr == _counts.end())
+ return;
+
+ if (!--itr->second)
+ _counts.erase(itr);
+ }
+
+ mutable std::mutex _lock;
+ std::unordered_map _counts;
+};
+}
+
+#endif // TRINITYCORE_IP_CONNECTION_LIMIT_H
diff --git a/src/server/bnetserver/Server/Session.cpp b/src/server/bnetserver/Server/Session.cpp
index 5184db81fd..ccc5c86266 100644
--- a/src/server/bnetserver/Server/Session.cpp
+++ b/src/server/bnetserver/Server/Session.cpp
@@ -17,6 +17,7 @@
#include "Session.h"
#include "ByteConverter.h"
+#include "Config.h"
#include "DatabaseEnv.h"
#include "Errors.h"
#include "IpBanCheckConnectionInitializer.h"
@@ -75,7 +76,8 @@ Battlenet::Session::Session(Trinity::Net::IoContextTcpSocket&& socket) : _socket
_packetReadState(PacketReadState::HeaderLength), _packetBuffer(PacketHeaderLengthSize),
_sessionId(++sSessionMgr.SessionIdGenerator), _creationTime(SystemTimePoint::clock::now()),
_accountInfo(new AccountInfo()), _gameAccountInfo(nullptr), _locale(),
- _os(), _build(0), _buildVariant(), _timezoneOffset(0min), _ipCountry(), _clientSecret(), _authed(false), _requestToken(0)
+ _os(), _build(0), _buildVariant(), _timezoneOffset(0min), _ipCountry(), _clientSecret(), _authed(false), _handshakeDone(false), _handshakeDeadline(TimePoint::max()),
+ _loginDeadline(TimePoint::max()), _requestToken(0)
{
}
@@ -86,15 +88,57 @@ std::shared_ptr Battlenet::Session::CreateSocket(Tri
return std::make_shared(std::move(socket), SslContext::instance());
}
+namespace
+{
+Trinity::Net::IpConnectionLimit BattlenetConnectionLimit;
+
+// runs once the TLS handshake is done
+struct HandshakeDoneConnectionInitializer final : Trinity::Net::SocketConnectionInitializer
+{
+ explicit HandshakeDoneConnectionInitializer(std::weak_ptr session) : _session(std::move(session)) { }
+
+ void Start() override
+ {
+ if (std::shared_ptr session = _session.lock())
+ session->SetHandshakeDone();
+ InvokeNext();
+ }
+
+private:
+ std::weak_ptr _session;
+};
+
+TimePoint DeadlineFromConfig(char const* name, int32 defaultSeconds)
+{
+ int32 const seconds = sConfigMgr->GetIntDefault(name, defaultSeconds);
+ return seconds > 0 ? TimePoint::clock::now() + Seconds(seconds) : TimePoint::max();
+}
+}
+
void Battlenet::Session::Start()
{
TC_LOG_TRACE("session", "{} Accepted connection", GetClientInfo());
+ // connections per address; the server's own PC is never limited
+ boost::asio::ip::address const& address = _socket->GetRemoteIpAddress();
+ _ipConnectionSlot = BattlenetConnectionLimit.TryAcquire(address.to_string(), address.is_loopback(),
+ uint32(std::max(sConfigMgr->GetIntDefault("Network.ConnectionsPerIp", 16), 0)));
+ if (!_ipConnectionSlot)
+ {
+ TC_LOG_ERROR("session", "{} already has Network.ConnectionsPerIp open connections, refusing another", GetClientInfo());
+ _socket->CloseSocket();
+ return;
+ }
+
+ _handshakeDeadline = DeadlineFromConfig("Network.HandshakeTimeout", 30);
+ _loginDeadline = DeadlineFromConfig("Network.LoginTimeout", 600);
+
// build initializer chain
- std::array, 3> initializers =
+ std::array, 4> initializers =
{ {
std::make_shared>(this),
std::make_shared>(_socket.get()),
+ std::make_shared(weak_from_this()),
std::make_shared>(_socket.get(), this),
} };
@@ -106,6 +150,14 @@ bool Battlenet::Session::Update()
if (!_socket->Update())
return false;
+ TimePoint const now = TimePoint::clock::now();
+ if ((!_handshakeDone && now > _handshakeDeadline) || (!_authed && now > _loginDeadline))
+ {
+ TC_LOG_DEBUG("session", "{} did not finish the {} in time, closing", GetClientInfo(), _handshakeDone ? "login" : "TLS handshake");
+ _socket->CloseSocket();
+ return false;
+ }
+
_queryProcessor.ProcessReadyCallbacks();
return true;
diff --git a/src/server/bnetserver/Server/Session.h b/src/server/bnetserver/Server/Session.h
index 0a1bcb8a98..c7dc4336c5 100644
--- a/src/server/bnetserver/Server/Session.h
+++ b/src/server/bnetserver/Server/Session.h
@@ -23,6 +23,7 @@
#include "DatabaseEnvFwd.h"
#include "Duration.h"
#include "Hash.h"
+#include "IpConnectionLimit.h"
#include "Realm.h"
#include "Socket.h"
#include "SslStream.h"
@@ -93,6 +94,7 @@ namespace Battlenet
void DelayedCloseSocket() { return _socket->DelayedCloseSocket(); }
bool IsAuthed() const { return _authed; }
+ void SetHandshakeDone() { _handshakeDone = true; }
uint32 GetSessionId() const { return _sessionId; }
SystemTimePoint GetCreationTime() const { return _creationTime; }
@@ -171,6 +173,12 @@ namespace Battlenet
bool _authed;
+ // closed when the TLS handshake or the login doesn't finish in time (Network.HandshakeTimeout, Network.LoginTimeout)
+ bool _handshakeDone;
+ TimePoint _handshakeDeadline;
+ TimePoint _loginDeadline;
+ std::unique_ptr _ipConnectionSlot;
+
QueryCallbackProcessor _queryProcessor;
std::unordered_map> _responseCallbacks;
diff --git a/src/server/bnetserver/bnetserver.conf.dist b/src/server/bnetserver/bnetserver.conf.dist
index 6527ba48bb..32d056dc4b 100644
--- a/src/server/bnetserver/bnetserver.conf.dist
+++ b/src/server/bnetserver/bnetserver.conf.dist
@@ -148,6 +148,31 @@ ProcessPriority = 0
RealmsStateUpdateDelay = 10
+#
+# Network.ConnectionsPerIp
+# Description: Open Battle.net connections allowed from one address. Connections from this PC (127.0.0.1) are never
+# limited. Raise it when many players share one internet address (LAN party, one household).
+# Default: 16
+# 0 - (No limit)
+
+Network.ConnectionsPerIp = 16
+
+#
+# Network.HandshakeTimeout
+# Description: Seconds a new connection has to finish the TLS handshake before it is closed.
+# Default: 30
+# 0 - (No limit)
+
+Network.HandshakeTimeout = 30
+
+#
+# Network.LoginTimeout
+# Description: Seconds a connection has to log in before it is closed.
+# Default: 600
+# 0 - (No limit)
+
+Network.LoginTimeout = 600
+
#
# WrongPass.MaxCount
# Description: Number of login attempts with wrong password before the account or IP will be
diff --git a/src/server/game/Server/WorldSocket.cpp b/src/server/game/Server/WorldSocket.cpp
index 5008d816f1..29f0336c39 100644
--- a/src/server/game/Server/WorldSocket.cpp
+++ b/src/server/game/Server/WorldSocket.cpp
@@ -67,7 +67,7 @@ std::array const WorldSocket::EncryptionKeySeed = { 0x71, 0xC9, 0xED,
WorldSocket::WorldSocket(Trinity::Net::IoContextTcpSocket&& socket) : BaseSocket(std::move(socket)),
_type(CONNECTION_TYPE_REALM), _key(0), _serverChallenge(), _sessionKey(), _encryptKey(), _overSpeedPings(0),
- _worldSession(nullptr), _authed(false), _canRequestHotfixes(true), _headerBuffer(sizeof(IncomingPacketHeader)), _sendBufferSize(4096), _compressionStream(nullptr)
+ _worldSession(nullptr), _authed(false), _canRequestHotfixes(true), _authDeadline(TimePoint::max()), _headerBuffer(sizeof(IncomingPacketHeader)), _sendBufferSize(4096), _compressionStream(nullptr)
{
}
@@ -121,8 +121,27 @@ private:
MessageBuffer _packetBuffer;
};
+namespace
+{
+Trinity::Net::IpConnectionLimit WorldConnectionLimit;
+}
+
void WorldSocket::Start()
{
+ // connections per address: a player uses two (realm and instance); the server's own PC is never limited
+ boost::asio::ip::address const& address = GetRemoteIpAddress();
+ _ipConnectionSlot = WorldConnectionLimit.TryAcquire(address.to_string(), address.is_loopback(),
+ uint32(std::max(sConfigMgr->GetIntDefault("Network.ConnectionsPerIp", 16), 0)));
+ if (!_ipConnectionSlot)
+ {
+ TC_LOG_ERROR("network", "WorldSocket::Start: {} already has Network.ConnectionsPerIp open connections, refusing another", address.to_string());
+ CloseSocket();
+ return;
+ }
+
+ int32 const authTimeout = sConfigMgr->GetIntDefault("Network.AuthTimeout", 60);
+ _authDeadline = authTimeout > 0 ? TimePoint::clock::now() + Seconds(authTimeout) : TimePoint::max();
+
// build initializer chain
std::array, 3> initializers =
{ {
@@ -204,6 +223,14 @@ bool WorldSocket::InitializeCompression()
bool WorldSocket::Update()
{
+ // a connection that never logs in only holds a slot
+ if (!_authed && _authDeadline != TimePoint::max() && TimePoint::clock::now() > _authDeadline)
+ {
+ TC_LOG_DEBUG("network", "WorldSocket::Update: {} did not log in within Network.AuthTimeout, closing", GetRemoteIpAddress().to_string());
+ CloseSocket();
+ return false;
+ }
+
EncryptablePacket* queued;
if (_bufferQueue.Dequeue(queued))
{
diff --git a/src/server/game/Server/WorldSocket.h b/src/server/game/Server/WorldSocket.h
index aedbfcb85d..56542907ca 100644
--- a/src/server/game/Server/WorldSocket.h
+++ b/src/server/game/Server/WorldSocket.h
@@ -21,12 +21,14 @@
#include "AsyncCallbackProcessor.h"
#include "AuthDefines.h"
#include "DatabaseEnvFwd.h"
+#include "IpConnectionLimit.h"
#include "MPSCQueue.h"
#include "MessageBuffer.h"
#include "Socket.h"
#include "WorldPacket.h"
#include "WorldPacketCrypt.h"
#include
+#include
#include
namespace JSON::RealmList
@@ -164,9 +166,12 @@ private:
std::mutex _worldSessionLock;
WorldSession* _worldSession;
- bool _authed;
+ std::atomic _authed; // also set from the world thread (SetWorldSession), read by Update for the login timeout
bool _canRequestHotfixes;
+ std::unique_ptr _ipConnectionSlot;
+ TimePoint _authDeadline; // closed if not logged in by then (Network.AuthTimeout); TimePoint::max() = no limit
+
MessageBuffer _headerBuffer;
MessageBuffer _packetBuffer;
MPSCQueue _bufferQueue;
diff --git a/src/server/worldserver/worldserver.conf.dist b/src/server/worldserver/worldserver.conf.dist
index 3946953a01..c6029df5ec 100644
--- a/src/server/worldserver/worldserver.conf.dist
+++ b/src/server/worldserver/worldserver.conf.dist
@@ -3196,6 +3196,24 @@ Network.SkipBuildAuthKeyCheck = 0
Network.EnterEncryptedModeDelay = 1500
+#
+# Network.ConnectionsPerIp
+# Description: Open game connections allowed from one address. A player uses two (realm and instance). Connections
+# from this PC (127.0.0.1) are never limited. Raise it when many players share one internet address
+# (LAN party, one household).
+# Default: 16
+# 0 - (No limit)
+
+Network.ConnectionsPerIp = 16
+
+#
+# Network.AuthTimeout
+# Description: Seconds a new game connection has to log in before it is closed.
+# Default: 60
+# 0 - (No limit)
+
+Network.AuthTimeout = 60
+
#
###################################################################################################
diff --git a/tests/common/IpConnectionLimit.cpp b/tests/common/IpConnectionLimit.cpp
new file mode 100644
index 0000000000..6b7086813a
--- /dev/null
+++ b/tests/common/IpConnectionLimit.cpp
@@ -0,0 +1,41 @@
+#include "tc_catch2.h"
+#include "IpConnectionLimit.h"
+
+using Trinity::Net::IpConnectionLimit;
+
+TEST_CASE("An address gets no more than the limit of connections", "[IpConnectionLimit]")
+{
+ IpConnectionLimit limit;
+ auto a = limit.TryAcquire("10.0.0.5", false, 2);
+ auto b = limit.TryAcquire("10.0.0.5", false, 2);
+ REQUIRE(a);
+ REQUIRE(b);
+ CHECK(!limit.TryAcquire("10.0.0.5", false, 2));
+ CHECK(limit.GetCount("10.0.0.5") == 2);
+
+ // another address has its own count
+ CHECK(limit.TryAcquire("10.0.0.6", false, 2));
+}
+
+TEST_CASE("A closed connection frees its place", "[IpConnectionLimit]")
+{
+ IpConnectionLimit limit;
+ auto a = limit.TryAcquire("10.0.0.5", false, 1);
+ REQUIRE(a);
+ CHECK(!limit.TryAcquire("10.0.0.5", false, 1));
+ a.reset();
+ CHECK(limit.GetCount("10.0.0.5") == 0);
+ CHECK(limit.TryAcquire("10.0.0.5", false, 1));
+}
+
+TEST_CASE("Loopback and a limit of 0 are never limited or counted", "[IpConnectionLimit]")
+{
+ IpConnectionLimit limit;
+ for (int i = 0; i < 50; ++i)
+ {
+ CHECK(limit.TryAcquire("127.0.0.1", true, 1));
+ CHECK(limit.TryAcquire("10.0.0.5", false, 0));
+ }
+ CHECK(limit.GetCount("127.0.0.1") == 0);
+ CHECK(limit.GetCount("10.0.0.5") == 0);
+}