From 72c213ddef1797cd096757e1c8c70d826abd7514 Mon Sep 17 00:00:00 2001 From: Greg Bowler Date: Thu, 5 Nov 2026 16:00:06 +0000 Subject: [PATCH] Bind each token to one encrypted request --- README.md | 2 + src/Authenticator.php | 3 +- src/Token.php | 19 +++++- src/TokenReuseException.php | 4 ++ test/phpunit/TokenNonceTest.php | 116 ++++++++++++++++++++++++++++++++ 5 files changed, 140 insertions(+), 4 deletions(-) create mode 100644 src/TokenReuseException.php create mode 100644 test/phpunit/TokenNonceTest.php diff --git a/README.md b/README.md index 9778c37..5e76035 100644 --- a/README.md +++ b/README.md @@ -75,6 +75,8 @@ Without an override, login requests the current URI. The provider accepts root-r The `authwaveHost` constructor argument selects the provider and defaults to `login.authwave.com`. For a self-hosted provider, supply its scheme, host and optional port, such as `https://login.example.com`. +A token can encrypt only its first complete request. Repeating the same request is allowed; a different payload raises TokenReuseException. Create a fresh token for a different action or return query, and do not copy tokens or reuse supplied IVs. Session serialisation retains the binding. Tokens restored from older sessions without a binding can still decrypt responses, but require a fresh token to start another request. + Logging out ----------- diff --git a/src/Authenticator.php b/src/Authenticator.php index 482bd81..159e728 100644 --- a/src/Authenticator.php +++ b/src/Authenticator.php @@ -86,13 +86,14 @@ public function login(?Token $token = null):void { $token = new Token($this->secret); } + $loginUri = $this->getLoginUri($token); $this->sessionData = new SessionData( $token, null, ($this->returnUri ?? $this->currentUriPath)->getQuery(), ); $this->session->set(SessionData::class, $this->sessionData); - $this->redirectHandler->redirect($this->getLoginUri($token)); + $this->redirectHandler->redirect($loginUri); } public function logout( diff --git a/src/Token.php b/src/Token.php index 4c17c9a..9d23ded 100644 --- a/src/Token.php +++ b/src/Token.php @@ -13,6 +13,7 @@ class Token { private Key $key; private InitVector $secretSessionIv; private InitVector $iv; + private ?string $requestPlaintext; public function __construct( string $secret, @@ -20,10 +21,18 @@ public function __construct( ?InitVector $iv = null, ) { $this->key = new Key($secret); + $this->requestPlaintext = null; $this->secretSessionIv = $sessionIv ?? new InitVector(); $this->iv = $iv ?? new InitVector(); } + public function __wakeup():void { + // Older sessions cannot tell us which plaintext has already used this nonce. + if(!array_key_exists("requestPlaintext", get_object_vars($this))) { + $this->requestPlaintext = ""; + } + } + public function getIv():InitVector { return $this->iv; } @@ -41,9 +50,13 @@ public function getSecretIv():InitVector { * the client application in the querystring. */ public function generateRequestCipher(string $message = ""):CipherText { -// TODO: $message should probably always be a KVP, so we can build up the querystring message here without concatenating. - $plainTextMessage = new PlainTextMessage($message . "&secretIv=" . $this->getSecretIv(), $this->getIv()); - return $plainTextMessage->encrypt($this->key); + $plaintext = $message . "&secretIv=" . $this->getSecretIv(); + if(!is_null($this->requestPlaintext) && $this->requestPlaintext !== $plaintext) { + throw new TokenReuseException("Create a new token for a different request."); + } + $cipher = (new PlainTextMessage($plaintext, $this->getIv()))->encrypt($this->key); + $this->requestPlaintext = $plaintext; + return $cipher; } // The response cipher is send from the remote provider back to the client // application after a successful authentication and includes a serialised diff --git a/src/TokenReuseException.php b/src/TokenReuseException.php new file mode 100644 index 0000000..bf2e84b --- /dev/null +++ b/src/TokenReuseException.php @@ -0,0 +1,4 @@ + */ + public static function changedRequests():array { + return [ + "changed action" => ["action=login", "action=logout"], + "changed return query" => ["action=login&returnQuery=page%3D1", "action=login&returnQuery=page%3D2"], + "empty first message" => ["", "action=login"], + "empty second message" => ["action=login", ""], + ]; + } + + #[DataProvider("changedRequests")] + public function testDifferentRequestsCannotShareToken(string $first, string $second):void { + $token = new Token(str_repeat("s", 32)); + $iv = $token->getIv()->getBytes(); + $cipher = (string)$token->generateRequestCipher($first); + try { + $token->generateRequestCipher($second); + self::fail("Expected token reuse to be rejected"); + } + catch(TokenReuseException) {} + self::assertSame($iv, $token->getIv()->getBytes()); + self::assertSame($cipher, (string)$token->generateRequestCipher($first)); + } + + public function testSessionSerialisationPreservesTheRequestBinding():void { + $token = new Token(str_repeat("s", 32)); + $cipher = (string)$token->generateRequestCipher("action=login"); + /** @var SessionData $restored */ + $restored = unserialize(serialize(new SessionData($token))); + self::assertSame($cipher, (string)$restored->getToken()->generateRequestCipher("action=login")); + self::expectException(TokenReuseException::class); + $restored->getToken()->generateRequestCipher("action=logout"); + } + + public function testUnusedTokenCanBeRestoredBeforeFirstEncryption():void { + /** @var Token $token */ + $token = unserialize(serialize(new Token(str_repeat("s", 32)))); + self::assertNotSame("", (string)$token->generateRequestCipher("action=login")); + } + + public function testLegacySessionCanDecryptButCannotReuseUnknownRequestNonce():void { + $secret = str_repeat("s", 32); + $token = new Token($secret); + $fields = ""; + foreach(["key", "secretSessionIv", "iv"] as $name) { + $value = (new \ReflectionProperty(Token::class, $name))->getValue($token); + $fields .= serialize("\0" . Token::class . "\0" . $name) . serialize($value); + } + /** @var Token $legacy */ + $legacy = unserialize('O:' . strlen(Token::class) . ':"' . Token::class . '":3:{' . $fields . '}'); + $cipher = sodium_crypto_secretbox( + '{"id":"user-id","email":"person@example.com"}', + $token->getIv()->getBytes(), $secret, + ); + self::assertSame("user-id", $legacy->decode(base64_encode($cipher))->getId()); + self::expectException(TokenReuseException::class); + $legacy->generateRequestCipher("action=login"); + } + + public function testFailedEncryptionDoesNotBindTheToken():void { + $token = new Token(""); + $failures = 0; + foreach(["action=login", "action=logout"] as $message) { + try { + $token->generateRequestCipher($message); + self::fail("Expected invalid key to fail encryption"); + } + catch(EncryptionFailureException) { $failures++; } + } + self::assertSame(2, $failures); + } + + public function testLoginAndLogoutBuildersRequireSeparateTokens():void { + $token = new Token(str_repeat("s", 32)); + $uri = new LoginUri($token, "/callback", "deployment"); + self::assertSame((string)$uri, (string)new LoginUri($token, "/callback", "deployment")); + self::expectException(TokenReuseException::class); + new LogoutUri($token, "/callback", "deployment"); + } + + public function testRejectedLoginLeavesExistingExchangeUntouched():void { + $secret = str_repeat("s", 32); + $pending = new SessionData(new Token($secret)); + $_SESSION = [SessionData::class => $pending, "basket" => ["tea"]]; + $auth = new Authenticator( + "deployment_" . $secret, "/callback", + session: new GlobalSessionContainer(), + redirectHandler: self::createStub(RedirectHandler::class), + ); + $used = new Token($secret); + $used->generateRequestCipher("action=logout"); + try { + $auth->login($used); + self::fail("Expected token reuse to be rejected"); + } + catch(TokenReuseException) {} + self::assertSame($pending, $_SESSION[SessionData::class]); + self::assertSame(["tea"], $_SESSION["basket"]); + } +}