From 85814913e47eee9e3cb02f593ca5740d7dcad624 Mon Sep 17 00:00:00 2001 From: netkas Date: Sun, 5 Jan 2025 01:23:43 -0500 Subject: [PATCH] Update password handling and session methods --- src/Socialbox/Classes/Cryptography.php | 14 ++- .../StandardMethods/GetSessionState.php | 6 -- .../SettingsDeletePassword.php | 53 ++++++++++ .../StandardMethods/SettingsSetPassword.php | 17 ++-- .../SettingsUpdatePassword.php | 57 +++++++++++ src/Socialbox/Enums/StandardError.php | 12 +-- src/Socialbox/Enums/StandardMethods.php | 98 ++++++++++++------- src/Socialbox/Managers/PasswordManager.php | 26 +++++ src/Socialbox/Managers/SessionManager.php | 8 +- .../Objects/Database/RegisteredPeerRecord.php | 7 +- .../Objects/Database/SessionRecord.php | 11 +++ 11 files changed, 239 insertions(+), 70 deletions(-) create mode 100644 src/Socialbox/Classes/StandardMethods/SettingsDeletePassword.php create mode 100644 src/Socialbox/Classes/StandardMethods/SettingsUpdatePassword.php diff --git a/src/Socialbox/Classes/Cryptography.php b/src/Socialbox/Classes/Cryptography.php index 8b6fdee..dc1bb00 100644 --- a/src/Socialbox/Classes/Cryptography.php +++ b/src/Socialbox/Classes/Cryptography.php @@ -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,22 +651,21 @@ $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; } - - // If all checks pass, the hash is valid. - return true; } - catch (Exception $e) + catch (Exception) { - throw new CryptographyException("Invalid hash: " . $e->getMessage()); + return false; } + + return true; } /** diff --git a/src/Socialbox/Classes/StandardMethods/GetSessionState.php b/src/Socialbox/Classes/StandardMethods/GetSessionState.php index 11f4d2d..dc45964 100644 --- a/src/Socialbox/Classes/StandardMethods/GetSessionState.php +++ b/src/Socialbox/Classes/StandardMethods/GetSessionState.php @@ -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()); } } \ No newline at end of file diff --git a/src/Socialbox/Classes/StandardMethods/SettingsDeletePassword.php b/src/Socialbox/Classes/StandardMethods/SettingsDeletePassword.php new file mode 100644 index 0000000..92259a4 --- /dev/null +++ b/src/Socialbox/Classes/StandardMethods/SettingsDeletePassword.php @@ -0,0 +1,53 @@ +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); + } + } \ No newline at end of file diff --git a/src/Socialbox/Classes/StandardMethods/SettingsSetPassword.php b/src/Socialbox/Classes/StandardMethods/SettingsSetPassword.php index 8241343..1c180dd 100644 --- a/src/Socialbox/Classes/StandardMethods/SettingsSetPassword.php +++ b/src/Socialbox/Classes/StandardMethods/SettingsSetPassword.php @@ -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) { diff --git a/src/Socialbox/Classes/StandardMethods/SettingsUpdatePassword.php b/src/Socialbox/Classes/StandardMethods/SettingsUpdatePassword.php new file mode 100644 index 0000000..eb6b62a --- /dev/null +++ b/src/Socialbox/Classes/StandardMethods/SettingsUpdatePassword.php @@ -0,0 +1,57 @@ +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); + } + } \ No newline at end of file diff --git a/src/Socialbox/Enums/StandardError.php b/src/Socialbox/Enums/StandardError.php index ef54bfd..3c0fbc6 100644 --- a/src/Socialbox/Enums/StandardError.php +++ b/src/Socialbox/Enums/StandardError.php @@ -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', }; } diff --git a/src/Socialbox/Enums/StandardMethods.php b/src/Socialbox/Enums/StandardMethods.php index 3ffb879..1f33ef5 100644 --- a/src/Socialbox/Enums/StandardMethods.php +++ b/src/Socialbox/Enums/StandardMethods.php @@ -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,43 +145,28 @@ $session = $clientRequest->getSession(); - // If the flag `VER_PRIVACY_POLICY` is set, then the user can accept the privacy policy - if($session->flagExists(SessionFlags::VER_PRIVACY_POLICY)) + // If the session is external (eg; coming from a different server) + // Servers will have their own access control mechanisms + if($session->isExternal()) { - $methods[] = self::ACCEPT_PRIVACY_POLICY; + // TODO: Implement server access control } - - // If the flag `VER_TERMS_OF_SERVICE` is set, then the user can accept the terms of service - if($session->flagExists(SessionFlags::VER_TERMS_OF_SERVICE)) + // If the session is authenticated, then allow additional method calls + elseif($session->isAuthenticated()) { - $methods[] = self::ACCEPT_TERMS_OF_SERVICE; - } + // 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, + ]); - // If the flag `VER_COMMUNITY_GUIDELINES` is set, then the user can accept the community guidelines - if($session->flagExists(SessionFlags::VER_COMMUNITY_GUIDELINES)) - { - $methods[] = self::ACCEPT_COMMUNITY_GUIDELINES; - } - - // If the flag `VER_IMAGE_CAPTCHA` is set, then the user has to get and answer an image captcha - if($session->flagExists(SessionFlags::VER_IMAGE_CAPTCHA)) - { - $methods[] = self::VERIFICATION_GET_IMAGE_CAPTCHA; - $methods[] = self::VERIFICATION_ANSWER_IMAGE_CAPTCHA; - } - - // If the flag `SET_PASSWORD` is set, then the user has to set a password - if(in_array(SessionFlags::SET_PASSWORD, $session->getFlags())) - { - $methods[] = self::SETTINGS_SET_PASSWORD; - } - - // If the user is authenticated, then allow additional method calls - if($session->isAuthenticated()) - { - // Authenticated users can always manage their signing keys - $methods[] = self::SETTINGS_ADD_SIGNING_KEY; - $methods[] = self::SETTINGS_GET_SIGNING_KEYS; + // 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())) @@ -182,6 +174,46 @@ $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)) + { + $methods[] = self::ACCEPT_PRIVACY_POLICY; + } + + // If the flag `VER_TERMS_OF_SERVICE` is set, then the user can accept the terms of service + if($session->flagExists(SessionFlags::VER_TERMS_OF_SERVICE)) + { + $methods[] = self::ACCEPT_TERMS_OF_SERVICE; + } + + // If the flag `VER_COMMUNITY_GUIDELINES` is set, then the user can accept the community guidelines + if($session->flagExists(SessionFlags::VER_COMMUNITY_GUIDELINES)) + { + $methods[] = self::ACCEPT_COMMUNITY_GUIDELINES; + } + + // If the flag `VER_IMAGE_CAPTCHA` is set, then the user has to get and answer an image captcha + if($session->flagExists(SessionFlags::VER_IMAGE_CAPTCHA)) + { + $methods[] = self::VERIFICATION_GET_IMAGE_CAPTCHA; + $methods[] = self::VERIFICATION_ANSWER_IMAGE_CAPTCHA; + } + + // If the flag `SET_PASSWORD` is set, then the user has to set a password + if($session->flagExists(SessionFlags::SET_PASSWORD)) + { + $methods[] = self::SETTINGS_SET_PASSWORD; + } + + // If the flag `SET_DISPLAY_NAME` is set, then the user has to set a display name + if($session->flagExists(SessionFlags::SET_DISPLAY_NAME)) + { + $methods[] = self::SETTINGS_SET_DISPLAY_NAME; + } + } return $methods; } diff --git a/src/Socialbox/Managers/PasswordManager.php b/src/Socialbox/Managers/PasswordManager.php index 313cc4f..0a6947c 100644 --- a/src/Socialbox/Managers/PasswordManager.php +++ b/src/Socialbox/Managers/PasswordManager.php @@ -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. * diff --git a/src/Socialbox/Managers/SessionManager.php b/src/Socialbox/Managers/SessionManager.php index d58d745..ef36946 100644 --- a/src/Socialbox/Managers/SessionManager.php +++ b/src/Socialbox/Managers/SessionManager.php @@ -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())) { diff --git a/src/Socialbox/Objects/Database/RegisteredPeerRecord.php b/src/Socialbox/Objects/Database/RegisteredPeerRecord.php index 56ad984..a88f48e 100644 --- a/src/Socialbox/Objects/Database/RegisteredPeerRecord.php +++ b/src/Socialbox/Objects/Database/RegisteredPeerRecord.php @@ -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(); } /** diff --git a/src/Socialbox/Objects/Database/SessionRecord.php b/src/Socialbox/Objects/Database/SessionRecord.php index 37145d1..6492528 100644 --- a/src/Socialbox/Objects/Database/SessionRecord.php +++ b/src/Socialbox/Objects/Database/SessionRecord.php @@ -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. *