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/Controllers/CloudInternalController.php

272 lines
11 KiB
PHP

<?php
namespace App\Controllers;
use App\Services\Config;
use App\Services\RedisClient;
use App\Services\Cloud\CloudAgentClient;
use App\Services\Cloud\CloudAgentSecretCipher;
use App\Services\Cloud\CloudConsoleTicketService;
use App\Services\Cloud\CloudError;
use App\Services\Cloud\CloudOperationCompletionService;
use App\Models\CloudHostAgent;
/** Private HMAC endpoints used only by the local Agent gateway. */
final class CloudInternalController
{
public static function validSignature(
string $method,
string $path,
string $body,
array $headers,
string $key,
int $now,
string $expectedService = 'agent-gateway'
): bool {
$time = $headers['timestamp'] ?? '';
$nonce = $headers['nonce'] ?? '';
$digest = $headers['digest'] ?? '';
$actor = $headers['actor'] ?? '';
$signature = $headers['signature'] ?? '';
if (strlen($key) < 32 || str_contains($key, "\0")
|| str_contains($key, "\r") || str_contains($key, "\n")
|| !is_string($time) || preg_match('/^[0-9]{1,12}$/D', $time) !== 1
|| (string) (int) $time !== $time || abs($now - (int) $time) > 60
|| !is_string($nonce)
|| preg_match('/^[A-Za-z0-9_-]{16,128}$/D', $nonce) !== 1
|| !is_string($digest)
|| preg_match('/^[a-f0-9]{64}$/D', $digest) !== 1
|| !hash_equals(hash('sha256', $body), $digest)
|| !is_string($signature)
|| preg_match('/^[a-f0-9]{64}$/D', $signature) !== 1
|| !is_string($actor) || strlen($actor) > 4096
|| !self::validGatewayActor($actor, $expectedService)) {
return false;
}
$expected = hash_hmac('sha256', CloudAgentClient::canonical(
$method,
$path,
$digest,
$time,
$nonce,
$actor
), $key);
return hash_equals($expected, $signature);
}
public function introspection($request, $response)
{
try {
$body = (string) $request->getBody();
$secret = (string) Config::get('cloud_agent_gateway_secret', '');
$headers = [
'timestamp' => $request->getHeaderLine('X-Virt-Timestamp'),
'nonce' => $request->getHeaderLine('X-Virt-Nonce'),
'digest' => $request->getHeaderLine('X-Virt-Content-SHA256'),
'actor' => $request->getHeaderLine('X-Virt-Actor'),
'signature' => $request->getHeaderLine('X-Virt-Signature'),
];
if ($request->getMethod() !== 'POST'
|| $request->getUri()->getPath()
!== '/api/internal/cloud/session-introspection'
|| $request->getUri()->getQuery() !== ''
|| strlen($body) > 4096
|| !self::validSignature(
$request->getMethod(),
$request->getRequestTarget(),
$body,
$headers,
$secret,
time()
)) {
return $response->withJson(['active' => false], 403)
->withHeader('Cache-Control', 'no-store');
}
if (!self::consumeNonce($headers['nonce'])) {
return $response->withJson(['active' => false], 403)
->withHeader('Cache-Control', 'no-store');
}
try {
$value = json_decode($body, true, 8, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
throw new CloudError('控制台校验请求无效', 400);
}
if (!is_array($value) || array_is_list($value)) {
throw new CloudError('控制台校验请求无效', 400);
}
return $response->withJson(
CloudConsoleTicketService::introspect($value)
)->withHeader('Cache-Control', 'no-store');
} catch (CloudError $error) {
return $response->withJson(
['active' => false],
$error->httpStatus
)->withHeader('Cache-Control', 'no-store');
} catch (\Throwable $error) {
error_log('Cloud console introspection unavailable: '
. get_class($error));
return $response->withJson(['active' => false], 503)
->withHeader('Cache-Control', 'no-store');
}
}
public function agentAuth($request, $response)
{
try {
$body = (string) $request->getBody();
$secret = (string) Config::get('cloud_agent_gateway_secret', '');
$headers = [
'timestamp' => $request->getHeaderLine('X-Virt-Timestamp'),
'nonce' => $request->getHeaderLine('X-Virt-Nonce'),
'digest' => $request->getHeaderLine('X-Virt-Content-SHA256'),
'actor' => $request->getHeaderLine('X-Virt-Actor'),
'signature' => $request->getHeaderLine('X-Virt-Signature'),
];
if ($request->getMethod() !== 'POST'
|| $request->getUri()->getPath()
!== '/api/internal/cloud/agent-auth'
|| $request->getUri()->getQuery() !== ''
|| strlen($body) > 1024
|| !self::validSignature(
$request->getMethod(),
$request->getRequestTarget(),
$body,
$headers,
$secret,
time()
)
|| !self::consumeNonce($headers['nonce'])) {
return $response->withJson(['active' => false], 403)
->withHeader('Cache-Control', 'no-store');
}
try {
$value = json_decode($body, true, 8, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
throw new CloudError('Agent 认证请求无效', 400);
}
if (!is_array($value) || array_is_list($value)
|| count($value) !== 2
|| !array_key_exists('agent_id', $value)
|| !array_key_exists('agent_secret', $value)
|| !is_string($value['agent_id'])
|| preg_match('/^[1-9][0-9]{0,18}$/D', $value['agent_id']) !== 1
|| !is_string($value['agent_secret'])
|| strlen($value['agent_secret']) < 32
|| strlen($value['agent_secret']) > 256
|| preg_match('/^[\x21-\x7e]+$/D', $value['agent_secret']) !== 1) {
throw new CloudError('Agent 认证请求无效', 400);
}
$hostId = (int) $value['agent_id'];
$setting = CloudHostAgent::find($hostId);
if ($setting === null || !(bool) $setting->enabled
|| trim((string) $setting->sealed_api_secret) === '') {
return $response->withJson(['active' => false], 403)
->withHeader('Cache-Control', 'no-store');
}
$expected = CloudAgentSecretCipher::decrypt(
(string) $setting->sealed_api_secret,
$hostId
);
if (!hash_equals($expected, $value['agent_secret'])) {
return $response->withJson(['active' => false], 403)
->withHeader('Cache-Control', 'no-store');
}
return $response->withJson([
'active' => true,
'agent_id' => (string) $hostId,
])->withHeader('Cache-Control', 'no-store');
} catch (CloudError $error) {
return $response->withJson(['active' => false], $error->httpStatus)
->withHeader('Cache-Control', 'no-store');
} catch (\Throwable $error) {
error_log('Cloud Agent authentication unavailable: '
. get_class($error));
return $response->withJson(['active' => false], 503)
->withHeader('Cache-Control', 'no-store');
}
}
public function operationCompletion($request, $response)
{
try {
$body = (string) $request->getBody();
$headers = [
'timestamp' => $request->getHeaderLine('X-Virt-Timestamp'),
'nonce' => $request->getHeaderLine('X-Virt-Nonce'),
'digest' => $request->getHeaderLine('X-Virt-Content-SHA256'),
'actor' => $request->getHeaderLine('X-Virt-Actor'),
'signature' => $request->getHeaderLine('X-Virt-Signature'),
];
$path = '/api/internal/cloud/operation-completion';
if ($request->getMethod() !== 'POST'
|| $request->getUri()->getPath() !== $path
|| $request->getUri()->getQuery() !== ''
|| strlen($body) > 1048576
|| !self::validSignature('POST', $path, $body, $headers,
(string) Config::get('cloud_agent_gateway_secret', ''),
time())
|| !self::consumeNonce($headers['nonce'])) {
return $response->withJson(['accepted' => false], 403)
->withHeader('Cache-Control', 'no-store');
}
try {
$input = json_decode($body, true, 64, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
throw new CloudError('Agent 完成回执无效', 400);
}
if (!is_array($input)) {
throw new CloudError('Agent 完成回执无效', 400);
}
return $response->withJson(
CloudOperationCompletionService::accept($input)
)->withHeader('Cache-Control', 'no-store');
} catch (CloudError $error) {
return $response->withJson(['accepted' => false],
$error->httpStatus)->withHeader('Cache-Control', 'no-store');
} catch (\Throwable $error) {
error_log('Cloud operation completion unavailable: '
. get_class($error));
return $response->withJson(['accepted' => false], 503)
->withHeader('Cache-Control', 'no-store');
}
}
private static function consumeNonce(string $nonce): bool
{
$redis = (new RedisClient())->getClient();
return (string) $redis->set(
'virt-agent-gateway-nonce:' . $nonce,
'1',
'EX',
120,
'NX'
) === 'OK';
}
private static function validGatewayActor(
string $encoded,
string $expectedService
): bool
{
if (preg_match('/^[A-Za-z0-9_-]+$/D', $encoded) !== 1) {
return false;
}
$padding = (4 - strlen($encoded) % 4) % 4;
$raw = base64_decode(
strtr($encoded, '-_', '+/') . str_repeat('=', $padding),
true
);
if ($raw === false) {
return false;
}
try {
$actor = json_decode($raw, true, 4, JSON_THROW_ON_ERROR);
} catch (\Throwable $error) {
return false;
}
return is_array($actor) && !array_is_list($actor)
&& count($actor) === 1
&& ($actor['service'] ?? null) === $expectedService;
}
}