mirror of
https://github.com/Cockatrice/Cockatrice.git
synced 2026-11-05 01:23:24 -08:00
Some checks are pending
CodeQL / Analyze (cpp) (push) Waiting to run
CodeQL / Analyze (actions) (push) Waiting to run
Build Desktop / Configure (push) Waiting to run
Build Desktop / Debian 13 (push) Blocked by required conditions
Build Desktop / Debian 12 (push) Blocked by required conditions
Build Desktop / Fedora 44 (push) Blocked by required conditions
Build Desktop / Fedora 43 (push) Blocked by required conditions
Build Desktop / Servatrice_Debian 12 (push) Blocked by required conditions
Build Desktop / Ubuntu 24.04 (push) Blocked by required conditions
Build Desktop / Ubuntu 26.04 (push) Blocked by required conditions
Build Desktop / Arch (push) Blocked by required conditions
Build Desktop / Ubuntu 26.04 cover (push) Blocked by required conditions
Build Desktop / macOS 13 Intel (push) Blocked by required conditions
Build Desktop / macOS 14 (push) Blocked by required conditions
Build Desktop / macOS 15 (push) Blocked by required conditions
Build Desktop / macOS 26 Debug (push) Blocked by required conditions
Build Desktop / Windows 10 (push) Blocked by required conditions
Build Desktop / Prune caches (push) Waiting to run
Build Docker / Servatrice (arm) (push) Waiting to run
Build Docker / Servatrice (x86) (push) Waiting to run
Build Docker / Publish multi-platform Servatrice image (push) Blocked by required conditions
* [Security] Add per-address rate limiting for auth endpoints Introduce a thread-safe RateLimiter that tracks attempts per key (IP address) within a sliding time window, and wire it into the authentication endpoints: - Login: failed login attempts from an address are counted; once the configured maximum is exceeded within the window, further logins from that address are rejected with RespTooManyRequests. A successful login clears the failed attempts for that address. - Registration: implement the previously stubbed tooManyRegistrationAttempts, limiting how many accounts can be created per address per window. - Forgot-password: throttle both the email-request and the email-challenge paths per address. New [security] settings with defaults: max_login_attempts_per_ip=5 / login_attempt_window_seconds=900 max_registrations_per_ip=2 / registration_window_seconds=3600 max_forgot_password_requests_per_ip=3 / forgot_password_window_seconds=3600 Adds unit tests for the RateLimiter (window limit, over-limit blocking, clearing, per-key independence). Took 3 minutes * [Server] Fix rate limiter: disable semantics, draining window, bounded keys, pre-work login gate - recordAttempt()/isBlocked() return false when maxAttempts <= 0 or windowSeconds <= 0, so the documented 'set to 0 to disable' actually disables instead of blocking every address permanently - Keys at their limit are rejected without recording, so repeated attempts at the attacker's pace cannot keep sliding the window and holding the lockout open; a block now clears once the recorded attempts age out of windowSeconds - Attempts map is bounded: an opportunistic prune (every 60s) erases keys whose attempts have fully aged out - Login is throttled before the work: isLoginRateLimited() (a new virtual on Server, backed by isBlocked()) gates loginUser(), so a locked-out address no longer burns a database round trip and password verification per attempt - recordAttemptAt()/isBlockedAt() time seams make the sliding-window behaviour deterministically testable; tests rewritten for the real semantics (no reliance on the maxAttempts=0 bug, no sleeps) * [Server] Inform client of login/registration rate limit timeout - Add retryAfterSeconds/retryAfterSecondsAt to RateLimiter to compute seconds until oldest attempt exits the sliding window - Expose loginRateLimitRemainingSeconds via Server/Servatrice - Include denied_end_time (absolute epoch) in RespTooManyRequests for login pre-auth and when transitioning to lockout after failed attempt - Include denied_end_time in registration rate limit response - Client: show retry time for login RespTooManyRequests - Client: simplify registration RespTooManyRequests message to show retry time when provided - Add test for retryAfterSecondsAt * [Client] Restore registration guidance and drop duplicated rate limit reason The registration RespTooManyRequests case now only shows the retry-after copy when the server actually sent a denied_end_time; the per-email account cap path (no end time) falls back to the previous guidance about already having an account and contacting the server operator. Drop the canned denied_reason_str from the new login rate limit branches so the client no longer prints the same sentence twice. * [Server] Exempt trusted_sources from auth rate limits Addresses in security/trusted_sources bypass per-address limits, matching the existing max_users_per_address bypass in initSession. Without this, Webatrice behind local nginx (all clients as 127.0.0.1) would lock out every web user after 5 mistyped passwords, and cap the whole server at 2 registrations / 3 forgot-password requests per window. Adds Servatrice::isRateLimitExempt helper; recordFailedLogin, isLoginRateLimited, recordRegistrationAttempt and recordForgotPasswordAttempt all check it. # Conflicts: # servatrice/src/servatrice.cpp * [Server] Key login rate limit by (address, username) A successful login cleared the whole per-IP failure history, so 4 bad guesses plus 1 self-login (or guest UnknownUser login) from the same address bypassed the limiter. Failures are now bucketed per (address, lowercase username) and a success clears only its own pair. --------- Co-authored-by: Lukas Brübach <Bruebach.Lukas@bdosecurity.de>
400 lines
14 KiB
C++
400 lines
14 KiB
C++
/***************************************************************************
|
|
* Copyright (C) 2008 by Max-Wilhelm Bruker *
|
|
* brukie@laptop *
|
|
* *
|
|
* 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, write to the *
|
|
* Free Software Foundation, Inc., *
|
|
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
|
|
***************************************************************************/
|
|
#ifndef SERVATRICE_H
|
|
#define SERVATRICE_H
|
|
|
|
#include "metrics_registry.h"
|
|
#include "ratelimiter.h"
|
|
#include "smtpclient.h"
|
|
|
|
#include <QByteArray>
|
|
#include <QDateTime>
|
|
#include <QHostAddress>
|
|
#include <QList>
|
|
#include <QMap>
|
|
#include <QMetaType>
|
|
#include <QMutex>
|
|
#include <QMutexLocker>
|
|
#include <QReadWriteLock>
|
|
#include <QSslCertificate>
|
|
#include <QSslKey>
|
|
#include <QString>
|
|
|
|
// IWYU pragma: keep
|
|
// Q_DECLARE_METATYPE below needs the complete type.
|
|
#include <QSqlDatabase>
|
|
#include <QTcpServer>
|
|
#include <QWebSocketServer>
|
|
#include <QtGlobal>
|
|
#include <atomic>
|
|
#include <libcockatrice/protocol/pb/response_report_stats.pb.h>
|
|
#include <memory>
|
|
#include <qtmetamacros.h>
|
|
#include <server.h>
|
|
#include <utility>
|
|
|
|
class QObject;
|
|
class QThread;
|
|
class SessionEvent;
|
|
|
|
Q_DECLARE_METATYPE(QSqlDatabase)
|
|
|
|
class QTimer;
|
|
class Servatrice;
|
|
class Servatrice_ConnectionPool;
|
|
class Servatrice_DatabaseInterface;
|
|
class AbstractServerSocketInterface;
|
|
class IslInterface;
|
|
|
|
class Servatrice_GameServer : public QTcpServer
|
|
{
|
|
Q_OBJECT
|
|
private:
|
|
Servatrice *server;
|
|
QList<Servatrice_ConnectionPool *> connectionPools;
|
|
|
|
public:
|
|
Servatrice_GameServer(Servatrice *_server,
|
|
int _numberPools,
|
|
const QSqlDatabase &_sqlDatabase,
|
|
QObject *parent = nullptr);
|
|
~Servatrice_GameServer() override;
|
|
|
|
protected:
|
|
void incomingConnection(qintptr socketDescriptor) override;
|
|
Servatrice_ConnectionPool *findLeastUsedConnectionPool();
|
|
};
|
|
|
|
class Servatrice_WebsocketGameServer : public QWebSocketServer
|
|
{
|
|
Q_OBJECT
|
|
private:
|
|
Servatrice *server;
|
|
QList<Servatrice_ConnectionPool *> connectionPools;
|
|
|
|
public:
|
|
Servatrice_WebsocketGameServer(Servatrice *_server,
|
|
int _numberPools,
|
|
const QSqlDatabase &_sqlDatabase,
|
|
QObject *parent = nullptr);
|
|
~Servatrice_WebsocketGameServer() override;
|
|
|
|
protected:
|
|
Servatrice_ConnectionPool *findLeastUsedConnectionPool();
|
|
protected slots:
|
|
void onNewConnection();
|
|
};
|
|
|
|
class Servatrice_IslServer : public QTcpServer
|
|
{
|
|
Q_OBJECT
|
|
private:
|
|
Servatrice *server;
|
|
QSslCertificate cert;
|
|
QSslKey privateKey;
|
|
|
|
public:
|
|
Servatrice_IslServer(Servatrice *_server,
|
|
const QSslCertificate &_cert,
|
|
QSslKey _privateKey,
|
|
QObject *parent = nullptr)
|
|
: QTcpServer(parent), server(_server), cert(_cert), privateKey(std::move(_privateKey))
|
|
{
|
|
}
|
|
|
|
protected:
|
|
void incomingConnection(qintptr socketDescriptor) override;
|
|
};
|
|
|
|
class ServerProperties
|
|
{
|
|
public:
|
|
int id;
|
|
QSslCertificate cert;
|
|
QString hostname;
|
|
QHostAddress address;
|
|
int gamePort;
|
|
int controlPort;
|
|
|
|
ServerProperties(int _id,
|
|
const QSslCertificate &_cert,
|
|
QString _hostname,
|
|
const QHostAddress &_address,
|
|
int _gamePort,
|
|
int _controlPort)
|
|
: id(_id), cert(_cert), hostname(std::move(_hostname)), address(_address), gamePort(_gamePort),
|
|
controlPort(_controlPort)
|
|
{
|
|
}
|
|
};
|
|
|
|
class Servatrice : public Server
|
|
{
|
|
Q_OBJECT
|
|
public:
|
|
enum AuthenticationMethod
|
|
{
|
|
AuthenticationNone,
|
|
AuthenticationSql,
|
|
AuthenticationPassword
|
|
};
|
|
private slots:
|
|
void statusUpdate();
|
|
void shutdownTimeout();
|
|
void cleanupExpiredDeckShares();
|
|
|
|
protected:
|
|
void doSendIslMessage(const IslMessage &msg, int _serverId) override;
|
|
|
|
private:
|
|
enum DatabaseType
|
|
{
|
|
DatabaseNone,
|
|
DatabaseMySql
|
|
};
|
|
AuthenticationMethod authenticationMethod;
|
|
DatabaseType databaseType;
|
|
QTimer *pingClock, *statusUpdateClock;
|
|
QTimer *deckShareCleanupClock;
|
|
Servatrice_GameServer *gameServer;
|
|
Servatrice_WebsocketGameServer *websocketGameServer;
|
|
Servatrice_IslServer *islServer;
|
|
mutable QMutex loginMessageMutex;
|
|
QString loginMessage;
|
|
mutable QMutex shutdownStateMutex;
|
|
QString dbPrefix;
|
|
QMap<QString, bool> serverRequiredFeatureList;
|
|
QString officialWarnings;
|
|
Servatrice_DatabaseInterface *servatriceDatabaseInterface;
|
|
bool cleanupDatabaseForEmail(const QString &userName, EmailType type, const QString &token, qint64 rowId);
|
|
int serverId;
|
|
int uptime;
|
|
QMutex txBytesMutex, rxBytesMutex;
|
|
quint64 txBytes, rxBytes;
|
|
MetricsRegistry metricsRegistry;
|
|
int metricsSlowCommandMs = 500;
|
|
int metricsStallWarnMs = 2000;
|
|
std::atomic<qint64> eventLoopStallsTotal{0}; ///< heartbeat overshoots past the warn threshold
|
|
std::atomic<qint64> eventLoopLastStallMs{0}; ///< overshoot of the most recent stall
|
|
std::atomic<qint64> eventLoopMaxStallMs{0}; ///< worst overshoot seen since process start
|
|
|
|
QString shutdownReason;
|
|
int shutdownMinutes;
|
|
int nextShutdownMessageMinutes;
|
|
QTimer *shutdownTimer;
|
|
|
|
mutable QMutex reportStatsMutex;
|
|
QDateTime reportStatsTimestamp;
|
|
std::shared_ptr<const Response_ReportStats> reportStatsCache;
|
|
static constexpr int reportStatsCacheTtlSeconds = 60;
|
|
|
|
RateLimiter rateLimiter;
|
|
|
|
mutable QMutex serverListMutex;
|
|
QList<ServerProperties> serverList;
|
|
void updateServerList();
|
|
|
|
QMap<int, IslInterface *> islInterfaces;
|
|
|
|
QString getDBPrefixString() const;
|
|
QString getDBHostNameString() const;
|
|
QString getDBDatabaseNameString() const;
|
|
QString getDBUserNameString() const;
|
|
QString getDBPasswordString() const;
|
|
QString getRoomsMethodString() const;
|
|
QString getISLNetworkSSLCertFile() const;
|
|
QString getISLNetworkSSLKeyFile() const;
|
|
int getServerStatusUpdateTime() const;
|
|
int getNumberOfTCPPools() const;
|
|
int getServerTCPPort() const;
|
|
int getNumberOfWebSocketPools() const;
|
|
int getServerWebSocketPort() const;
|
|
int getISLNetworkPort() const;
|
|
bool getISLNetworkEnabled() const;
|
|
bool getEnableInternalSMTPClient() const;
|
|
QHostAddress getServerTCPHost() const;
|
|
QHostAddress getServerWebSocketHost() const;
|
|
|
|
public slots:
|
|
void scheduleShutdown(const QString &reason, int minutes);
|
|
void updateLoginMessage();
|
|
void setRequiredFeatures(const QString &featureList);
|
|
void onEmailDelivered(const QString &userName, EmailType type, const QString &token, qint64 rowId);
|
|
void onEmailPermanentlyFailed(const QString &userName,
|
|
EmailType type,
|
|
FailureReason reason,
|
|
const QString &token,
|
|
qint64 rowId);
|
|
|
|
public:
|
|
explicit Servatrice(QObject *parent = nullptr);
|
|
~Servatrice() override;
|
|
bool initServer();
|
|
QMap<QString, bool> getServerRequiredFeatureList() const override
|
|
{
|
|
return serverRequiredFeatureList;
|
|
}
|
|
QString getServerName() const;
|
|
QString getLoginMessage() const override
|
|
{
|
|
QMutexLocker locker(&loginMessageMutex);
|
|
return loginMessage;
|
|
}
|
|
SessionEvent *getLoginSessionEvent() const override;
|
|
SessionEvent *makeShutdownEvent() const;
|
|
QString getRequiredFeatures() const override;
|
|
QString getAuthenticationMethodString() const;
|
|
QString getDBTypeString() const;
|
|
QString getDbPrefix() const
|
|
{
|
|
return dbPrefix;
|
|
}
|
|
QString getEmailBlackList() const;
|
|
QString getEmailWhiteList() const;
|
|
AuthenticationMethod getAuthenticationMethod() const
|
|
{
|
|
return authenticationMethod;
|
|
}
|
|
bool permitUnregisteredUsers() const override
|
|
{
|
|
return authenticationMethod != AuthenticationNone;
|
|
}
|
|
bool getGameShouldPing() const override
|
|
{
|
|
return true;
|
|
}
|
|
bool getClientIDRequiredEnabled() const override;
|
|
bool getRegOnlyServerEnabled() const override;
|
|
bool getMaxUserLimitEnabled() const override;
|
|
bool getStoreReplaysEnabled() const override;
|
|
bool getRegistrationEnabled() const;
|
|
bool getRequireEmailForRegistrationEnabled() const;
|
|
bool getRequireEmailActivationEnabled() const;
|
|
bool getEnableLogQuery() const override;
|
|
bool getEnableForgotPassword() const;
|
|
bool getEnableForgotPasswordChallenge() const;
|
|
bool getEnableAudit() const;
|
|
bool getEnableRegistrationAudit() const;
|
|
bool getEnableForgotPasswordAudit() const;
|
|
int getMinPasswordLength() const;
|
|
int getIdleClientTimeout() const override;
|
|
int getServerID() const override;
|
|
int getMaxGameInactivityTime() const override;
|
|
int getMaxPlayerInactivityTime() const override;
|
|
int getClientKeepAlive() const override;
|
|
int getDeckShareExpiryDays() const;
|
|
int getDeckShareCleanupInterval() const;
|
|
int getDeckShareMaxDecksPerShare() const;
|
|
int getDeckShareMaxSharesPerDay() const;
|
|
int getMaxUsersPerAddress() const;
|
|
int getMessageCountingInterval() const override;
|
|
int getMaxMessageCountPerInterval() const override;
|
|
int getMaxMessageSizePerInterval() const override;
|
|
int getMaxGamesPerUser() const override;
|
|
int getCommandCountingInterval() const override;
|
|
int getMaxCommandCountPerInterval() const override;
|
|
int getMaxUserTotal() const override;
|
|
bool permitCreateGameAsJudge() const override;
|
|
int getMaxTcpUserLimit() const;
|
|
int getMaxWebSocketUserLimit() const;
|
|
int getUsersWithAddress(const QHostAddress &address) const;
|
|
int getMaxAccountsPerEmail() const;
|
|
int getForgotPasswordTokenLife() const;
|
|
QList<AbstractServerSocketInterface *> getUsersWithAddressAsList(const QHostAddress &address) const;
|
|
void incTxBytes(quint64 num);
|
|
void incRxBytes(quint64 num);
|
|
void addDatabaseInterface(QThread *thread, Servatrice_DatabaseInterface *databaseInterface);
|
|
|
|
// Metrics (see [metrics] section in servatrice.ini.example)
|
|
MetricsRegistry &getMetricsRegistry()
|
|
{
|
|
return metricsRegistry;
|
|
}
|
|
/**
|
|
* Sums cards across all zones of all running games. Each game takes its
|
|
* own gameMutex -- the hot per-game lock every game action contends on --
|
|
* and then iterates every player's zones, so the scrape cost is really
|
|
* O(total cards in play) plus one mutex acquisition per live game. Keep
|
|
* scrapes infrequent in big multiplayer rooms.
|
|
*/
|
|
qint64 getCardsInGamesTotal() const;
|
|
int getMetricsSlowCommandMs() const
|
|
{
|
|
return metricsSlowCommandMs;
|
|
}
|
|
/// Heartbeat overshoot that counts as a stall. A value of 0 disables the watchdogs.
|
|
int getMetricsStallWarnMs() const
|
|
{
|
|
return metricsStallWarnMs;
|
|
}
|
|
void observeGameStartDurationMs(qint64 elapsedMs) override;
|
|
qint64 getEventLoopStallsTotal() const
|
|
{
|
|
return eventLoopStallsTotal.load(std::memory_order_relaxed);
|
|
}
|
|
qint64 getEventLoopLastStallMs() const
|
|
{
|
|
return eventLoopLastStallMs.load(std::memory_order_relaxed);
|
|
}
|
|
qint64 getEventLoopMaxStallMs() const
|
|
{
|
|
return eventLoopMaxStallMs.load(std::memory_order_relaxed);
|
|
}
|
|
/// Records one heartbeat overshoot and logs a single warning for it.
|
|
void observeEventLoopStall(const QString &threadName, qint64 overshootMs);
|
|
/**
|
|
* Installs an EventLoopWatchdog in @p thread. Called once per socket pool
|
|
* thread right after it starts.
|
|
*/
|
|
void watchWorkerThread(QThread *thread);
|
|
|
|
RateLimiter *getRateLimiter()
|
|
{
|
|
return &rateLimiter;
|
|
}
|
|
bool recordFailedLogin(const QString &ipAddress, const QString &userName) override;
|
|
bool isLoginRateLimited(const QString &ipAddress, const QString &userName) override;
|
|
int loginRateLimitRemainingSeconds(const QString &ipAddress, const QString &userName) override;
|
|
void clearFailedLogins(const QString &ipAddress, const QString &userName) override;
|
|
bool recordRegistrationAttempt(const QString &ipAddress);
|
|
bool recordForgotPasswordAttempt(const QString &ipAddress);
|
|
/// True when the address is in security/trusted_sources and therefore exempt from per-address limits.
|
|
bool isRateLimitExempt(const QString &ipAddress) const;
|
|
int getMaxLoginAttemptsPerIp() const;
|
|
int getLoginAttemptWindowSeconds() const;
|
|
int getMaxRegistrationsPerIp() const;
|
|
int getRegistrationWindowSeconds() const;
|
|
int getMaxForgotPasswordRequestsPerIp() const;
|
|
int getForgotPasswordWindowSeconds() const;
|
|
|
|
bool islConnectionExists(int _serverId) const;
|
|
void addIslInterface(int _serverId, IslInterface *interface);
|
|
void removeIslInterface(int _serverId);
|
|
QReadWriteLock islLock;
|
|
|
|
// The moderation queue statistics are shared between all connected moderators and
|
|
// cached briefly to avoid re-running several full-table queries on every refresh.
|
|
std::shared_ptr<const Response_ReportStats> getCachedReportStats() const;
|
|
void cacheReportStats(const Response_ReportStats &stats);
|
|
|
|
QList<ServerProperties> getServerList() const;
|
|
};
|
|
|
|
#endif
|