feat(auth): add signed cookie session envelope
parent
00a7271e2b
commit
aa9ba06152
@ -0,0 +1,171 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Auth;
|
||||
|
||||
use App\Services\Config;
|
||||
|
||||
final class SignedCookieSession
|
||||
{
|
||||
public const COOKIE_NAME = 'auth_session';
|
||||
public const MAX_TTL = 365 * 86400;
|
||||
|
||||
private const FORMAT_VERSION = 1;
|
||||
private const PREFIX = 'v1';
|
||||
private const CLOCK_SKEW = 60;
|
||||
private const MAX_TOKEN_BYTES = 1024;
|
||||
private const KEY_INFO = 'virt-cloud/auth-cookie/v1';
|
||||
|
||||
public static function issue(
|
||||
int $userId,
|
||||
int $sessionVersion,
|
||||
int $expiresAt,
|
||||
?string $remoteAddress = null,
|
||||
?int $now = null
|
||||
): string {
|
||||
$issuedAt = $now ?? time();
|
||||
if ($userId < 1 || $sessionVersion < 0 || $issuedAt < 1
|
||||
|| $expiresAt <= $issuedAt || $expiresAt - $issuedAt > self::MAX_TTL) {
|
||||
throw new \InvalidArgumentException('Invalid signed cookie session claims.');
|
||||
}
|
||||
|
||||
$key = self::signingKey();
|
||||
$claims = [
|
||||
'version' => self::FORMAT_VERSION,
|
||||
'user_id' => $userId,
|
||||
'session_version' => $sessionVersion,
|
||||
'issued_at' => $issuedAt,
|
||||
'expires_at' => $expiresAt,
|
||||
'session_id' => bin2hex(random_bytes(32)),
|
||||
'ip_digest' => $remoteAddress === null || trim($remoteAddress) === ''
|
||||
? ''
|
||||
: self::ipDigest($remoteAddress, $key),
|
||||
];
|
||||
$payload = self::encode(json_encode($claims, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
$signature = self::encode(hash_hmac('sha256', self::PREFIX . '.' . $payload, $key, true));
|
||||
|
||||
return self::PREFIX . '.' . $payload . '.' . $signature;
|
||||
}
|
||||
|
||||
public static function verify(
|
||||
string $token,
|
||||
?string $remoteAddress = null,
|
||||
?int $now = null
|
||||
): ?array {
|
||||
if ($token === '' || strlen($token) > self::MAX_TOKEN_BYTES) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parts = explode('.', $token);
|
||||
if (count($parts) !== 3 || $parts[0] !== self::PREFIX) {
|
||||
return null;
|
||||
}
|
||||
[, $encodedPayload, $encodedSignature] = $parts;
|
||||
$payload = self::decode($encodedPayload);
|
||||
$signature = self::decode($encodedSignature);
|
||||
if ($payload === null || $signature === null || strlen($signature) !== 32) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$key = self::signingKey();
|
||||
$expected = hash_hmac('sha256', self::PREFIX . '.' . $encodedPayload, $key, true);
|
||||
if (!hash_equals($expected, $signature)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
$claims = json_decode($payload, true, 16, JSON_THROW_ON_ERROR);
|
||||
} catch (\JsonException $exception) {
|
||||
return null;
|
||||
}
|
||||
if (!self::validClaims($claims, $now ?? time())) {
|
||||
return null;
|
||||
}
|
||||
|
||||
if ($claims['ip_digest'] !== '') {
|
||||
if ($remoteAddress === null || trim($remoteAddress) === '') {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
$actualIpDigest = self::ipDigest($remoteAddress, $key);
|
||||
} catch (\InvalidArgumentException $exception) {
|
||||
return null;
|
||||
}
|
||||
if (!hash_equals($claims['ip_digest'], $actualIpDigest)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return $claims;
|
||||
}
|
||||
|
||||
private static function validClaims($claims, int $now): bool
|
||||
{
|
||||
if (!is_array($claims) || array_keys($claims) !== [
|
||||
'version', 'user_id', 'session_version', 'issued_at', 'expires_at', 'session_id', 'ip_digest',
|
||||
]) {
|
||||
return false;
|
||||
}
|
||||
foreach (['version', 'user_id', 'session_version', 'issued_at', 'expires_at'] as $name) {
|
||||
if (!is_int($claims[$name])) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (!is_string($claims['session_id']) || !is_string($claims['ip_digest'])) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $claims['version'] === self::FORMAT_VERSION
|
||||
&& $claims['user_id'] > 0
|
||||
&& $claims['session_version'] >= 0
|
||||
&& $claims['issued_at'] > 0
|
||||
&& $claims['issued_at'] <= $now + self::CLOCK_SKEW
|
||||
&& $claims['expires_at'] > $now
|
||||
&& $claims['expires_at'] > $claims['issued_at']
|
||||
&& $claims['expires_at'] - $claims['issued_at'] <= self::MAX_TTL
|
||||
&& preg_match('/^[a-f0-9]{64}$/D', $claims['session_id']) === 1
|
||||
&& ($claims['ip_digest'] === ''
|
||||
|| preg_match('/^[a-f0-9]{64}$/D', $claims['ip_digest']) === 1);
|
||||
}
|
||||
|
||||
private static function signingKey(): string
|
||||
{
|
||||
$siteKey = (string) Config::get('key', '');
|
||||
if (strlen($siteKey) < 32) {
|
||||
throw new \RuntimeException('The site key must contain at least 32 bytes for signed cookie sessions.');
|
||||
}
|
||||
|
||||
return hash_hkdf('sha256', $siteKey, 32, self::KEY_INFO);
|
||||
}
|
||||
|
||||
private static function ipDigest(string $remoteAddress, string $key): string
|
||||
{
|
||||
$packed = @inet_pton(trim($remoteAddress));
|
||||
if ($packed === false) {
|
||||
throw new \InvalidArgumentException('Invalid remote address for signed cookie session.');
|
||||
}
|
||||
if (strlen($packed) === 16 && substr($packed, 0, 12) === str_repeat("\0", 10) . "\xff\xff") {
|
||||
$packed = substr($packed, 12);
|
||||
}
|
||||
|
||||
return hash_hmac('sha256', "ip\0" . $packed, $key);
|
||||
}
|
||||
|
||||
private static function encode(string $value): string
|
||||
{
|
||||
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
|
||||
}
|
||||
|
||||
private static function decode(string $value): ?string
|
||||
{
|
||||
if ($value === '' || preg_match('/^[A-Za-z0-9_-]+$/D', $value) !== 1) {
|
||||
return null;
|
||||
}
|
||||
$padding = (4 - strlen($value) % 4) % 4;
|
||||
$decoded = base64_decode(strtr($value, '-_', '+/') . str_repeat('=', $padding), true);
|
||||
if ($decoded === false || !hash_equals(self::encode($decoded), $value)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return $decoded;
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,98 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services {
|
||||
final class Config
|
||||
{
|
||||
public static array $values = [
|
||||
'key' => 'signed-cookie-session-test-key-0001',
|
||||
];
|
||||
|
||||
public static function get($name, $default = null)
|
||||
{
|
||||
return self::$values[$name] ?? $default;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
namespace {
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Auth\SignedCookieSession;
|
||||
use App\Services\Config;
|
||||
|
||||
$assert = static function ($condition, string $message): void {
|
||||
if (!$condition) {
|
||||
throw new RuntimeException($message);
|
||||
}
|
||||
};
|
||||
$encode = static function (string $value): string {
|
||||
return rtrim(strtr(base64_encode($value), '+/', '-_'), '=');
|
||||
};
|
||||
$signed = static function (array $claims) use ($encode): string {
|
||||
$payload = $encode(json_encode($claims, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
$key = hash_hkdf('sha256', Config::$values['key'], 32, 'virt-cloud/auth-cookie/v1');
|
||||
$signature = $encode(hash_hmac('sha256', 'v1.' . $payload, $key, true));
|
||||
return 'v1.' . $payload . '.' . $signature;
|
||||
};
|
||||
|
||||
$now = 1800000000;
|
||||
$token = SignedCookieSession::issue(17, 4, $now + 3600, '2001:db8::17', $now);
|
||||
$claims = SignedCookieSession::verify($token, '2001:0db8:0:0:0:0:0:17', $now + 1);
|
||||
$assert(is_array($claims), 'A valid signed cookie session was rejected.');
|
||||
$assert($claims['user_id'] === 17 && $claims['session_version'] === 4
|
||||
&& $claims['issued_at'] === $now && $claims['expires_at'] === $now + 3600,
|
||||
'Verified signed cookie claims changed.');
|
||||
$assert(preg_match('/^[a-f0-9]{64}$/D', $claims['session_id']) === 1,
|
||||
'Signed cookie session id is not a 256-bit random identifier.');
|
||||
$assert(SignedCookieSession::verify($token, '2001:db8::18', $now + 1) === null,
|
||||
'An IP-bound cookie was accepted from another address.');
|
||||
$assert(SignedCookieSession::verify($token, null, $now + 1) === null,
|
||||
'An IP-bound cookie was accepted without a remote address.');
|
||||
|
||||
[$prefix, $payload, $signature] = explode('.', $token);
|
||||
$decoded = json_decode(base64_decode(strtr($payload, '-_', '+/')), true, 16, JSON_THROW_ON_ERROR);
|
||||
foreach (['version', 'user_id', 'session_version', 'issued_at', 'expires_at', 'session_id', 'ip_digest'] as $field) {
|
||||
$tampered = $decoded;
|
||||
$tampered[$field] = is_int($tampered[$field]) ? $tampered[$field] + 1 : str_repeat('a', 64);
|
||||
$tamperedPayload = $encode(json_encode($tampered, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR));
|
||||
$assert(SignedCookieSession::verify($prefix . '.' . $tamperedPayload . '.' . $signature,
|
||||
'2001:db8::17', $now + 1) === null, 'Tampering ' . $field . ' did not invalidate the signature.');
|
||||
}
|
||||
|
||||
$unbound = SignedCookieSession::issue(23, 0, $now + 30, null, $now);
|
||||
$assert(SignedCookieSession::verify($unbound, '203.0.113.9', $now + 1)['user_id'] === 23,
|
||||
'An unbound signed cookie unexpectedly required an address match.');
|
||||
$assert(SignedCookieSession::verify($unbound, null, $now + 30) === null,
|
||||
'An expired signed cookie session was accepted.');
|
||||
|
||||
$invalid = $claims;
|
||||
$invalid['issued_at'] = $now + 61;
|
||||
$assert(SignedCookieSession::verify($signed($invalid), '2001:db8::17', $now) === null,
|
||||
'A cookie issued beyond the clock-skew allowance was accepted.');
|
||||
$invalid = $claims;
|
||||
$invalid['expires_at'] = $invalid['issued_at'] + SignedCookieSession::MAX_TTL + 1;
|
||||
$assert(SignedCookieSession::verify($signed($invalid), '2001:db8::17', $now) === null,
|
||||
'A cookie beyond the maximum lifetime was accepted.');
|
||||
$invalid = $claims;
|
||||
$invalid['user_id'] = '17';
|
||||
$assert(SignedCookieSession::verify($signed($invalid), '2001:db8::17', $now) === null,
|
||||
'A cookie with non-canonical claim types was accepted.');
|
||||
$invalid = $claims;
|
||||
$invalid['extra'] = true;
|
||||
$assert(SignedCookieSession::verify($signed($invalid), '2001:db8::17', $now) === null,
|
||||
'A cookie with an unexpected claim was accepted.');
|
||||
$assert(SignedCookieSession::verify('v1.invalid.invalid', null, $now) === null
|
||||
&& SignedCookieSession::verify(str_repeat('a', 1025), null, $now) === null,
|
||||
'Malformed or oversized cookie input was accepted.');
|
||||
|
||||
Config::$values['key'] = 'short';
|
||||
try {
|
||||
SignedCookieSession::issue(1, 0, $now + 60, null, $now);
|
||||
throw new RuntimeException('A weak site key was accepted for cookie signing.');
|
||||
} catch (RuntimeException $exception) {
|
||||
$assert(str_contains($exception->getMessage(), 'at least 32 bytes'),
|
||||
'Weak-key failure did not identify the configuration requirement.');
|
||||
}
|
||||
|
||||
echo "Signed cookie session integrity, lifetime and optional IP binding passed.\n";
|
||||
}
|
||||
Loading…
Reference in New Issue