46 lines
1.4 KiB
PHP
46 lines
1.4 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Support;
|
|
|
|
use phpseclib3\Net\SSH2;
|
|
use RuntimeException;
|
|
|
|
final class SshHostKeyVerifier
|
|
{
|
|
/** @throws RuntimeException */
|
|
public static function verify(SSH2 $client, string $host): void
|
|
{
|
|
$knownHostsPath = config('vmware.ssh_known_hosts');
|
|
if (!$knownHostsPath) {
|
|
if (config('vmware.tls_verify', true)) {
|
|
throw new RuntimeException("SSH host key verification required for {$host}: set VCENTER_SSH_KNOWN_HOSTS or VCENTER_TLS_VERIFY=false");
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
if (!is_readable($knownHostsPath)) {
|
|
throw new RuntimeException("SSH known_hosts file not readable: {$knownHostsPath}");
|
|
}
|
|
|
|
$serverKey = (string) $client->getServerPublicHostKey();
|
|
$serverKeyParts = preg_split('/\s+/', trim($serverKey));
|
|
$serverKeyValue = $serverKeyParts[1] ?? $serverKey;
|
|
|
|
$lines = file($knownHostsPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES) ?: [];
|
|
foreach ($lines as $line) {
|
|
$parts = preg_split('/\s+/', trim($line));
|
|
if (count($parts) < 3 || $parts[0] !== $host) {
|
|
continue;
|
|
}
|
|
if (hash_equals($parts[2], $serverKeyValue)) {
|
|
return;
|
|
}
|
|
}
|
|
|
|
throw new RuntimeException("SSH host key verification failed for {$host}: no matching known_hosts entry");
|
|
}
|
|
}
|