[Server/Client] Enforce and complete the forced password change at login (#7680)

checkUserPassword ignored force_password_change on the challenge-response
path, so a reset password stayed valid. Returning PasswordChangeRequired
was not enough on its own: the session was dropped and the client told the
user to ask the administrator for the temporary password they had just used.

The pending session now keeps its identity without registering a user
session or announcing a join, may only ping and change its password, and
the client completes the change in-session before reconnecting.

Co-authored-by: Lukas Brübach <Bruebach.Lukas@bdosecurity.de>
This commit is contained in:
BruebachL 2026-11-02 07:01:29 +01:00 • committed by GitHub
parent ef4574d2b9
commit 50a2ae9cc8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
16 changed files with 575 additions and 28 deletions

View file

@ -15,7 +15,7 @@ target_include_directories(libcockatrice_network_client_abstract PUBLIC .)
target_link_libraries(
libcockatrice_network_client_abstract
PUBLIC ${COCKATRICE_QT_VERSION_NAME}::Network ${COCKATRICE_QT_VERSION_NAME}::WebSockets libcockatrice_protocol
libcockatrice_network_server_remote
libcockatrice_network_server_remote libcockatrice_utility
)
target_precompile_headers(libcockatrice_network_client_abstract PRIVATE "${CMAKE_SOURCE_DIR}/cmake/pch/qtcore_pch.h")

View file

@ -10,6 +10,7 @@
#include "libcockatrice/protocol/pb/serverinfo_user.pb.h"
#include "libcockatrice/protocol/pb/session_commands.pb.h"
#include "libcockatrice/protocol/pb/session_event.pb.h"
#include "libcockatrice/utility/passwordhasher.h"
#include <QDebug>
#include <QList>
@ -80,6 +81,26 @@ AbstractClient::~AbstractClient()
{
}
Command_AccountPassword AbstractClient::makeAccountPasswordCommand(const QString &oldPassword,
const QString &newPassword) const
{
Command_AccountPassword cmd;
cmd.set_old_password(oldPassword.toStdString());
if (getServerSupportsChallengeResponse()) {
// A verifier lets the server upgrade the stored credential without ever seeing the
// password, and it is what a challenge-response server expects for a new password.
cmd.set_hashed_new_password(PasswordHasher::generatePasswordVerifier(newPassword).toStdString());
} else if (getServerSupportsPasswordHash()) {
// The server hashes the password itself with its own salt; a salted hash is the
// strongest form it accepts, so the plaintext never goes on the wire.
const QString passwordSalt = PasswordHasher::generateRandomSalt();
cmd.set_hashed_new_password(PasswordHasher::computeHash(newPassword, passwordSalt).toStdString());
} else {
cmd.set_new_password(newPassword.toStdString());
}
return cmd;
}
void AbstractClient::processProtocolItem(const ServerMessage &item)
{
switch (item.message_type()) {

View file

@ -47,6 +47,7 @@ class Event_UserJoined;
class Event_UserLeft;
class Event_ServerMessage;
class Event_ListRooms;
class Command_AccountPassword;
class Event_GameJoined;
class Event_UserMessage;
class Event_NotifyUser;
@ -67,6 +68,9 @@ enum ClientStatus
StatusSubmitForgotPasswordReset,
StatusSubmitForgotPasswordChallenge,
StatusGettingPasswordSalt,
//! The server accepted the credentials but keeps the session open until the account
//! password is replaced; the connection must survive for `Command_AccountPassword`.
StatusPasswordChangeRequired,
};
class AbstractClient : public QObject
@ -171,6 +175,16 @@ public:
{
return serverSupportsChallengeResponse;
}
/**
* @brief Builds the account-password command in the form this server understands.
*
* Challenge-response servers take a scrypt verifier; servers that only advertise
* SupportsPasswordHash take a salted SHA-512 hash; anything older gets the plaintext,
* which is the only form it understands. Both password-change paths go through here so
* the two cannot drift apart and hand a plaintext password to a server that can hash it.
*/
Command_AccountPassword makeAccountPasswordCommand(const QString &oldPassword, const QString &newPassword) const;
const QString &getUserName() const
{
return userName;

View file

@ -125,6 +125,7 @@ RemoteClient::RemoteClient(QObject *parent, INetworkSettingsProvider *_networkSe
&RemoteClient::doSubmitForgotPasswordResetToServer);
connect(this, &RemoteClient::sigSubmitForgotPasswordChallengeToServer, this,
&RemoteClient::doSubmitForgotPasswordChallengeToServer);
connect(this, &RemoteClient::sigChangePasswordToServer, this, &RemoteClient::doChangePasswordToServer);
}
RemoteClient::~RemoteClient()
@ -354,6 +355,29 @@ void RemoteClient::submitPasswordVerifierResponse(const Response &response)
}
}
void RemoteClient::changePasswordToServer(const QString &oldPassword, const QString &newPassword)
{
emit sigChangePasswordToServer(oldPassword, newPassword);
}
void RemoteClient::doChangePasswordToServer(const QString &oldPassword, const QString &newPassword)
{
const Command_AccountPassword cmd = makeAccountPasswordCommand(oldPassword, newPassword);
PendingCommand *pend = prepareSessionCommand(cmd);
connect(pend, &PendingCommand::finished, this, &RemoteClient::accountPasswordResponse);
sendCommand(pend);
}
void RemoteClient::accountPasswordResponse(const Response &response)
{
if (response.response_code() == Response::RespOk) {
emit sigPasswordChangeSuccess();
} else {
emit sigPasswordChangeError(response.response_code());
}
}
void RemoteClient::processConnectionClosedEvent(const Event_ConnectionClosed & /*event*/)
{
doDisconnectFromServer();
@ -475,6 +499,23 @@ void RemoteClient::loginResponse(const Response &response)
emit notifyUserAboutUpdate();
}
} else if (response.response_code() == Response::RespPasswordChangeRequired) {
// The credentials were accepted: the server keeps this session open and serves
// nothing but ping and Command_AccountPassword until the password is replaced.
// Treating it as a failed login would disconnect before the dialog that collects
// the new password (queued to the UI thread behind this slot) can send anything:
// the command would sit in pendingCommands forever, because the ping timer that
// times it out stops with the connection. Keep the session and let the controller
// report the outcome through accountPasswordResponse().
QList<QString> missingFeatures;
if (resp.missing_features_size() > 0) {
for (int i = 0; i < resp.missing_features_size(); ++i) {
missingFeatures << QString::fromStdString(resp.missing_features(i));
}
}
setStatus(StatusPasswordChangeRequired);
emit loginError(response.response_code(), QString::fromStdString(resp.denied_reason_str()),
static_cast<quint32>(resp.denied_end_time()), missingFeatures);
} else if (response.response_code() != Response::RespNotConnected) {
QList<QString> missingFeatures;
if (resp.missing_features_size() > 0) {

View file

@ -71,6 +71,11 @@ signals:
//! should only store it for the connection it is currently negotiating, so
//! the hostname and user name are intentionally not part of the signal.
void sigPasswordVerifierReady(const QString &verifier);
//! \brief Outcome of the password change the server demanded at login.
void sigPasswordChangeSuccess();
void sigPasswordChangeError(int responseCode);
//! \brief Request a password change; queued to the client thread like the other requests.
void sigChangePasswordToServer(const QString &oldPassword, const QString &newPassword);
private slots:
void slotConnected();
void readData();
@ -99,6 +104,8 @@ private slots:
Command_Login generateCommandLogin();
void doSubmitPasswordVerifier();
void submitPasswordVerifierResponse(const Response &response);
void accountPasswordResponse(const Response &response);
void doChangePasswordToServer(const QString &oldPassword, const QString &newPassword);
void doDisconnectFromServer();
void doActivateToServer(const QString &_token);
void doRequestForgotPasswordToServer(const QString &hostname, unsigned int port, const QString &_userName);
@ -201,6 +208,10 @@ public:
unsigned int port,
const QString &_userName,
const QString &_email);
//! \brief Change the password of the account that just logged in, following the
//! server's forced-password-change reply. Emits sigPasswordChangeSuccess or
//! sigPasswordChangeError when the server answers.
void changePasswordToServer(const QString &oldPassword, const QString &newPassword);
};
#endif

View file

@ -131,6 +131,16 @@ AuthenticationResult Server::loginUser(Server_ProtocolHandler *session,
return authState;
}
if (authState == PasswordChangeRequired) {
// The credentials were right, but the account must choose a new password before it may
// use the server. Give the session an identity so it can complete that change, without
// registering a user session or announcing the user as logged in.
ServerInfo_User pendingData = databaseInterface->getUserData(name, true);
pendingData.set_address(session->getAddress().toStdString());
session->setUserInfo(pendingData);
return authState;
}
ServerInfo_User data = databaseInterface->getUserData(name, true);
data.set_address(session->getAddress().toStdString());
name = QString::fromStdString(data.name()); // Compensate for case indifference
@ -296,7 +306,9 @@ void Server::removeClient(Server_ProtocolHandler *client)
QWriteLocker locker(&clientsLock);
clients.removeAt(clientIndex);
ServerInfo_User *data = client->getUserInfo();
if (data) {
// A session that never completed login (for example one that still owes a password change)
// has no session id: it was never announced as joined, so it must not be announced as leaving.
if (data && data->has_session_id()) {
Event_UserLeft event;
event.set_name(data->name());
SessionEvent *se = Server_ProtocolHandler::prepareSessionEvent(event);
@ -311,12 +323,10 @@ void Server::removeClient(Server_ProtocolHandler *client)
users.remove(QString::fromStdString(data->name()));
qDebug() << "Server::removeClient: name=" << QString::fromStdString(data->name());
if (data->has_session_id()) {
const qint64 sessionId = data->session_id();
usersBySessionId.remove(sessionId);
emit endSession(sessionId);
qDebug() << "closed session id:" << sessionId;
}
const qint64 sessionId = data->session_id();
usersBySessionId.remove(sessionId);
emit endSession(sessionId);
qDebug() << "closed session id:" << sessionId;
}
qDebug() << "Server::removeClient: removed" << (void *)client << ";" << clients.size() << "clients; "
<< users.size() << "users left";
@ -330,7 +340,9 @@ QList<QString> Server::getOnlineModeratorList() const
ServerInfo_User *data = client->getUserInfo();
//! \todo This line should be updated in the event there is any type of new user level created.
if (data &&
// A session that still owes a forced password change has user info but no session id:
// it never joined, so it must not be reported as an online moderator either.
if (data && data->has_session_id() &&
(data->user_level() & ServerInfo_User::IsModerator || data->user_level() & ServerInfo_User::IsAdmin)) {
results << QString::fromStdString(data->name()).simplified();
}

View file

@ -64,8 +64,9 @@ Server_ProtocolHandler::Server_ProtocolHandler(Server *_server,
Server_DatabaseInterface *_databaseInterface,
QObject *parent)
: QObject(parent), Server_AbstractUserInterface(_server), deleted(false), databaseInterface(_databaseInterface),
authState(NotLoggedIn), usingRealPassword(false), acceptsUserListChanges(false), acceptsRoomListChanges(false),
idleClientWarningSent(false), timeRunning(0), lastDataReceived(0), lastActionReceived(0)
authState(NotLoggedIn), usingRealPassword(false), passwordChangePending(false), acceptsUserListChanges(false),
acceptsRoomListChanges(false), idleClientWarningSent(false), timeRunning(0), lastDataReceived(0),
lastActionReceived(0)
{
connect(server, &Server::pingClockTimeout, this, &Server_ProtocolHandler::pingClockTimeout);
@ -212,7 +213,10 @@ Response::ResponseCode Server_ProtocolHandler::processSessionCommandContainer(co
logDebugMessage(getSafeDebugString(sc));
}
const auto commandType = static_cast<SessionCommand::SessionCommandType>(num);
if (authState == NotLoggedIn && !isPreAuthSessionCommand(commandType)) {
if (passwordChangePending && commandType != SessionCommand::PING &&
commandType != SessionCommand::ACCOUNT_PASSWORD) {
resp = Response::RespFunctionNotAllowed;
} else if (authState == NotLoggedIn && !isPreAuthSessionCommand(commandType)) {
resp = Response::RespLoginNeeded;
} else {
switch (commandType) {
@ -489,6 +493,19 @@ void Server_ProtocolHandler::processCommandContainer(const CommandContainer &con
lastDataReceived = timeRunning;
// A session that still owes a forced password change may only reach the session family,
// where processSessionCommandContainer narrows it further to ping and the change itself.
// Every other family is rejected here, including a container that also carries a session
// command: the dispatch below prefers game/room over session, so testing only for the
// absence of a session command would let such a container through.
if (passwordChangePending &&
(cont.game_command_size() || cont.room_command_size() || cont.moderator_command_size() ||
cont.admin_command_size() || cont.developer_command_size())) {
sendResponseContainer(ResponseContainer(cont.has_cmd_id() ? cont.cmd_id() : -1),
Response::RespFunctionNotAllowed);
return;
}
ResponseContainer responseContainer(cont.has_cmd_id() ? cont.cmd_id() : -1);
Response::ResponseCode finalResponseCode;
@ -696,6 +713,11 @@ Response::ResponseCode Server_ProtocolHandler::cmdLogin(const Command_Login &cmd
server->recordFailedLogin(getAddress(), userName);
return Response::RespAccountNotActivated;
case PasswordChangeRequired:
// The credentials were right, but the account must choose a new password first.
// Keep the session authenticated just far enough for the client to do that:
// processCommandContainer refuses everything except the change itself.
authState = PasswordRight;
passwordChangePending = true;
return Response::RespPasswordChangeRequired;
default:
server->clearFailedLogins(getAddress(), userName);

View file

@ -46,6 +46,12 @@ protected:
Server_DatabaseInterface *databaseInterface;
AuthenticationResult authState;
bool usingRealPassword;
/**
* @brief True when the credentials were right but the account must choose a new password
* before it may use the server. Only ping, the password change and disconnecting
* are served while this is set.
*/
bool passwordChangePending;
bool acceptsUserListChanges;
bool acceptsRoomListChanges;
bool idleClientWarningSent;