You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Auth/SignedCookieSession.php

178 lines
6.2 KiB
PHP

<?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();
$bindToIp = Config::get('enable_login_bind_ip', 'false') === 'true';
if ($bindToIp && ($remoteAddress === null || trim($remoteAddress) === '')) {
throw new \InvalidArgumentException('A remote address is required when login IP binding is enabled.');
}
$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' => $bindToIp ? 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'] === ''
&& Config::get('enable_login_bind_ip', 'false') === 'true') {
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;
}
}