From fab87c2696b9d6a26310f1bfc024b018ca5184fe Mon Sep 17 00:00:00 2001 From: VirtualTam Date: Fri, 27 Apr 2018 22:12:22 +0200 Subject: Move LoginManager and SessionManager to the Security namespace Signed-off-by: VirtualTam --- application/LoginManager.php | 238 -------------------------------- application/SessionManager.php | 179 ------------------------ application/security/LoginManager.php | 238 ++++++++++++++++++++++++++++++++ application/security/SessionManager.php | 179 ++++++++++++++++++++++++ composer.json | 3 +- index.php | 4 +- tests/LoginManagerTest.php | 199 -------------------------- tests/SessionManagerTest.php | 149 -------------------- tests/security/LoginManagerTest.php | 199 ++++++++++++++++++++++++++ tests/security/SessionManagerTest.php | 149 ++++++++++++++++++++ 10 files changed, 769 insertions(+), 768 deletions(-) delete mode 100644 application/LoginManager.php delete mode 100644 application/SessionManager.php create mode 100644 application/security/LoginManager.php create mode 100644 application/security/SessionManager.php delete mode 100644 tests/LoginManagerTest.php delete mode 100644 tests/SessionManagerTest.php create mode 100644 tests/security/LoginManagerTest.php create mode 100644 tests/security/SessionManagerTest.php diff --git a/application/LoginManager.php b/application/LoginManager.php deleted file mode 100644 index 27d06705..00000000 --- a/application/LoginManager.php +++ /dev/null @@ -1,238 +0,0 @@ -globals = &$globals; - $this->configManager = $configManager; - $this->sessionManager = $sessionManager; - $this->banFile = $this->configManager->get('resource.ban_file', 'data/ipbans.php'); - $this->readBanFile(); - if ($this->configManager->get('security.open_shaarli')) { - $this->openShaarli = true; - } - } - - /** - * Check user session state and validity (expiration) - * - * @param array $cookie The $_COOKIE array - * @param string $webPath Path on the server in which the cookie will be available on - * @param string $clientIpId Client IP address identifier - * @param string $token Session token - * - * @return bool true if the user session is valid, false otherwise - */ - public function checkLoginState($cookie, $webPath, $clientIpId, $token) - { - if (! $this->configManager->exists('credentials.login')) { - // Shaarli is not configured yet - $this->isLoggedIn = false; - return; - } - - if (isset($cookie[SessionManager::$LOGGED_IN_COOKIE]) - && $cookie[SessionManager::$LOGGED_IN_COOKIE] === $token - ) { - $this->sessionManager->storeLoginInfo($clientIpId); - $this->isLoggedIn = true; - } - - if ($this->sessionManager->hasSessionExpired() - || $this->sessionManager->hasClientIpChanged($clientIpId) - ) { - $this->sessionManager->logout($webPath); - $this->isLoggedIn = false; - return; - } - - $this->sessionManager->extendSession(); - } - - /** - * Return whether the user is currently logged in - * - * @return true when the user is logged in, false otherwise - */ - public function isLoggedIn() - { - if ($this->openShaarli) { - return true; - } - return $this->isLoggedIn; - } - - /** - * Check user credentials are valid - * - * @param string $remoteIp Remote client IP address - * @param string $clientIpId Client IP address identifier - * @param string $login Username - * @param string $password Password - * - * @return bool true if the provided credentials are valid, false otherwise - */ - public function checkCredentials($remoteIp, $clientIpId, $login, $password) - { - $hash = sha1($password . $login . $this->configManager->get('credentials.salt')); - - if ($login != $this->configManager->get('credentials.login') - || $hash != $this->configManager->get('credentials.hash') - ) { - logm( - $this->configManager->get('resource.log'), - $remoteIp, - 'Login failed for user ' . $login - ); - return false; - } - - $this->sessionManager->storeLoginInfo($clientIpId); - logm( - $this->configManager->get('resource.log'), - $remoteIp, - 'Login successful' - ); - return true; - } - - /** - * Read a file containing banned IPs - */ - protected function readBanFile() - { - if (! file_exists($this->banFile)) { - return; - } - include $this->banFile; - } - - /** - * Write the banned IPs to a file - */ - protected function writeBanFile() - { - if (! array_key_exists('IPBANS', $this->globals)) { - return; - } - file_put_contents( - $this->banFile, - "globals['IPBANS'], true) . ";\n?>" - ); - } - - /** - * Handle a failed login and ban the IP after too many failed attempts - * - * @param array $server The $_SERVER array - */ - public function handleFailedLogin($server) - { - $ip = $server['REMOTE_ADDR']; - $trusted = $this->configManager->get('security.trusted_proxies', []); - - if (in_array($ip, $trusted)) { - $ip = getIpAddressFromProxy($server, $trusted); - if (! $ip) { - // the IP is behind a trusted forward proxy, but is not forwarded - // in the HTTP headers, so we do nothing - return; - } - } - - // increment the fail count for this IP - if (isset($this->globals['IPBANS']['FAILURES'][$ip])) { - $this->globals['IPBANS']['FAILURES'][$ip]++; - } else { - $this->globals['IPBANS']['FAILURES'][$ip] = 1; - } - - if ($this->globals['IPBANS']['FAILURES'][$ip] >= $this->configManager->get('security.ban_after')) { - $this->globals['IPBANS']['BANS'][$ip] = time() + $this->configManager->get('security.ban_duration', 1800); - logm( - $this->configManager->get('resource.log'), - $server['REMOTE_ADDR'], - 'IP address banned from login' - ); - } - $this->writeBanFile(); - } - - /** - * Handle a successful login - * - * @param array $server The $_SERVER array - */ - public function handleSuccessfulLogin($server) - { - $ip = $server['REMOTE_ADDR']; - // FIXME unban when behind a trusted proxy? - - unset($this->globals['IPBANS']['FAILURES'][$ip]); - unset($this->globals['IPBANS']['BANS'][$ip]); - - $this->writeBanFile(); - } - - /** - * Check if the user can login from this IP - * - * @param array $server The $_SERVER array - * - * @return bool true if the user is allowed to login - */ - public function canLogin($server) - { - $ip = $server['REMOTE_ADDR']; - - if (! isset($this->globals['IPBANS']['BANS'][$ip])) { - // the user is not banned - return true; - } - - if ($this->globals['IPBANS']['BANS'][$ip] > time()) { - // the user is still banned - return false; - } - - // the ban has expired, the user can attempt to log in again - logm($this->configManager->get('resource.log'), $server['REMOTE_ADDR'], 'Ban lifted.'); - unset($this->globals['IPBANS']['FAILURES'][$ip]); - unset($this->globals['IPBANS']['BANS'][$ip]); - - $this->writeBanFile(); - return true; - } -} diff --git a/application/SessionManager.php b/application/SessionManager.php deleted file mode 100644 index 63eeb8aa..00000000 --- a/application/SessionManager.php +++ /dev/null @@ -1,179 +0,0 @@ -session = &$session; - $this->conf = $conf; - } - - /** - * Generates a session token - * - * @return string token - */ - public function generateToken() - { - $token = sha1(uniqid('', true) .'_'. mt_rand() . $this->conf->get('credentials.salt')); - $this->session['tokens'][$token] = 1; - return $token; - } - - /** - * Checks the validity of a session token, and destroys it afterwards - * - * @param string $token The token to check - * - * @return bool true if the token is valid, else false - */ - public function checkToken($token) - { - if (! isset($this->session['tokens'][$token])) { - // the token is wrong, or has already been used - return false; - } - - // destroy the token to prevent future use - unset($this->session['tokens'][$token]); - return true; - } - - /** - * Validate session ID to prevent Full Path Disclosure. - * - * See #298. - * The session ID's format depends on the hash algorithm set in PHP settings - * - * @param string $sessionId Session ID - * - * @return true if valid, false otherwise. - * - * @see http://php.net/manual/en/function.hash-algos.php - * @see http://php.net/manual/en/session.configuration.php - */ - public static function checkId($sessionId) - { - if (empty($sessionId)) { - return false; - } - - if (!$sessionId) { - return false; - } - - if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) { - return false; - } - - return true; - } - - /** - * Store user login information after a successful login - * - * @param string $clientIpId Client IP address identifier - */ - public function storeLoginInfo($clientIpId) - { - // Generate unique random number (different than phpsessionid) - $this->session['uid'] = sha1(uniqid('', true) . '_' . mt_rand()); - $this->session['ip'] = $clientIpId; - $this->session['username'] = $this->conf->get('credentials.login'); - $this->session['expires_on'] = time() + self::$INACTIVITY_TIMEOUT; - } - - /** - * Extend session validity - */ - public function extendSession() - { - if (! empty($this->session['longlastingsession'])) { - // "Stay signed in" is enabled - $this->session['expires_on'] = time() + $this->session['longlastingsession']; - return; - } - $this->session['expires_on'] = time() + self::$INACTIVITY_TIMEOUT; - } - - /** - * Logout a user by unsetting all login information - * - * See: - * - https://secure.php.net/manual/en/function.setcookie.php - * - * @param string $webPath path on the server in which the cookie will be available on - */ - public function logout($webPath) - { - if (isset($this->session)) { - unset($this->session['uid']); - unset($this->session['ip']); - unset($this->session['username']); - unset($this->session['visibility']); - unset($this->session['untaggedonly']); - } - setcookie(self::$LOGGED_IN_COOKIE, 'false', 0, $webPath); - } - - /** - * Check whether the session has expired - * - * @param string $clientIpId Client IP address identifier - * - * @return bool true if the session has expired, false otherwise - */ - public function hasSessionExpired() - { - if (empty($this->session['uid'])) { - return true; - } - if (time() >= $this->session['expires_on']) { - return true; - } - return false; - } - - /** - * Check whether the client IP address has changed - * - * @param string $clientIpId Client IP address identifier - * - * @return bool true if the IP has changed, false if it has not, or - * if session protection has been disabled - */ - public function hasClientIpChanged($clientIpId) - { - if ($this->conf->get('security.session_protection_disabled') === true) { - return false; - } - if ($this->session['ip'] == $clientIpId) { - return false; - } - return true; - } -} diff --git a/application/security/LoginManager.php b/application/security/LoginManager.php new file mode 100644 index 00000000..e7b9b21e --- /dev/null +++ b/application/security/LoginManager.php @@ -0,0 +1,238 @@ +globals = &$globals; + $this->configManager = $configManager; + $this->sessionManager = $sessionManager; + $this->banFile = $this->configManager->get('resource.ban_file', 'data/ipbans.php'); + $this->readBanFile(); + if ($this->configManager->get('security.open_shaarli')) { + $this->openShaarli = true; + } + } + + /** + * Check user session state and validity (expiration) + * + * @param array $cookie The $_COOKIE array + * @param string $webPath Path on the server in which the cookie will be available on + * @param string $clientIpId Client IP address identifier + * @param string $token Session token + * + * @return bool true if the user session is valid, false otherwise + */ + public function checkLoginState($cookie, $webPath, $clientIpId, $token) + { + if (! $this->configManager->exists('credentials.login')) { + // Shaarli is not configured yet + $this->isLoggedIn = false; + return; + } + + if (isset($cookie[SessionManager::$LOGGED_IN_COOKIE]) + && $cookie[SessionManager::$LOGGED_IN_COOKIE] === $token + ) { + $this->sessionManager->storeLoginInfo($clientIpId); + $this->isLoggedIn = true; + } + + if ($this->sessionManager->hasSessionExpired() + || $this->sessionManager->hasClientIpChanged($clientIpId) + ) { + $this->sessionManager->logout($webPath); + $this->isLoggedIn = false; + return; + } + + $this->sessionManager->extendSession(); + } + + /** + * Return whether the user is currently logged in + * + * @return true when the user is logged in, false otherwise + */ + public function isLoggedIn() + { + if ($this->openShaarli) { + return true; + } + return $this->isLoggedIn; + } + + /** + * Check user credentials are valid + * + * @param string $remoteIp Remote client IP address + * @param string $clientIpId Client IP address identifier + * @param string $login Username + * @param string $password Password + * + * @return bool true if the provided credentials are valid, false otherwise + */ + public function checkCredentials($remoteIp, $clientIpId, $login, $password) + { + $hash = sha1($password . $login . $this->configManager->get('credentials.salt')); + + if ($login != $this->configManager->get('credentials.login') + || $hash != $this->configManager->get('credentials.hash') + ) { + logm( + $this->configManager->get('resource.log'), + $remoteIp, + 'Login failed for user ' . $login + ); + return false; + } + + $this->sessionManager->storeLoginInfo($clientIpId); + logm( + $this->configManager->get('resource.log'), + $remoteIp, + 'Login successful' + ); + return true; + } + + /** + * Read a file containing banned IPs + */ + protected function readBanFile() + { + if (! file_exists($this->banFile)) { + return; + } + include $this->banFile; + } + + /** + * Write the banned IPs to a file + */ + protected function writeBanFile() + { + if (! array_key_exists('IPBANS', $this->globals)) { + return; + } + file_put_contents( + $this->banFile, + "globals['IPBANS'], true) . ";\n?>" + ); + } + + /** + * Handle a failed login and ban the IP after too many failed attempts + * + * @param array $server The $_SERVER array + */ + public function handleFailedLogin($server) + { + $ip = $server['REMOTE_ADDR']; + $trusted = $this->configManager->get('security.trusted_proxies', []); + + if (in_array($ip, $trusted)) { + $ip = getIpAddressFromProxy($server, $trusted); + if (! $ip) { + // the IP is behind a trusted forward proxy, but is not forwarded + // in the HTTP headers, so we do nothing + return; + } + } + + // increment the fail count for this IP + if (isset($this->globals['IPBANS']['FAILURES'][$ip])) { + $this->globals['IPBANS']['FAILURES'][$ip]++; + } else { + $this->globals['IPBANS']['FAILURES'][$ip] = 1; + } + + if ($this->globals['IPBANS']['FAILURES'][$ip] >= $this->configManager->get('security.ban_after')) { + $this->globals['IPBANS']['BANS'][$ip] = time() + $this->configManager->get('security.ban_duration', 1800); + logm( + $this->configManager->get('resource.log'), + $server['REMOTE_ADDR'], + 'IP address banned from login' + ); + } + $this->writeBanFile(); + } + + /** + * Handle a successful login + * + * @param array $server The $_SERVER array + */ + public function handleSuccessfulLogin($server) + { + $ip = $server['REMOTE_ADDR']; + // FIXME unban when behind a trusted proxy? + + unset($this->globals['IPBANS']['FAILURES'][$ip]); + unset($this->globals['IPBANS']['BANS'][$ip]); + + $this->writeBanFile(); + } + + /** + * Check if the user can login from this IP + * + * @param array $server The $_SERVER array + * + * @return bool true if the user is allowed to login + */ + public function canLogin($server) + { + $ip = $server['REMOTE_ADDR']; + + if (! isset($this->globals['IPBANS']['BANS'][$ip])) { + // the user is not banned + return true; + } + + if ($this->globals['IPBANS']['BANS'][$ip] > time()) { + // the user is still banned + return false; + } + + // the ban has expired, the user can attempt to log in again + logm($this->configManager->get('resource.log'), $server['REMOTE_ADDR'], 'Ban lifted.'); + unset($this->globals['IPBANS']['FAILURES'][$ip]); + unset($this->globals['IPBANS']['BANS'][$ip]); + + $this->writeBanFile(); + return true; + } +} diff --git a/application/security/SessionManager.php b/application/security/SessionManager.php new file mode 100644 index 00000000..6f004b24 --- /dev/null +++ b/application/security/SessionManager.php @@ -0,0 +1,179 @@ +session = &$session; + $this->conf = $conf; + } + + /** + * Generates a session token + * + * @return string token + */ + public function generateToken() + { + $token = sha1(uniqid('', true) .'_'. mt_rand() . $this->conf->get('credentials.salt')); + $this->session['tokens'][$token] = 1; + return $token; + } + + /** + * Checks the validity of a session token, and destroys it afterwards + * + * @param string $token The token to check + * + * @return bool true if the token is valid, else false + */ + public function checkToken($token) + { + if (! isset($this->session['tokens'][$token])) { + // the token is wrong, or has already been used + return false; + } + + // destroy the token to prevent future use + unset($this->session['tokens'][$token]); + return true; + } + + /** + * Validate session ID to prevent Full Path Disclosure. + * + * See #298. + * The session ID's format depends on the hash algorithm set in PHP settings + * + * @param string $sessionId Session ID + * + * @return true if valid, false otherwise. + * + * @see http://php.net/manual/en/function.hash-algos.php + * @see http://php.net/manual/en/session.configuration.php + */ + public static function checkId($sessionId) + { + if (empty($sessionId)) { + return false; + } + + if (!$sessionId) { + return false; + } + + if (!preg_match('/^[a-zA-Z0-9,-]{2,128}$/', $sessionId)) { + return false; + } + + return true; + } + + /** + * Store user login information after a successful login + * + * @param string $clientIpId Client IP address identifier + */ + public function storeLoginInfo($clientIpId) + { + // Generate unique random number (different than phpsessionid) + $this->session['uid'] = sha1(uniqid('', true) . '_' . mt_rand()); + $this->session['ip'] = $clientIpId; + $this->session['username'] = $this->conf->get('credentials.login'); + $this->session['expires_on'] = time() + self::$INACTIVITY_TIMEOUT; + } + + /** + * Extend session validity + */ + public function extendSession() + { + if (! empty($this->session['longlastingsession'])) { + // "Stay signed in" is enabled + $this->session['expires_on'] = time() + $this->session['longlastingsession']; + return; + } + $this->session['expires_on'] = time() + self::$INACTIVITY_TIMEOUT; + } + + /** + * Logout a user by unsetting all login information + * + * See: + * - https://secure.php.net/manual/en/function.setcookie.php + * + * @param string $webPath path on the server in which the cookie will be available on + */ + public function logout($webPath) + { + if (isset($this->session)) { + unset($this->session['uid']); + unset($this->session['ip']); + unset($this->session['username']); + unset($this->session['visibility']); + unset($this->session['untaggedonly']); + } + setcookie(self::$LOGGED_IN_COOKIE, 'false', 0, $webPath); + } + + /** + * Check whether the session has expired + * + * @param string $clientIpId Client IP address identifier + * + * @return bool true if the session has expired, false otherwise + */ + public function hasSessionExpired() + { + if (empty($this->session['uid'])) { + return true; + } + if (time() >= $this->session['expires_on']) { + return true; + } + return false; + } + + /** + * Check whether the client IP address has changed + * + * @param string $clientIpId Client IP address identifier + * + * @return bool true if the IP has changed, false if it has not, or + * if session protection has been disabled + */ + public function hasClientIpChanged($clientIpId) + { + if ($this->conf->get('security.session_protection_disabled') === true) { + return false; + } + if ($this->session['ip'] == $clientIpId) { + return false; + } + return true; + } +} diff --git a/composer.json b/composer.json index 15e082f8..0d4c623c 100644 --- a/composer.json +++ b/composer.json @@ -36,7 +36,8 @@ "Shaarli\\Api\\Controllers\\": "application/api/controllers", "Shaarli\\Api\\Exceptions\\": "application/api/exceptions", "Shaarli\\Config\\": "application/config/", - "Shaarli\\Config\\Exception\\": "application/config/exception" + "Shaarli\\Config\\Exception\\": "application/config/exception", + "Shaarli\\Security\\": "application/security" } } } diff --git a/index.php b/index.php index 30bfc170..139812d7 100644 --- a/index.php +++ b/index.php @@ -78,8 +78,8 @@ require_once 'application/Updater.php'; use \Shaarli\Languages; use \Shaarli\ThemeUtils; use \Shaarli\Config\ConfigManager; -use \Shaarli\LoginManager; -use \Shaarli\SessionManager; +use \Shaarli\Security\LoginManager; +use \Shaarli\Security\SessionManager; // Ensure the PHP version is supported try { diff --git a/tests/LoginManagerTest.php b/tests/LoginManagerTest.php deleted file mode 100644 index 27ca0db5..00000000 --- a/tests/LoginManagerTest.php +++ /dev/null @@ -1,199 +0,0 @@ -banFile)) { - unlink($this->banFile); - } - - $this->configManager = new \FakeConfigManager([ - 'resource.ban_file' => $this->banFile, - 'resource.log' => $this->logFile, - 'security.ban_after' => 4, - 'security.ban_duration' => 3600, - 'security.trusted_proxies' => [$this->trustedProxy], - ]); - - $this->globals = &$GLOBALS; - unset($this->globals['IPBANS']); - - $this->loginManager = new LoginManager($this->globals, $this->configManager, null); - $this->server['REMOTE_ADDR'] = $this->ipAddr; - } - - /** - * Wipe test resources - */ - public function tearDown() - { - unset($this->globals['IPBANS']); - } - - /** - * Instantiate a LoginManager and load ban records - */ - public function testReadBanFile() - { - file_put_contents( - $this->banFile, - " array('127.0.0.1' => 99));\n?>" - ); - new LoginManager($this->globals, $this->configManager, null); - $this->assertEquals(99, $this->globals['IPBANS']['FAILURES']['127.0.0.1']); - } - - /** - * Record a failed login attempt - */ - public function testHandleFailedLogin() - { - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - } - - /** - * Record a failed login attempt - IP behind a trusted proxy - */ - public function testHandleFailedLoginBehindTrustedProxy() - { - $server = [ - 'REMOTE_ADDR' => $this->trustedProxy, - 'HTTP_X_FORWARDED_FOR' => $this->ipAddr, - ]; - $this->loginManager->handleFailedLogin($server); - $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - - $this->loginManager->handleFailedLogin($server); - $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - } - - /** - * Record a failed login attempt - IP behind a trusted proxy but not forwarded - */ - public function testHandleFailedLoginBehindTrustedProxyNoIp() - { - $server = [ - 'REMOTE_ADDR' => $this->trustedProxy, - ]; - $this->loginManager->handleFailedLogin($server); - $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr])); - - $this->loginManager->handleFailedLogin($server); - $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr])); - } - - /** - * Record a failed login attempt and ban the IP after too many failures - */ - public function testHandleFailedLoginBanIp() - { - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - $this->assertTrue($this->loginManager->canLogin($this->server)); - - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - $this->assertTrue($this->loginManager->canLogin($this->server)); - - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(3, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - $this->assertTrue($this->loginManager->canLogin($this->server)); - - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(4, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - $this->assertFalse($this->loginManager->canLogin($this->server)); - - // handleFailedLogin is not supposed to be called at this point: - // - no login form should be displayed once an IP has been banned - // - yet this could happen when using custom templates / scripts - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(5, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - $this->assertFalse($this->loginManager->canLogin($this->server)); - } - - /** - * Nothing to do - */ - public function testHandleSuccessfulLogin() - { - $this->assertTrue($this->loginManager->canLogin($this->server)); - - $this->loginManager->handleSuccessfulLogin($this->server); - $this->assertTrue($this->loginManager->canLogin($this->server)); - } - - /** - * Erase failure records after successfully logging in from this IP - */ - public function testHandleSuccessfulLoginAfterFailure() - { - $this->loginManager->handleFailedLogin($this->server); - $this->loginManager->handleFailedLogin($this->server); - $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); - $this->assertTrue($this->loginManager->canLogin($this->server)); - - $this->loginManager->handleSuccessfulLogin($this->server); - $this->assertTrue($this->loginManager->canLogin($this->server)); - $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr])); - $this->assertFalse(isset($this->globals['IPBANS']['BANS'][$this->ipAddr])); - } - - /** - * The IP is not banned - */ - public function testCanLoginIpNotBanned() - { - $this->assertTrue($this->loginManager->canLogin($this->server)); - } - - /** - * The IP is banned - */ - public function testCanLoginIpBanned() - { - // ban the IP for an hour - $this->globals['IPBANS']['FAILURES'][$this->ipAddr] = 10; - $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() + 3600; - - $this->assertFalse($this->loginManager->canLogin($this->server)); - } - - /** - * The IP is banned, and the ban duration is over - */ - public function testCanLoginIpBanExpired() - { - // ban the IP for an hour - $this->globals['IPBANS']['FAILURES'][$this->ipAddr] = 10; - $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() + 3600; - $this->assertFalse($this->loginManager->canLogin($this->server)); - - // lift the ban - $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() - 3600; - $this->assertTrue($this->loginManager->canLogin($this->server)); - } -} diff --git a/tests/SessionManagerTest.php b/tests/SessionManagerTest.php deleted file mode 100644 index aa75962a..00000000 --- a/tests/SessionManagerTest.php +++ /dev/null @@ -1,149 +0,0 @@ -generateToken(); - - $this->assertEquals(1, $session['tokens'][$token]); - $this->assertEquals(40, strlen($token)); - } - - /** - * Check a session token - */ - public function testCheckToken() - { - $token = '4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b'; - $session = [ - 'tokens' => [ - $token => 1, - ], - ]; - $sessionManager = new SessionManager($session, self::$conf); - - // check and destroy the token - $this->assertTrue($sessionManager->checkToken($token)); - $this->assertFalse(isset($session['tokens'][$token])); - - // ensure the token has been destroyed - $this->assertFalse($sessionManager->checkToken($token)); - } - - /** - * Generate and check a session token - */ - public function testGenerateAndCheckToken() - { - $session = []; - $sessionManager = new SessionManager($session, self::$conf); - - $token = $sessionManager->generateToken(); - - // ensure a token has been generated - $this->assertEquals(1, $session['tokens'][$token]); - $this->assertEquals(40, strlen($token)); - - // check and destroy the token - $this->assertTrue($sessionManager->checkToken($token)); - $this->assertFalse(isset($session['tokens'][$token])); - - // ensure the token has been destroyed - $this->assertFalse($sessionManager->checkToken($token)); - } - - /** - * Check an invalid session token - */ - public function testCheckInvalidToken() - { - $session = []; - $sessionManager = new SessionManager($session, self::$conf); - - $this->assertFalse($sessionManager->checkToken('4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b')); - } - - /** - * Test SessionManager::checkId with a valid ID - TEST ALL THE HASHES! - * - * This tests extensively covers all hash algorithms / bit representations - */ - public function testIsAnyHashSessionIdValid() - { - foreach (self::$sidHashes as $algo => $bpcs) { - foreach ($bpcs as $bpc => $hash) { - $this->assertTrue(SessionManager::checkId($hash)); - } - } - } - - /** - * Test checkId with a valid ID - SHA-1 hashes - */ - public function testIsSha1SessionIdValid() - { - $this->assertTrue(SessionManager::checkId(sha1('shaarli'))); - } - - /** - * Test checkId with a valid ID - SHA-256 hashes - */ - public function testIsSha256SessionIdValid() - { - $this->assertTrue(SessionManager::checkId(hash('sha256', 'shaarli'))); - } - - /** - * Test checkId with a valid ID - SHA-512 hashes - */ - public function testIsSha512SessionIdValid() - { - $this->assertTrue(SessionManager::checkId(hash('sha512', 'shaarli'))); - } - - /** - * Test checkId with invalid IDs. - */ - public function testIsSessionIdInvalid() - { - $this->assertFalse(SessionManager::checkId('')); - $this->assertFalse(SessionManager::checkId([])); - $this->assertFalse( - SessionManager::checkId('c0ZqcWF3VFE2NmJBdm1HMVQ0ZHJ3UmZPbTFsNGhkNHI=') - ); - } -} diff --git a/tests/security/LoginManagerTest.php b/tests/security/LoginManagerTest.php new file mode 100644 index 00000000..b957abe3 --- /dev/null +++ b/tests/security/LoginManagerTest.php @@ -0,0 +1,199 @@ +banFile)) { + unlink($this->banFile); + } + + $this->configManager = new \FakeConfigManager([ + 'resource.ban_file' => $this->banFile, + 'resource.log' => $this->logFile, + 'security.ban_after' => 4, + 'security.ban_duration' => 3600, + 'security.trusted_proxies' => [$this->trustedProxy], + ]); + + $this->globals = &$GLOBALS; + unset($this->globals['IPBANS']); + + $this->loginManager = new LoginManager($this->globals, $this->configManager, null); + $this->server['REMOTE_ADDR'] = $this->ipAddr; + } + + /** + * Wipe test resources + */ + public function tearDown() + { + unset($this->globals['IPBANS']); + } + + /** + * Instantiate a LoginManager and load ban records + */ + public function testReadBanFile() + { + file_put_contents( + $this->banFile, + " array('127.0.0.1' => 99));\n?>" + ); + new LoginManager($this->globals, $this->configManager, null); + $this->assertEquals(99, $this->globals['IPBANS']['FAILURES']['127.0.0.1']); + } + + /** + * Record a failed login attempt + */ + public function testHandleFailedLogin() + { + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + } + + /** + * Record a failed login attempt - IP behind a trusted proxy + */ + public function testHandleFailedLoginBehindTrustedProxy() + { + $server = [ + 'REMOTE_ADDR' => $this->trustedProxy, + 'HTTP_X_FORWARDED_FOR' => $this->ipAddr, + ]; + $this->loginManager->handleFailedLogin($server); + $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + + $this->loginManager->handleFailedLogin($server); + $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + } + + /** + * Record a failed login attempt - IP behind a trusted proxy but not forwarded + */ + public function testHandleFailedLoginBehindTrustedProxyNoIp() + { + $server = [ + 'REMOTE_ADDR' => $this->trustedProxy, + ]; + $this->loginManager->handleFailedLogin($server); + $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr])); + + $this->loginManager->handleFailedLogin($server); + $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr])); + } + + /** + * Record a failed login attempt and ban the IP after too many failures + */ + public function testHandleFailedLoginBanIp() + { + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(1, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + $this->assertTrue($this->loginManager->canLogin($this->server)); + + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + $this->assertTrue($this->loginManager->canLogin($this->server)); + + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(3, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + $this->assertTrue($this->loginManager->canLogin($this->server)); + + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(4, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + $this->assertFalse($this->loginManager->canLogin($this->server)); + + // handleFailedLogin is not supposed to be called at this point: + // - no login form should be displayed once an IP has been banned + // - yet this could happen when using custom templates / scripts + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(5, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + $this->assertFalse($this->loginManager->canLogin($this->server)); + } + + /** + * Nothing to do + */ + public function testHandleSuccessfulLogin() + { + $this->assertTrue($this->loginManager->canLogin($this->server)); + + $this->loginManager->handleSuccessfulLogin($this->server); + $this->assertTrue($this->loginManager->canLogin($this->server)); + } + + /** + * Erase failure records after successfully logging in from this IP + */ + public function testHandleSuccessfulLoginAfterFailure() + { + $this->loginManager->handleFailedLogin($this->server); + $this->loginManager->handleFailedLogin($this->server); + $this->assertEquals(2, $this->globals['IPBANS']['FAILURES'][$this->ipAddr]); + $this->assertTrue($this->loginManager->canLogin($this->server)); + + $this->loginManager->handleSuccessfulLogin($this->server); + $this->assertTrue($this->loginManager->canLogin($this->server)); + $this->assertFalse(isset($this->globals['IPBANS']['FAILURES'][$this->ipAddr])); + $this->assertFalse(isset($this->globals['IPBANS']['BANS'][$this->ipAddr])); + } + + /** + * The IP is not banned + */ + public function testCanLoginIpNotBanned() + { + $this->assertTrue($this->loginManager->canLogin($this->server)); + } + + /** + * The IP is banned + */ + public function testCanLoginIpBanned() + { + // ban the IP for an hour + $this->globals['IPBANS']['FAILURES'][$this->ipAddr] = 10; + $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() + 3600; + + $this->assertFalse($this->loginManager->canLogin($this->server)); + } + + /** + * The IP is banned, and the ban duration is over + */ + public function testCanLoginIpBanExpired() + { + // ban the IP for an hour + $this->globals['IPBANS']['FAILURES'][$this->ipAddr] = 10; + $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() + 3600; + $this->assertFalse($this->loginManager->canLogin($this->server)); + + // lift the ban + $this->globals['IPBANS']['BANS'][$this->ipAddr] = time() - 3600; + $this->assertTrue($this->loginManager->canLogin($this->server)); + } +} diff --git a/tests/security/SessionManagerTest.php b/tests/security/SessionManagerTest.php new file mode 100644 index 00000000..e4e1cfbc --- /dev/null +++ b/tests/security/SessionManagerTest.php @@ -0,0 +1,149 @@ +generateToken(); + + $this->assertEquals(1, $session['tokens'][$token]); + $this->assertEquals(40, strlen($token)); + } + + /** + * Check a session token + */ + public function testCheckToken() + { + $token = '4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b'; + $session = [ + 'tokens' => [ + $token => 1, + ], + ]; + $sessionManager = new SessionManager($session, self::$conf); + + // check and destroy the token + $this->assertTrue($sessionManager->checkToken($token)); + $this->assertFalse(isset($session['tokens'][$token])); + + // ensure the token has been destroyed + $this->assertFalse($sessionManager->checkToken($token)); + } + + /** + * Generate and check a session token + */ + public function testGenerateAndCheckToken() + { + $session = []; + $sessionManager = new SessionManager($session, self::$conf); + + $token = $sessionManager->generateToken(); + + // ensure a token has been generated + $this->assertEquals(1, $session['tokens'][$token]); + $this->assertEquals(40, strlen($token)); + + // check and destroy the token + $this->assertTrue($sessionManager->checkToken($token)); + $this->assertFalse(isset($session['tokens'][$token])); + + // ensure the token has been destroyed + $this->assertFalse($sessionManager->checkToken($token)); + } + + /** + * Check an invalid session token + */ + public function testCheckInvalidToken() + { + $session = []; + $sessionManager = new SessionManager($session, self::$conf); + + $this->assertFalse($sessionManager->checkToken('4dccc3a45ad9d03e5542b90c37d8db6d10f2b38b')); + } + + /** + * Test SessionManager::checkId with a valid ID - TEST ALL THE HASHES! + * + * This tests extensively covers all hash algorithms / bit representations + */ + public function testIsAnyHashSessionIdValid() + { + foreach (self::$sidHashes as $algo => $bpcs) { + foreach ($bpcs as $bpc => $hash) { + $this->assertTrue(SessionManager::checkId($hash)); + } + } + } + + /** + * Test checkId with a valid ID - SHA-1 hashes + */ + public function testIsSha1SessionIdValid() + { + $this->assertTrue(SessionManager::checkId(sha1('shaarli'))); + } + + /** + * Test checkId with a valid ID - SHA-256 hashes + */ + public function testIsSha256SessionIdValid() + { + $this->assertTrue(SessionManager::checkId(hash('sha256', 'shaarli'))); + } + + /** + * Test checkId with a valid ID - SHA-512 hashes + */ + public function testIsSha512SessionIdValid() + { + $this->assertTrue(SessionManager::checkId(hash('sha512', 'shaarli'))); + } + + /** + * Test checkId with invalid IDs. + */ + public function testIsSessionIdInvalid() + { + $this->assertFalse(SessionManager::checkId('')); + $this->assertFalse(SessionManager::checkId([])); + $this->assertFalse( + SessionManager::checkId('c0ZqcWF3VFE2NmJBdm1HMVQ0ZHJ3UmZPbTFsNGhkNHI=') + ); + } +} -- cgit v1.2.3