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/Cloud/CloudAgentFileSecretResolve...

169 lines
6.4 KiB
PHP

<?php
namespace App\Services\Cloud;
/**
* Resolve Go Agent transport material from root-owned files.
*
* The agent registry deliberately stores only public identity metadata. This
* resolver is the panel-side bridge to the corresponding host-local secret
* directory; no key, certificate, or private key is read from a database
* model. Files are named by the already-validated Agent ID and are checked
* as ordinary files before their contents are consumed.
*/
final class CloudAgentFileSecretResolver implements CloudAgentSecretResolver
{
private const AGENT_ID_PATTERN = '/^[A-Za-z0-9][A-Za-z0-9_.:-]{0,95}$/D';
private const MAX_KEY_FILE_BYTES = 4096;
private const MAX_TLS_FILE_BYTES = 1024 * 1024;
/**
* @param callable|null $fileReader Optional test-only reader. It receives
* an absolute path and returns the file bytes or null.
*/
public function __construct(
private readonly string $directory,
?callable $fileReader = null,
) {
if (!self::validAbsoluteDirectory($directory)) {
throw new \InvalidArgumentException('Agent secret directory is invalid');
}
$this->fileReader = \Closure::fromCallable($fileReader ?? [self::class, 'readSecureFile']);
}
/** @var \Closure(string):string|null */
private \Closure $fileReader;
/**
* Files use the following fixed names per Agent:
*
* <id>.hmac canonical standard-base64, 32 raw bytes
* <id>.ca.pem panel trust anchor
* <id>.crt panel client certificate
* <id>.key panel client private key
*
* Returning paths instead of certificate contents keeps the TLS library's
* normal certificate handling and lets CloudAgentClient re-check the
* registered certificate fingerprint before every request.
*
* @return array{hmac_key:string,ca_file:string,cert_file:string,key_file:string}|null
*/
public function resolve(string $agentId): ?array
{
if (preg_match(self::AGENT_ID_PATTERN, $agentId) !== 1) {
return null;
}
$base = rtrim($this->directory, '/') . '/' . $agentId;
$hmac = $this->readHmac($base . '.hmac');
if ($hmac === null) {
return null;
}
$paths = [
'ca_file' => $base . '.ca.pem',
'cert_file' => $base . '.crt',
'key_file' => $base . '.key',
];
foreach ($paths as $path) {
if (($this->fileReader)($path) === null) {
return null;
}
}
return ['hmac_key' => $hmac] + $paths;
}
private function readHmac(string $path): ?string
{
$contents = ($this->fileReader)($path);
if (!is_string($contents)) {
return null;
}
// Permit exactly one conventional final LF/CRLF, but do not trim
// arbitrary whitespace: accepting it would make the file protocol
// ambiguous across PHP and Go.
if (str_ends_with($contents, "\r\n")) {
$contents = substr($contents, 0, -2);
} elseif (str_ends_with($contents, "\n")) {
$contents = substr($contents, 0, -1);
}
if ($contents === '' || preg_match('/^[A-Za-z0-9+\/=]+$/D', $contents) !== 1) {
return null;
}
$decoded = base64_decode($contents, true);
if (!is_string($decoded) || strlen($decoded) !== 32
|| !hash_equals($contents, base64_encode($decoded))) {
return null;
}
return $decoded;
}
private static function validAbsoluteDirectory(string $directory): bool
{
if ($directory === '' || $directory === '/' || $directory !== trim($directory)
|| $directory[0] !== '/' || preg_match('/[\x00-\x1F\x7F]/', $directory) === 1
|| str_contains($directory, '//')) {
return false;
}
$parts = explode('/', trim($directory, '/'));
foreach ($parts as $part) {
if ($part === '' || $part === '.' || $part === '..'
|| preg_match('/^[A-Za-z0-9_.:-]+$/D', $part) !== 1) {
return false;
}
}
return true;
}
/**
* Read a secret file only when its leaf and every parent are real,
* non-writable filesystem objects. The injected reader used by contract
* tests is intentionally the sole bypass; production construction uses
* this method by default.
*/
private static function readSecureFile(string $path): ?string
{
if ($path === '' || $path[0] !== '/' || preg_match('/[\x00-\x1F\x7F]/', $path) === 1) {
return null;
}
// Reuse the transport resolver's ownership/symlink policy before
// reading the HMAC, CA, certificate or private key. The bounded
// size check below remains stricter for secret files.
// HMAC material is a bearer signing secret just like the private key;
// group/other-readable files are rejected even though CA/cert PEM
// files may use the looser non-writable certificate mode.
$privateKey = str_ends_with($path, '.key') || str_ends_with($path, '.hmac');
if (!CloudAgentHostClientResolver::validateCredentialPath($path, $privateKey)) {
return null;
}
$stat = @lstat($path);
$maxBytes = str_ends_with($path, '.hmac')
? self::MAX_KEY_FILE_BYTES : self::MAX_TLS_FILE_BYTES;
if (!is_array($stat)
|| (($stat['mode'] ?? 0) & 0170000) !== 0100000
|| (($stat['mode'] ?? 0) & 0022) !== 0
|| (int) ($stat['size'] ?? 0) < 1
|| (int) ($stat['size'] ?? 0) > $maxBytes) {
return null;
}
$directory = dirname($path);
while ($directory !== '/') {
$directoryStat = @lstat($directory);
$mode = is_array($directoryStat) ? (int) ($directoryStat['mode'] ?? 0) : 0;
if (!is_array($directoryStat)
|| ($mode & 0170000) !== 0040000
|| ($mode & 0022) !== 0) {
return null;
}
$parent = dirname($directory);
if ($parent === $directory) {
return null;
}
$directory = $parent;
}
$value = @file_get_contents($path);
return is_string($value) && strlen($value) <= $maxBytes
? $value : null;
}
}