fix(auth): replace fragmented cookies with signed session

go
codex 42 minutes ago
parent aa9ba06152
commit 21fded1fcd

@ -4,11 +4,14 @@ namespace App\Services\Auth;
use App\Models\User;
use App\Utils;
use App\Services\Config;
use App\Services\LoginSessionRevocationService;
class Cookie extends Base
{
private const LEGACY_COOKIE_NAMES = [
'uid', 'email', 'key', 'ip', 'expire_in', LoginSessionRevocationService::COOKIE_VERSION_NAME,
];
public function login($uid, $time)
{
$user = User::find($uid);
@ -16,56 +19,42 @@ class Cookie extends Base
return;
}
$now = time();
$expiresAt = $now + (int) $time;
$sessionVersion = LoginSessionRevocationService::currentVersion($user);
$key = LoginSessionRevocationService::cookieKey($user->pass, $sessionVersion);
$expire_in = $time+time();
$token = SignedCookieSession::issue(
(int) $user->id,
$sessionVersion,
$expiresAt,
self::remoteAddress(),
$now
);
Utils\Cookie::set([
"uid" => $uid,
"email" => $user->email,
"key" => $key,
"ip" => md5($_SERVER["REMOTE_ADDR"].Config::get('key').$uid.$expire_in),
"expire_in" => $expire_in,
LoginSessionRevocationService::COOKIE_VERSION_NAME => $sessionVersion,
], $expire_in);
SignedCookieSession::COOKIE_NAME => $token,
], $expiresAt);
self::clearLegacyCookies();
}
public function getUser()
{
$uid = Utils\Cookie::get('uid');
$key = Utils\Cookie::get('key');
$ip = Utils\Cookie::get('ip');
$sessionVersion = Utils\Cookie::get(LoginSessionRevocationService::COOKIE_VERSION_NAME);
$expire_in = Utils\Cookie::get('expire_in');
if ($uid == null) {
$user = new User();
$user->isLogin = false;
return $user;
}
if ($ip != md5($_SERVER["REMOTE_ADDR"].Config::get('key').$uid.$expire_in) && Config::get('enable_login_bind_ip')=='true') {
$user = new User();
$user->isLogin = false;
return $user;
}
if ($expire_in<time()) {
$user = new User();
$user->isLogin = false;
return $user;
$claims = SignedCookieSession::verify(
(string) Utils\Cookie::get(SignedCookieSession::COOKIE_NAME),
self::remoteAddress()
);
if ($claims === null) {
return self::guest();
}
$user = User::find($uid);
$user = User::find($claims['user_id']);
if ($user == null) {
$user = new User();
$user->isLogin = false;
return $user;
return self::guest();
}
if (!LoginSessionRevocationService::cookieKeyMatches($user, $key, $sessionVersion)) {
$user->isLogin = false;
return $user;
if (!LoginSessionRevocationService::snapshotMatches(
$claims['session_version'],
LoginSessionRevocationService::currentVersion($user)
)) {
return self::guest($user);
}
$user->isLogin = true;
return $user;
@ -75,12 +64,26 @@ class Cookie extends Base
{
$time = time() - 1000;
Utils\Cookie::set([
"uid" => null,
"email" => null,
"key" => null,
"ip" => null,
"expire_in" => null,
LoginSessionRevocationService::COOKIE_VERSION_NAME => null,
SignedCookieSession::COOKIE_NAME => null,
], $time);
self::clearLegacyCookies($time);
}
private static function remoteAddress(): ?string
{
$address = isset($_SERVER['REMOTE_ADDR']) ? trim((string) $_SERVER['REMOTE_ADDR']) : '';
return $address === '' ? null : $address;
}
private static function guest(?User $user = null): User
{
$user = $user ?? new User();
$user->isLogin = false;
return $user;
}
private static function clearLegacyCookies(?int $time = null): void
{
Utils\Cookie::set(array_fill_keys(self::LEGACY_COOKIE_NAMES, null), $time ?? time() - 1000);
}
}

@ -29,6 +29,10 @@ final class SignedCookieSession
}
$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,
@ -36,9 +40,7 @@ final class SignedCookieSession
'issued_at' => $issuedAt,
'expires_at' => $expiresAt,
'session_id' => bin2hex(random_bytes(32)),
'ip_digest' => $remoteAddress === null || trim($remoteAddress) === ''
? ''
: self::ipDigest($remoteAddress, $key),
'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));
@ -81,6 +83,10 @@ final class SignedCookieSession
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;

@ -8,26 +8,42 @@ use App\Services\Config;
use App\Services\Jwt;
use App\Services\RedisClient;
use App\Services\LoginSessionRevocationService;
use App\Services\Auth\SignedCookieSession;
final class CloudSessionService
{
private static function identity(): array
private static function identity(bool $requireValid = false): array
{
$driver = (string) Config::get('authDriver', 'cookie');
$names = match ($driver) {
'redis' => ['sid'], 'jwt' => ['token'], default => ['uid', 'key', 'ip', 'expire_in', 'login_session_version'],
'redis' => ['sid'], 'jwt' => ['token'], default => [SignedCookieSession::COOKIE_NAME],
};
$values = [];
foreach ($names as $name) {
$values[$name] = isset($_COOKIE[$name]) && is_string($_COOKIE[$name]) ? $_COOKIE[$name] : '';
}
return [$driver, $values, hash('sha256', json_encode([$driver, $values], JSON_THROW_ON_ERROR))];
$claims = null;
if ($driver === 'cookie') {
$claims = SignedCookieSession::verify(
$values[SignedCookieSession::COOKIE_NAME],
isset($_SERVER['REMOTE_ADDR']) ? (string) $_SERVER['REMOTE_ADDR'] : null
);
if ($requireValid && $claims === null) {
throw new CloudError('会话已失效,请重新登录', 401);
}
}
return [$driver, $values, hash('sha256', json_encode([$driver, $values], JSON_THROW_ON_ERROR)), $claims];
}
public static function current(User $user): string
{
[$driver, $values, $fingerprint] = self::identity();
[$driver, $values, $fingerprint, $claims] = self::identity(true);
$version = LoginSessionRevocationService::currentVersion($user);
if ($driver === 'cookie'
&& ((int) $claims['user_id'] !== (int) $user->id
|| (int) $claims['session_version'] !== $version)) {
throw new CloudError('会话已失效,请重新登录', 401);
}
$session = CloudSession::where('fingerprint', $fingerprint)->first();
if ($session !== null) {
if ((int) $session->user_id !== (int) $user->id || !(bool) $session->active
@ -55,7 +71,7 @@ final class CloudSessionService
$claims = Jwt::decodeArray($values['token'] ?? '');
$expiry = (int) ($claims->expire_time ?? 0);
} else {
$expiry = (int) ($values['expire_in'] ?? 0);
$expiry = (int) $claims['expires_at'];
}
if ($expiry <= time()) {
throw new CloudError('会话已失效', 401);

@ -3,6 +3,7 @@
namespace App\Services;
use App\Models\SiteVisitEvent;
use App\Services\Auth\SignedCookieSession;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
@ -157,7 +158,7 @@ class SiteAnalyticsRecorder
$context = ['user_id' => 0, 'is_admin' => false];
$cookies = $request->getCookieParams();
$driver = strtolower((string) Config::get('authDriver', 'redis'));
$cookieName = $driver === 'cookie' ? 'uid' : ($driver === 'jwt' ? 'token' : 'sid');
$cookieName = $driver === 'cookie' ? SignedCookieSession::COOKIE_NAME : ($driver === 'jwt' ? 'token' : 'sid');
if (!isset($cookies[$cookieName]) || trim((string) $cookies[$cookieName]) === '') {
return $context;
}

@ -5,6 +5,8 @@ namespace App\Services {
'authDriver' => 'cookie',
'super_admin' => '99',
'cloud_agent_gateway_secret' => 'kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk',
'key' => 'cloud-session-security-test-key-0001',
'enable_login_bind_ip' => 'false',
];
public static function get($name, $default = null) { return self::$values[$name] ?? $default; }
}
@ -41,6 +43,7 @@ namespace {
use App\Services\Cloud\CloudAgentClient;
use App\Services\Cloud\CloudError;
use App\Services\LoginSessionRevocationService;
use App\Services\Auth\SignedCookieSession;
use App\Services\AdminCsrf;
use App\Services\Config;
use App\Services\RedisClient;
@ -58,9 +61,17 @@ namespace {
$capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 1, 'uuid' => '11111111-1111-4111-8111-111111111111', 'status' => 'active', 'expires_at' => time() + 3600]);
$capsule->getConnection('default')->table('cloud_instances')->insert(['host_id' => 9, 'user_id' => 2, 'uuid' => '22222222-2222-4222-8222-222222222222', 'status' => 'active', 'expires_at' => time() + 3600]);
$user = new User(); $user->id = 1; $user->enable = 1; $user->is_admin = false; $user->login_session_version = 0; $user->save(); $user->isLogin = true; \App\Services\Auth::$user = $user;
$_COOKIE = ['uid' => '1', 'key' => 'authenticated-cookie-reference', 'ip' => 'bound-cookie', 'expire_in' => (string) (time() + 300), 'login_session_version' => '0'];
$cookieExpiry = time() + 300;
$_COOKIE = [SignedCookieSession::COOKIE_NAME => SignedCookieSession::issue(1, 0, $cookieExpiry)];
$id = CloudSessionService::current($user);
$assert($id === CloudSessionService::current($user) && CloudSession::count() === 1, 'Concurrent-equivalent cookie duplicated session.');
$assert((int) CloudSession::find($id)->expires_at === $cookieExpiry,
'Cloud session expiry was not derived from the verified signed claim.');
$_COOKIE['expire_in'] = (string) (time() + 86400 * 365);
$assert($id === CloudSessionService::current($user)
&& (int) CloudSession::find($id)->expires_at === $cookieExpiry,
'A retired expire_in cookie changed the cloud session lifetime.');
unset($_COOKIE['expire_in']);
$assert(CloudSessionService::active($id, 9, '11111111-1111-4111-8111-111111111111'), 'Active owner console rejected.');
$assert(!CloudSessionService::active($id, 9, '22222222-2222-4222-8222-222222222222')
&& !CloudSessionService::active($id, 8, '11111111-1111-4111-8111-111111111111'), 'Console crossed tenant or host boundary.');
@ -70,7 +81,7 @@ namespace {
User::where('id', 1)->update(['enable' => 0]); $assert(!CloudSessionService::active($id), 'Disabled user retained console.'); User::where('id', 1)->update(['enable' => 1]);
CloudSession::where('id', $id)->update(['expires_at' => time() - 1]); $assert(!CloudSessionService::active($id), 'Expired session retained console.'); CloudSession::where('id', $id)->update(['expires_at' => time() + 300]);
LoginSessionRevocationService::revokeUser($user); $assert(!CloudSessionService::active($id), 'Password/version change retained console.');
$_COOKIE['key'] = 'new-authenticated-cookie'; $_COOKIE['login_session_version'] = '1';
$_COOKIE = [SignedCookieSession::COOKIE_NAME => SignedCookieSession::issue(1, 1, time() + 300)];
$new = CloudSessionService::current($user); CloudSessionService::revokeCurrent(); $assert(!CloudSessionService::active($new), 'Logout failed to revoke ticket session.');
try { CloudSessionService::current($user); throw new RuntimeException('Revoked fingerprint was reactivated.'); } catch (CloudError $expected) {}
Config::$values['authDriver'] = 'redis'; $_COOKIE = ['sid' => 'test-redis-session']; RedisClient::$values['test-redis-session'] = LoginSessionRevocationService::encodeRedisSession(1, 1);
@ -113,7 +124,7 @@ namespace {
), 'Tampered or stale Agent-gateway signature was accepted.');
}
// Middleware uses the existing per-account CSRF session token and returns JSON instead of redirects.
Config::$values['authDriver'] = 'cookie'; $_COOKIE = ['uid' => '1', 'key' => 'third-auth-cookie', 'ip' => '', 'expire_in' => (string) (time() + 300), 'login_session_version' => '1'];
Config::$values['authDriver'] = 'cookie'; $_COOKIE = [SignedCookieSession::COOKIE_NAME => SignedCookieSession::issue(1, 1, time() + 300)];
$request = Request::createFromEnvironment(Environment::mock(['REQUEST_METHOD' => 'POST', 'REQUEST_URI' => '/api/v1/vms/1/actions']));
$called = false; $next = function ($request, $response) use (&$called) { $called = true; return $response; };
$middleware = new \App\Middleware\CloudApi(); $reply = $middleware($request, new Response(), $next);

@ -0,0 +1,132 @@
<?php
namespace App\Services {
final class Config
{
public static array $values = [
'key' => 'cookie-auth-integrity-test-key-0001',
'enable_login_bind_ip' => 'false',
];
public static function get($name, $default = null)
{
return self::$values[$name] ?? $default;
}
}
}
namespace App\Utils {
final class Cookie
{
public static array $writes = [];
public static function set($values, $expires): void
{
self::$writes[] = ['values' => $values, 'expires' => $expires];
foreach ($values as $name => $value) {
if ($value === null) {
unset($_COOKIE[$name]);
} else {
$_COOKIE[$name] = (string) $value;
}
}
}
public static function get($name)
{
return $_COOKIE[$name] ?? '';
}
}
}
namespace {
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\User;
use App\Services\Auth\Cookie as CookieAuth;
use App\Services\Auth\SignedCookieSession;
use App\Services\Config;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$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), '+/', '-_'), '=');
};
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('user', static function (Blueprint $table): void {
$table->increments('id');
$table->string('email');
$table->string('pass');
$table->integer('enable')->default(1);
$table->integer('is_admin')->default(0);
$table->integer('login_session_version')->default(0);
});
$user = new User();
$user->id = 7;
$user->email = 'cookie@example.test';
$user->pass = 'unused-password-hash';
$user->enable = 1;
$user->is_admin = 0;
$user->login_session_version = 0;
$user->save();
$_SERVER['REMOTE_ADDR'] = '203.0.113.7';
$_COOKIE = [
'uid' => '7', 'email' => $user->email, 'key' => 'legacy-key', 'ip' => 'legacy-ip',
'expire_in' => (string) (time() + 86400), 'login_session_version' => '0',
];
$auth = new CookieAuth();
$auth->login(7, 300);
$assert(count(\App\Utils\Cookie::$writes) === 2,
'Cookie login did not atomically issue the signed cookie and expire the legacy set.');
$assert(array_keys(\App\Utils\Cookie::$writes[0]['values']) === [SignedCookieSession::COOKIE_NAME],
'Cookie login issued more than the single signed credential.');
foreach (['uid', 'email', 'key', 'ip', 'expire_in', 'login_session_version'] as $legacyName) {
$assert(!isset($_COOKIE[$legacyName]), 'Cookie login retained legacy credential ' . $legacyName . '.');
}
$assert($auth->getUser()->isLogin === true, 'A freshly issued signed cookie did not authenticate.');
$token = $_COOKIE[SignedCookieSession::COOKIE_NAME];
[$prefix, $payload, $signature] = explode('.', $token);
$padding = (4 - strlen($payload) % 4) % 4;
$claims = json_decode(base64_decode(strtr($payload, '-_', '+/') . str_repeat('=', $padding), true),
true, 16, JSON_THROW_ON_ERROR);
$claims['expires_at'] += 86400 * 365;
$_COOKIE[SignedCookieSession::COOKIE_NAME] = $prefix . '.'
. $encode(json_encode($claims, JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR)) . '.' . $signature;
$assert($auth->getUser()->isLogin === false,
'Changing only expires_at reactivated or extended the signed cookie.');
$_COOKIE = [
'uid' => '7', 'email' => $user->email, 'key' => 'legacy-key', 'ip' => 'legacy-ip',
'expire_in' => (string) (time() + 86400), 'login_session_version' => '0',
];
$assert($auth->getUser()->isLogin === false, 'The retired six-cookie credential was accepted.');
$_COOKIE = [SignedCookieSession::COOKIE_NAME => SignedCookieSession::issue(7, 0, time() + 300)];
User::where('id', 7)->update(['login_session_version' => 1]);
$assert($auth->getUser()->isLogin === false, 'A revoked signed cookie version was accepted.');
Config::$values['enable_login_bind_ip'] = 'true';
$_COOKIE = [SignedCookieSession::COOKIE_NAME => SignedCookieSession::issue(7, 1, time() + 300, $_SERVER['REMOTE_ADDR'])];
$assert($auth->getUser()->isLogin === true, 'An IP-bound signed cookie was rejected at its issuing address.');
$_SERVER['REMOTE_ADDR'] = '203.0.113.8';
$assert($auth->getUser()->isLogin === false, 'An IP-bound signed cookie was accepted from another address.');
\App\Utils\Cookie::$writes = [];
$auth->logout();
$assert(count(\App\Utils\Cookie::$writes) === 2
&& array_key_exists(SignedCookieSession::COOKIE_NAME, \App\Utils\Cookie::$writes[0]['values']),
'Cookie logout did not expire the signed credential and legacy set.');
echo "Cookie auth single-token integrity, revocation, IP binding and clean break passed.\n";
}

@ -63,7 +63,8 @@ $configSource = file_get_contents($root . '/resources/views/venix/admin/config.t
$userSource = file_get_contents($root . '/resources/views/venix/admin/user/index.tpl');
$migrationSource = file_get_contents($root . '/sql/login_session_revocation.sql');
$baselineSqlSource = file_get_contents($root . '/sql/ss.sql');
if ($cookieSource === false || strpos($cookieSource, 'LoginSessionRevocationService::cookieKeyMatches') === false
if ($cookieSource === false || strpos($cookieSource, 'SignedCookieSession::verify') === false
|| strpos($cookieSource, 'LoginSessionRevocationService::snapshotMatches') === false
|| $redisSource === false || strpos($redisSource, 'LoginSessionRevocationService::decodeRedisSession') === false
|| $jwtSource === false || strpos($jwtSource, 'session_version') === false
|| $configControllerSource === false || strpos($configControllerSource, 'LoginSessionRevocationService::revokeAll') === false

@ -5,6 +5,7 @@ namespace App\Services {
{
public static array $values = [
'key' => 'signed-cookie-session-test-key-0001',
'enable_login_bind_ip' => 'true',
];
public static function get($name, $default = null)
@ -59,11 +60,16 @@ namespace {
'2001:db8::17', $now + 1) === null, 'Tampering ' . $field . ' did not invalidate the signature.');
}
Config::$values['enable_login_bind_ip'] = 'false';
$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.');
Config::$values['enable_login_bind_ip'] = 'true';
$assert(SignedCookieSession::verify($unbound, '203.0.113.9', $now + 1) === null,
'An unbound cookie was accepted after IP binding became mandatory.');
Config::$values['enable_login_bind_ip'] = 'false';
$invalid = $claims;
$invalid['issued_at'] = $now + 61;

Loading…
Cancel
Save