Update password handling and session methods

This commit is contained in:
netkas 2025-01-05 01:23:43 -05:00
parent 8b9896f196
commit 85814913e4
11 changed files with 239 additions and 70 deletions

View file

@ -642,7 +642,6 @@
*
* @param string $hash The hash string to be validated.
* @return bool Returns true if the hash is valid and meets current security standards.
* @throws CryptographyException If the hash format is invalid or does not meet security requirements.
*/
public static function validatePasswordHash(string $hash): bool
{
@ -652,23 +651,22 @@
$argon2id_pattern = '/^\$argon2id\$v=\d+\$m=\d+,t=\d+,p=\d+\$[A-Za-z0-9+\/=]+\$[A-Za-z0-9+\/=]+$/D';
if (!preg_match($argon2id_pattern, $hash))
{
throw new CryptographyException("Invalid hash format");
return false;
}
// Step 2: Check if it needs rehashing (validates the hash structure)
if (sodium_crypto_pwhash_str_needs_rehash($hash, SODIUM_CRYPTO_PWHASH_OPSLIMIT_INTERACTIVE, SODIUM_CRYPTO_PWHASH_MEMLIMIT_INTERACTIVE))
{
throw new CryptographyException("Hash does not meet current security requirements");
return false;
}
}
catch (Exception)
{
return false;
}
// If all checks pass, the hash is valid.
return true;
}
catch (Exception $e)
{
throw new CryptographyException("Invalid hash: " . $e->getMessage());
}
}
/**
* Verifies a password against a stored hash.

View file

@ -3,7 +3,6 @@
namespace Socialbox\Classes\StandardMethods;
use Socialbox\Abstracts\Method;
use Socialbox\Enums\StandardError;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
@ -16,11 +15,6 @@
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if($request->getSessionUuid() === null)
{
return $rpcRequest->produceError(StandardError::SESSION_REQUIRED);
}
return $rpcRequest->produceResponse($request->getSession()->toStandardSessionState());
}
}

View file

@ -0,0 +1,53 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Exception;
use Socialbox\Abstracts\Method;
use Socialbox\Classes\Configuration;
use Socialbox\Classes\Cryptography;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\PasswordManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class SettingsDeletePassword extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if(Configuration::getRegistrationConfiguration()->isPasswordRequired())
{
return $rpcRequest->produceError(StandardError::FORBIDDEN, 'A password is required for this server');
}
try
{
if (!PasswordManager::usesPassword($request->getPeer()->getUuid()))
{
return $rpcRequest->produceError(StandardError::METHOD_NOT_ALLOWED, "Cannot update password when one isn't already set, use 'settingsSetPassword' instead");
}
}
catch (DatabaseOperationException $e)
{
throw new StandardException('Failed to check password due to an internal exception', StandardError::INTERNAL_SERVER_ERROR, $e);
}
try
{
// Set the password
PasswordManager::updatePassword($request->getPeer(), $rpcRequest->getParameter('password'));
}
catch(Exception $e)
{
throw new StandardException('Failed to set password due to an internal exception', StandardError::INTERNAL_SERVER_ERROR, $e);
}
return $rpcRequest->produceResponse(true);
}
}

View file

@ -4,6 +4,7 @@
use Exception;
use Socialbox\Abstracts\Method;
use Socialbox\Classes\Cryptography;
use Socialbox\Enums\Flags\SessionFlags;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
@ -26,16 +27,16 @@
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, "Missing 'password' parameter");
}
if(!preg_match('/^[a-f0-9]{128}$/', $rpcRequest->getParameter('password')))
if(!Cryptography::validatePasswordHash($rpcRequest->getParameter('password')))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, "Invalid 'password' parameter, must be sha512 hexadecimal hash");
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, "Invalid 'password' parameter, must be a valid argon2id hash");
}
try
{
if (PasswordManager::usesPassword($request->getPeer()->getUuid()))
{
return $rpcRequest->produceError(StandardError::METHOD_NOT_ALLOWED, "Cannot set password when one is already set, use 'settingsChangePassword' instead");
return $rpcRequest->produceError(StandardError::METHOD_NOT_ALLOWED, "Cannot set password when one is already set, use 'settingsUpdatePassword' instead");
}
}
catch (DatabaseOperationException $e)
@ -48,11 +49,11 @@
// Set the password
PasswordManager::setPassword($request->getPeer(), $rpcRequest->getParameter('password'));
// Remove the SET_PASSWORD flag
SessionManager::removeFlags($request->getSessionUuid(), [SessionFlags::SET_PASSWORD]);
// Check & update the session flow
SessionManager::updateFlow($request->getSession());
// Remove the SET_PASSWORD flag & update the session flow if necessary
if($request->getSession()->flagExists(SessionFlags::SET_PASSWORD))
{
SessionManager::updateFlow($request->getSession(), [SessionFlags::SET_PASSWORD]);
}
}
catch(Exception $e)
{

View file

@ -0,0 +1,57 @@
<?php
namespace Socialbox\Classes\StandardMethods;
use Exception;
use Socialbox\Abstracts\Method;
use Socialbox\Classes\Cryptography;
use Socialbox\Enums\StandardError;
use Socialbox\Exceptions\DatabaseOperationException;
use Socialbox\Exceptions\StandardException;
use Socialbox\Interfaces\SerializableInterface;
use Socialbox\Managers\PasswordManager;
use Socialbox\Objects\ClientRequest;
use Socialbox\Objects\RpcRequest;
class SettingsUpdatePassword extends Method
{
/**
* @inheritDoc
*/
public static function execute(ClientRequest $request, RpcRequest $rpcRequest): ?SerializableInterface
{
if(!$rpcRequest->containsParameter('password'))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, "Missing 'password' parameter");
}
if(!Cryptography::validatePasswordHash($rpcRequest->getParameter('password')))
{
return $rpcRequest->produceError(StandardError::RPC_INVALID_ARGUMENTS, "Invalid 'password' parameter, must be a valid argon2id hash");
}
try
{
if (!PasswordManager::usesPassword($request->getPeer()->getUuid()))
{
return $rpcRequest->produceError(StandardError::METHOD_NOT_ALLOWED, "Cannot update password when one isn't already set, use 'settingsSetPassword' instead");
}
}
catch (DatabaseOperationException $e)
{
throw new StandardException('Failed to check password due to an internal exception', StandardError::INTERNAL_SERVER_ERROR, $e);
}
try
{
// Set the password
PasswordManager::updatePassword($request->getPeer(), $rpcRequest->getParameter('password'));
}
catch(Exception $e)
{
throw new StandardException('Failed to set password due to an internal exception', StandardError::INTERNAL_SERVER_ERROR, $e);
}
return $rpcRequest->produceResponse(true);
}
}

View file

@ -7,7 +7,7 @@ enum StandardError : int
// Fallback Codes
case UNKNOWN = -1;
// Server/Request Errors
// Generic Errors
case INTERNAL_SERVER_ERROR = -100;
case SERVER_UNAVAILABLE = -101;
case BAD_REQUEST = -102;
@ -26,12 +26,7 @@ enum StandardError : int
// Authentication/Cryptography Errors
case INVALID_PUBLIC_KEY = -4000; // *
case SESSION_REQUIRED = -5001; // *
case SESSION_NOT_FOUND = -5002; // *
case SESSION_EXPIRED = -5003; // *
case SESSION_DHE_REQUIRED = -5004; // *
case ALREADY_AUTHENTICATED = -6005;
case UNSUPPORTED_AUTHENTICATION_TYPE = -6006;
case AUTHENTICATION_REQUIRED = -6007;
@ -55,7 +50,7 @@ enum StandardError : int
{
return match ($this)
{
self::UNKNOWN => 'Unknown Error',
default => 'Unknown Error',
self::RPC_METHOD_NOT_FOUND => 'The request method was not found',
self::RPC_INVALID_ARGUMENTS => 'The request method contains one or more invalid arguments',
@ -68,7 +63,6 @@ enum StandardError : int
self::ALREADY_AUTHENTICATED => 'The action cannot be preformed while authenticated',
self::AUTHENTICATION_REQUIRED => 'Authentication is required to preform this action',
self::SESSION_NOT_FOUND => 'The requested session UUID was not found',
self::SESSION_REQUIRED => 'A session is required to preform this action',
self::REGISTRATION_DISABLED => 'Registration is disabled on the server',
self::CAPTCHA_NOT_AVAILABLE => 'Captcha is not available',
self::INCORRECT_CAPTCHA_ANSWER => 'The Captcha answer is incorrect',
@ -79,8 +73,6 @@ enum StandardError : int
self::USERNAME_ALREADY_EXISTS => 'The given username already exists on the network',
self::NOT_REGISTERED => 'The given username is not registered on the server',
self::METHOD_NOT_ALLOWED => 'The requested method is not allowed',
self::SESSION_EXPIRED => 'The session has expired',
self::SESSION_DHE_REQUIRED => 'The session requires DHE to be established',
};
}

View file

@ -2,6 +2,7 @@
namespace Socialbox\Enums;
use Socialbox\Classes\Configuration;
use Socialbox\Classes\StandardMethods\AcceptCommunityGuidelines;
use Socialbox\Classes\StandardMethods\AcceptPrivacyPolicy;
use Socialbox\Classes\StandardMethods\AcceptTermsOfService;
@ -12,9 +13,11 @@
use Socialbox\Classes\StandardMethods\Ping;
use Socialbox\Classes\StandardMethods\SettingsAddSigningKey;
use Socialbox\Classes\StandardMethods\SettingsDeleteDisplayName;
use Socialbox\Classes\StandardMethods\SettingsDeletePassword;
use Socialbox\Classes\StandardMethods\SettingsGetSigningKeys;
use Socialbox\Classes\StandardMethods\SettingsSetDisplayName;
use Socialbox\Classes\StandardMethods\SettingsSetPassword;
use Socialbox\Classes\StandardMethods\SettingsUpdatePassword;
use Socialbox\Classes\StandardMethods\VerificationAnswerImageCaptcha;
use Socialbox\Classes\StandardMethods\VerificationGetImageCaptcha;
use Socialbox\Enums\Flags\SessionFlags;
@ -54,6 +57,8 @@
case VERIFICATION_ANSWER_EXTERNAL_URL = 'verificationAnswerExternalUrl';
case SETTINGS_SET_PASSWORD = 'settingsSetPassword';
case SETTINGS_UPDATE_PASSWORD = 'settingsUpdatePassword';
case SETTINGS_DELETE_PASSWORD = 'settingsDeletePassword';
case SETTINGS_SET_OTP = 'settingsSetOtp';
case SETTINGS_SET_DISPLAY_NAME = 'settingsSetDisplayName';
case SETTINGS_DELETE_DISPLAY_NAME = 'settingsDeleteDisplayName';
@ -91,6 +96,8 @@
self::VERIFICATION_ANSWER_IMAGE_CAPTCHA => VerificationAnswerImageCaptcha::execute($request, $rpcRequest),
self::SETTINGS_SET_PASSWORD => SettingsSetPassword::execute($request, $rpcRequest),
self::SETTINGS_UPDATE_PASSWORD => SettingsUpdatePassword::execute($request, $rpcRequest),
self::SETTINGS_DELETE_PASSWORD => SettingsDeletePassword::execute($request, $rpcRequest),
self::SETTINGS_SET_DISPLAY_NAME => SettingsSetDisplayName::execute($request, $rpcRequest),
self::SETTINGS_DELETE_DISPLAY_NAME => SettingsDeleteDisplayName::execute($request, $rpcRequest),
@ -138,6 +145,38 @@
$session = $clientRequest->getSession();
// If the session is external (eg; coming from a different server)
// Servers will have their own access control mechanisms
if($session->isExternal())
{
// TODO: Implement server access control
}
// If the session is authenticated, then allow additional method calls
elseif($session->isAuthenticated())
{
// These methods are always allowed for authenticated users
$methods = array_merge($methods, [
self::SETTINGS_ADD_SIGNING_KEY,
self::SETTINGS_GET_SIGNING_KEYS,
self::SETTINGS_SET_DISPLAY_NAME,
self::SETTINGS_SET_PASSWORD,
]);
// Prevent the user from deleting their display name if it is required
if(!Configuration::getRegistrationConfiguration()->isDisplayNameRequired())
{
$methods[] = self::SETTINGS_DELETE_DISPLAY_NAME;
}
// Always allow the authenticated user to change their password
if(!in_array(SessionFlags::SET_PASSWORD, $session->getFlags()))
{
$methods[] = self::SETTINGS_SET_PASSWORD;
}
}
// If the session isn't authenticated nor a host, a limited set of methods is available
else
{
// If the flag `VER_PRIVACY_POLICY` is set, then the user can accept the privacy policy
if($session->flagExists(SessionFlags::VER_PRIVACY_POLICY))
{
@ -164,22 +203,15 @@
}
// If the flag `SET_PASSWORD` is set, then the user has to set a password
if(in_array(SessionFlags::SET_PASSWORD, $session->getFlags()))
if($session->flagExists(SessionFlags::SET_PASSWORD))
{
$methods[] = self::SETTINGS_SET_PASSWORD;
}
// If the user is authenticated, then allow additional method calls
if($session->isAuthenticated())
// If the flag `SET_DISPLAY_NAME` is set, then the user has to set a display name
if($session->flagExists(SessionFlags::SET_DISPLAY_NAME))
{
// Authenticated users can always manage their signing keys
$methods[] = self::SETTINGS_ADD_SIGNING_KEY;
$methods[] = self::SETTINGS_GET_SIGNING_KEYS;
// Always allow the authenticated user to change their password
if(!in_array(SessionFlags::SET_PASSWORD, $session->getFlags()))
{
$methods[] = self::SETTINGS_SET_PASSWORD;
$methods[] = self::SETTINGS_SET_DISPLAY_NAME;
}
}

View file

@ -115,6 +115,32 @@
}
}
/**
* Deletes the stored password for a specific peer.
*
* @param string|RegisteredPeerRecord $peerUuid The unique identifier of the peer, or an instance of RegisteredPeerRecord.
* @return void
* @throws DatabaseOperationException If an error occurs during the database operation.
*/
public static function deletePassword(string|RegisteredPeerRecord $peerUuid): void
{
if($peerUuid instanceof RegisteredPeerRecord)
{
$peerUuid = $peerUuid->getUuid();
}
try
{
$stmt = Database::getConnection()->prepare('DELETE FROM authentication_passwords WHERE peer_uuid=:uuid');
$stmt->bindParam(':uuid', $peerUuid);
$stmt->execute();
}
catch(PDOException $e)
{
throw new DatabaseOperationException('An error occurred while deleting the password', $e);
}
}
/**
* Verifies a given password against a stored password hash for a specific peer.
*

View file

@ -423,11 +423,12 @@
* Marks the session as complete if all necessary conditions are met.
*
* @param SessionRecord $session The session record to evaluate and potentially mark as complete.
* @param array $flagsToRemove An array of flags to remove from the session if it is marked as complete.
* @return void
* @throws DatabaseOperationException If there is an error while updating the session in the database.
* @throws StandardException If the session record cannot be found or if there is an error during retrieval.
* @return void
*/
public static function updateFlow(SessionRecord $session): void
public static function updateFlow(SessionRecord $session, array $flagsToRemove=[]): void
{
// Don't do anything if the session is already authenticated
if(!in_array(SessionFlags::REGISTRATION_REQUIRED, $session->getFlags()) || !in_array(SessionFlags::AUTHENTICATION_REQUIRED, $session->getFlags()))
@ -435,6 +436,9 @@
return;
}
self::removeFlags($session->getUuid(), $flagsToRemove);
$session = self::getSession($session->getUuid());
// Check if all registration/authentication requirements are met
if(SessionFlags::isComplete($session->getFlags()))
{

View file

@ -228,13 +228,14 @@
}
/**
* Determines if the server is external.
* Determines if the user is considered external by checking if the username is 'host' and the server
* is not the same as the domain from the configuration.
*
* @return bool True if the server is external, false otherwise.
* @return bool True if the user is external, false otherwise.
*/
public function isExternal(): bool
{
return $this->server === 'host';
return $this->username === 'host' && $this->server !== Configuration::getInstanceConfiguration()->getDomain();
}
/**

View file

@ -260,6 +260,17 @@
return $this->clientVersion;
}
/**
* Returns whether the session is external.
*
* @return bool True if the session is external, false otherwise.
* @throws DatabaseOperationException Thrown if the peer record cannot be retrieved.
*/
public function isExternal(): bool
{
return RegisteredPeerManager::getPeer($this->peerUuid)->isExternal();
}
/**
* Converts the current session state into a standard session state object.
*