Network: connections per address and login timeouts
Nothing limited how many connections one address could hold open, and a connection that never logged in stayed open for good, on both servers. worldserver: Network.ConnectionsPerIp (16; a player uses two) and Network.AuthTimeout (60 s to log in). bnetserver: Network.ConnectionsPerIp (16), Network.HandshakeTimeout (30 s for the TLS handshake) and Network.LoginTimeout (600 s to log in). 0 turns each off, and connections from the server's own PC (loopback) are never limited, so the local launcher and a single-PC realm are unaffected. The count lives in Trinity::Net::IpConnectionLimit (common/network), with a test.
This commit is contained in:
@@ -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 <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#ifndef TRINITYCORE_IP_CONNECTION_LIMIT_H
|
||||
#define TRINITYCORE_IP_CONNECTION_LIMIT_H
|
||||
|
||||
#include "Define.h"
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
|
||||
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<Slot> TryAcquire(std::string const& address, bool isLoopback, uint32 limit)
|
||||
{
|
||||
if (!limit || isLoopback)
|
||||
return std::make_unique<Slot>(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<Slot>(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<std::string, uint32> _counts;
|
||||
};
|
||||
}
|
||||
|
||||
#endif // TRINITYCORE_IP_CONNECTION_LIMIT_H
|
||||
@@ -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::Socket> Battlenet::Session::CreateSocket(Tri
|
||||
return std::make_shared<Socket>(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<Battlenet::Session> session) : _session(std::move(session)) { }
|
||||
|
||||
void Start() override
|
||||
{
|
||||
if (std::shared_ptr<Battlenet::Session> session = _session.lock())
|
||||
session->SetHandshakeDone();
|
||||
InvokeNext();
|
||||
}
|
||||
|
||||
private:
|
||||
std::weak_ptr<Battlenet::Session> _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<std::shared_ptr<Trinity::Net::SocketConnectionInitializer>, 3> initializers =
|
||||
std::array<std::shared_ptr<Trinity::Net::SocketConnectionInitializer>, 4> initializers =
|
||||
{ {
|
||||
std::make_shared<Trinity::Net::IpBanCheckConnectionInitializer<Session>>(this),
|
||||
std::make_shared<Trinity::Net::SslHandshakeConnectionInitializer<Socket>>(_socket.get()),
|
||||
std::make_shared<HandshakeDoneConnectionInitializer>(weak_from_this()),
|
||||
std::make_shared<Trinity::Net::ReadConnectionInitializer<Socket, Session>>(_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;
|
||||
|
||||
@@ -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<Trinity::Net::IpConnectionLimit::Slot> _ipConnectionSlot;
|
||||
|
||||
QueryCallbackProcessor _queryProcessor;
|
||||
|
||||
std::unordered_map<uint32, std::function<void(MessageBuffer)>> _responseCallbacks;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -67,7 +67,7 @@ std::array<uint8, 32> 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<std::shared_ptr<Trinity::Net::SocketConnectionInitializer>, 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))
|
||||
{
|
||||
|
||||
@@ -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 <array>
|
||||
#include <atomic>
|
||||
#include <mutex>
|
||||
|
||||
namespace JSON::RealmList
|
||||
@@ -164,9 +166,12 @@ private:
|
||||
|
||||
std::mutex _worldSessionLock;
|
||||
WorldSession* _worldSession;
|
||||
bool _authed;
|
||||
std::atomic<bool> _authed; // also set from the world thread (SetWorldSession), read by Update for the login timeout
|
||||
bool _canRequestHotfixes;
|
||||
|
||||
std::unique_ptr<Trinity::Net::IpConnectionLimit::Slot> _ipConnectionSlot;
|
||||
TimePoint _authDeadline; // closed if not logged in by then (Network.AuthTimeout); TimePoint::max() = no limit
|
||||
|
||||
MessageBuffer _headerBuffer;
|
||||
MessageBuffer _packetBuffer;
|
||||
MPSCQueue<EncryptablePacket, &EncryptablePacket::SocketQueueLink> _bufferQueue;
|
||||
|
||||
@@ -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
|
||||
|
||||
#
|
||||
###################################################################################################
|
||||
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
Reference in New Issue
Block a user