CVE-2023-38489 (published 2023-07-27T15:15Z)

Kirby is a content management system. A vulnerability in versions prior to 3.5.8.3, 3.6.6.3, 3.7.5.2, 3.8.4.1, and 3.9.6 affects all Kirby sites with user accounts (unless Kirby's API and Panel are disabled in the config). It can only be abused if a Kirby user is logged in on a device or browser that is shared with potentially untrusted users or if an attacker already maliciously used a previous password to log in to a Kirby site as the affected user.\n\nInsufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization. In the variation described in this advisory, it allows attackers to stay logged in to a Kirby site on another device even if the logged in user has since changed their password. Kirby did not invalidate user sessions that were created with a password that was since changed by the user or by a site admin. If a user changed their password to lock out an attacker who was already in possession of the previous password or of a login session on another device or browser, the attacker would not be reliably prevented from accessing the Kirby site as the affected user.\n\nThe problem has been patched in Kirby 3.5.8.3, 3.6.6.3, 3.7.5.2, 3.8.4.1, and 3.9.6. In all of the mentioned releases, the maintainers have updated the authentication implementation to keep track of the hashed password in each active session. If the password changed since the login, the session is invalidated. To enforce this fix even if the vulnerability was previously abused, all users are logged out from the Kirby site after updating to one of the patched releases.

CVSS v3 base score: 7.3, HIGH (CVSS:3.1/AV:N/AC:L/PR:L/UI:R/S:U/C:H/I:H/A:N)

Weakness information:
cwe_id: CWE-613
cwe_name: Insufficient Session Expiration
description: According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
extended_description: 
            
            
            
         
         

Fix information:
repo_url: https://github.com/getkirby/kirby
commit_details: repo_url: https://github.com/getkirby/kirby
author: Lukas Bestle
author_date: 2023-07-23 21:37:48+02:00
msg: Invalidate session on password change

https://github.com/getkirby/kirby/security/advisories/GHSA-5mvj-rvp8-rf45
repository: repo_url: https://github.com/getkirby/kirby
repo_name: getkirby/kirby
description: Kirby's core application folder
repo_language: PHP
owner: getkirby
file_changes: filename: Auth.php
change_type: ModificationType.MODIFY
diff: @@ -279,18 +279,39 @@ class Auth
 
 		$id = $session->data()->get('kirby.userId');
 
+		// if no user is logged in, return immediately
 		if (is_string($id) !== true) {
 			return null;
 		}
 
-		if ($user = $this->kirby->users()->find($id)) {
-			// in case the session needs to be updated, do it now
-			// for better performance
-			$session->commit();
-			return $user;
+		// a user is logged in, ensure it exists
+		$user = $this->kirby->users()->find($id);
+		if ($user === null) {
+			return null;
 		}
 
-		return null;
+		if ($passwordTimestamp = $user->passwordTimestamp()) {
+			$loginTimestamp = $session->data()->get('kirby.loginTimestamp');
+			if (is_int($loginTimestamp) !== true) {
+				// session that was created before Kirby
+				// 3.5.8.3, 3.6.6.3, 3.7.5.2, 3.8.4.1 or 3.9.6
+				// or when the user didn't have a password set
+				$user->logout();
+				return null;
+			}
+
+			// invalidate the session if the password
+			// changed since the login
+			if ($loginTimestamp < $passwordTimestamp) {
+				$user->logout();
+				return null;
+			}
+		}
+
+		// in case the session needs to be updated, do it now
+		// for better performance
+		$session->commit();
+		return $user;
 	}
 
 	/**

programming_language: PHP
filename: User.php
change_type: ModificationType.MODIFY
diff: @@ -441,6 +441,9 @@ class User extends ModelWithContent
 
 		$session->regenerateToken(); // privilege change
 		$session->data()->set('kirby.userId', $this->id());
+		if ($this->passwordTimestamp() !== null) {
+			$session->data()->set('kirby.loginTimestamp', time());
+		}
 		$this->kirby()->auth()->setUser($this);
 
 		$kirby->trigger('user.login:after', ['user' => $this, 'session' => $session]);
@@ -461,6 +464,7 @@ class User extends ModelWithContent
 
 		// remove the user from the session for future requests
 		$session->data()->remove('kirby.userId');
+		$session->data()->remove('kirby.loginTimestamp');
 
 		// clear the cached user object from the app state of the current request
 		$this->kirby()->auth()->flush();
@@ -607,6 +611,26 @@ class User extends ModelWithContent
 		return $this->password = $this->readPassword();
 	}
 
+	/**
+	 * Returns the timestamp when the password
+	 * was last changed
+	 */
+	public function passwordTimestamp(): int|null
+	{
+		$file = $this->passwordFile();
+
+		// ensure we have the latest information
+		// to prevent cache attacks
+		clearstatcache();
+
+		// user does not have a password
+		if (is_file($file) === false) {
+			return null;
+		}
+
+		return filemtime($file);
+	}
+
 	/**
 	 * @return \Kirby\Cms\UserPermissions
 	 */
@@ -881,4 +905,12 @@ class User extends ModelWithContent
 
 		return true;
 	}
+
+	/**
+	 * Returns the path to the password file
+	 */
+	protected function passwordFile(): string
+	{
+		return $this->root() . '/.htpasswd';
+	}
 }

programming_language: PHP
filename: UserActions.php
change_type: ModificationType.MODIFY
diff: @@ -118,6 +118,13 @@ trait UserActions
 			// update the users collection
 			$user->kirby()->users()->set($user->id(), $user);
 
+			// keep the user logged in to the current browser
+			// if they changed their own password
+			// (regenerate the session token, update the login timestamp)
+			if ($user->isLoggedIn() === true) {
+				$user->loginPasswordless();
+			}
+
 			return $user;
 		});
 	}
@@ -323,7 +330,7 @@ trait UserActions
 	 */
 	protected function readPassword()
 	{
-		return F::read($this->root() . '/.htpasswd');
+		return F::read($this->passwordFile());
 	}
 
 	/**
@@ -384,6 +391,6 @@ trait UserActions
 		#[SensitiveParameter]
 		string $password = null
 	): bool {
-		return F::write($this->root() . '/.htpasswd', $password);
+		return F::write($this->passwordFile(), $password);
 	}
 }

programming_language: PHP
filename: AuthTest.php
change_type: ModificationType.MODIFY
diff: @@ -5,6 +5,7 @@ namespace Kirby\Cms;
 use Kirby\Exception\NotFoundException;
 use Kirby\Exception\PermissionException;
 use Kirby\Filesystem\Dir;
+use Kirby\Filesystem\F;
 use Kirby\Session\AutoSession;
 use Throwable;
 
@@ -15,13 +16,13 @@ class AuthTest extends TestCase
 {
 	protected $app;
 	protected $auth;
-	protected $fixtures;
+	protected $tmp;
 
 	public function setUp(): void
 	{
 		$this->app = new App([
 			'roots' => [
-				'index' => $this->fixtures = __DIR__ . '/fixtures/AuthTest'
+				'index' => $this->tmp = __DIR__ . '/tmp'
 			],
 			'options' => [
 				'api' => [
@@ -41,11 +42,13 @@ class AuthTest extends TestCase
 				[
 					'email'    => 'homer@simpsons.com',
 					'id'       => 'homer',
-					'password' => password_hash('springfield123', PASSWORD_DEFAULT)
+					'password' => $hash = password_hash('springfield123', PASSWORD_DEFAULT)
 				]
 			]
 		]);
-		Dir::make($this->fixtures . '/site/accounts');
+		Dir::make($this->tmp . '/site/accounts/homer');
+		F::write($this->tmp . '/site/accounts/homer/.htpasswd', $hash);
+		touch($this->tmp . '/site/accounts/homer/.htpasswd', 1337000000);
 
 		$this->auth = $this->app->auth();
 	}
@@ -53,7 +56,7 @@ class AuthTest extends TestCase
 	public function tearDown(): void
 	{
 		$this->app->session()->destroy();
-		Dir::remove($this->fixtures);
+		Dir::remove($this->tmp);
 		App::destroy();
 	}
 
@@ -254,7 +257,7 @@ class AuthTest extends TestCase
 	 * @covers ::status
 	 * @covers ::user
 	 */
-	public function testUserSession1()
+	public function testUserSession()
 	{
 		$session = $this->app->session();
 		$session->set('kirby.userId', 'marge');
@@ -286,10 +289,11 @@ class AuthTest extends TestCase
 	 * @covers ::status
 	 * @covers ::user
 	 */
-	public function testUserSession2()
+	public function testUserSessionManualSession()
 	{
 		$session = (new AutoSession($this->app->root('sessions')))->createManually();
 		$session->set('kirby.userId', 'homer');
+		$session->set('kirby.loginTimestamp', 1337000000);
 
 		$user = $this->auth->user($session);
 		$this->assertSame('homer@simpsons.com', $user->email());
@@ -300,6 +304,47 @@ class AuthTest extends TestCase
 		], $this->auth->status()->toArray());
 	}
 
+	/**
+	 * @covers ::status
+	 * @covers ::user
+	 */
+	public function testUserSessionOldTimestamp()
+	{
+		$session = $this->app->session();
+		$session->set('kirby.userId', 'homer');
+		$session->set('kirby.loginTimestamp', 1000000000);
+
+		$this->assertNull($this->auth->user());
+		$this->assertSame([
+			'challenge' => null,
+			'email'     => null,
+			'status'    => 'inactive'
+		], $this->auth->status()->toArray());
+
+		// user should be logged out completely
+		$this->assertSame([], $session->data()->get());
+	}
+
+	/**
+	 * @covers ::status
+	 * @covers ::user
+	 */
+	public function testUserSessionNoTimestamp()
+	{
+		$session = $this->app->session();
+		$session->set('kirby.userId', 'homer');
+
+		$this->assertNull($this->auth->user());
+		$this->assertSame([
+			'challenge' => null,
+			'email'     => null,
+			'status'    => 'inactive'
+		], $this->auth->status()->toArray());
+
+		// user should be logged out completely
+		$this->assertSame([], $session->data()->get());
+	}
+
 	/**
 	 * @covers ::status
 	 * @covers ::user

programming_language: PHP
filename: UserActionsTest.php
change_type: ModificationType.MODIFY
diff: @@ -42,6 +42,7 @@ class UserActionsTest extends TestCase
 
 	public function tearDown(): void
 	{
+		$this->app->session()->destroy();
 		Dir::remove($this->tmp);
 	}
 
@@ -390,15 +391,53 @@ class UserActionsTest extends TestCase
 				'user.changePassword:after' => function (User $newUser, User $oldUser) use ($phpunit, &$calls) {
 					$phpunit->assertTrue($newUser->validatePassword('topsecret2018'));
 					$phpunit->assertEmpty($oldUser->password());
-					$calls++;
-				}
+					$calls += 2;
+				},
+				'user.login:before' => function () use (&$calls) {
+					$calls += 4;
+				},
+				'user.login:after' => function () use (&$calls) {
+					$calls += 8;
+				},
 			]
 		]);
 
 		$user = $app->user('editor@domain.com');
 		$user->changePassword('topsecret2018');
 
-		$this->assertSame(2, $calls);
+		$this->assertSame(3, $calls);
+	}
+
+	public function testChangePasswordHooksCurrentUser()
+	{
+		$calls = 0;
+		$phpunit = $this;
+
+		$this->app = $this->app->clone([
+			'hooks' => [
+				'user.changePassword:before' => function (User $user, $password) use ($phpunit, &$calls) {
+					$phpunit->assertEmpty($user->password());
+					$phpunit->assertSame('topsecret2018', $password);
+					$calls++;
+				},
+				'user.changePassword:after' => function (User $newUser, User $oldUser) use ($phpunit, &$calls) {
+					$phpunit->assertTrue($newUser->validatePassword('topsecret2018'));
+					$phpunit->assertEmpty($oldUser->password());
+					$calls += 2;
+				},
+				'user.login:before' => function () use (&$calls) {
+					$calls += 4;
+				},
+				'user.login:after' => function () use (&$calls) {
+					$calls += 8;
+				},
+			]
+		]);
+
+		$user = $this->app->user('admin@domain.com');
+		$user->changePassword('topsecret2018');
+
+		$this->assertSame(15, $calls);
 	}
 
 	public function testChangeRoleHooks()

programming_language: PHP
filename: UserAuthTest.php
change_type: ModificationType.MODIFY
diff: @@ -2,6 +2,8 @@
 
 namespace Kirby\Cms;
 
+use Kirby\Filesystem\F;
+
 class UserAuthTest extends TestCase
 {
 	protected $app;
@@ -19,6 +21,7 @@ class UserAuthTest extends TestCase
 			'users' => [
 				[
 					'email' => 'test@getkirby.com',
+					'id'    => 'testuser',
 					'role'  => 'admin'
 				]
 			]
@@ -96,4 +99,30 @@ class UserAuthTest extends TestCase
 		// each hook needs to be called exactly twice
 		$this->assertSame((1 + 2 + 4 + 8) * 2, $calls);
 	}
+
+	public function testSessionData()
+	{
+		$user    = $this->app->user('test@getkirby.com');
+		$session = $this->app->session();
+
+		$this->assertSame([], $session->data()->get());
+		$user->loginPasswordless();
+		$this->assertSame(['kirby.userId' => 'testuser'], $session->data()->get());
+		$user->logout();
+		$this->assertSame([], $session->data()->get());
+	}
+
+	public function testSessionDataWithPassword()
+	{
+		F::write($this->tmp . '/accounts/testuser/.htpasswd', 'a very secure hash');
+
+		$user    = $this->app->user('test@getkirby.com');
+		$session = $this->app->session();
+
+		$this->assertSame([], $session->data()->get());
+		$user->loginPasswordless();
+		$this->assertSame(['kirby.userId' => 'testuser', 'kirby.loginTimestamp' => 1337000000], $session->data()->get());
+		$user->logout();
+		$this->assertSame([], $session->data()->get());
+	}
 }

programming_language: PHP
filename: UserTest.php
change_type: ModificationType.MODIFY
diff: @@ -193,6 +193,32 @@ class UserTest extends TestCase
 		Dir::remove($index);
 	}
 
+	public function testPasswordTimestamp()
+	{
+		$app = new App([
+			'roots' => [
+				'index'    => $this->tmp,
+				'accounts' => $this->tmp
+			]
+		]);
+
+		// create a user file
+		F::write($this->tmp . '/test/index.php', '<?php return [];');
+
+		$user = $app->user('test');
+		$this->assertNull($user->passwordTimestamp());
+
+		// create a password file
+		F::write($this->tmp . '/test/.htpasswd', 'a very secure hash');
+		touch($this->tmp . '/test/.htpasswd', 1337000000);
+
+		$this->assertSame(1337000000, $user->passwordTimestamp());
+
+		// timestamp is not cached
+		touch($this->tmp . '/test/.htpasswd', 1338000000);
+		$this->assertSame(1338000000, $user->passwordTimestamp());
+	}
+
 	public function passwordProvider()
 	{
 		return [

programming_language: PHP