mirror of
https://github.com/tiennm99/coolify.git
synced 2026-09-04 04:17:46 +00:00
fix: prevent sporadic SSH permission denied by validating key content
The root cause of sporadic "Permission denied (publickey)" errors was that validateSshKey() only checked if the key file existed on disk, never verifying its content matched the database. When keys were rotated or updated, the stale file persisted and SSH used the wrong key. Changes: - validateSshKey() now refreshes key from DB and compares file content - Server saved event detects private_key_id changes to invalidate mux - PrivateKey storeInFileSystem() uses file locking to prevent races - PrivateKey saved event auto-resyncs file on key content changes - Enforces 0600 permissions on key files Fixes coollabsio/coolify#7724
This commit is contained in:
@@ -8,6 +8,7 @@ use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Log;
|
||||
use Illuminate\Support\Facades\Process;
|
||||
use Illuminate\Support\Facades\Storage;
|
||||
|
||||
class SshMultiplexingHelper
|
||||
{
|
||||
@@ -208,13 +209,37 @@ class SshMultiplexingHelper
|
||||
|
||||
private static function validateSshKey(PrivateKey $privateKey): void
|
||||
{
|
||||
$keyLocation = $privateKey->getKeyLocation();
|
||||
$checkKeyCommand = "ls $keyLocation 2>/dev/null";
|
||||
$keyCheckProcess = Process::run($checkKeyCommand);
|
||||
$privateKey->refresh();
|
||||
|
||||
if ($keyCheckProcess->exitCode() !== 0) {
|
||||
$keyLocation = $privateKey->getKeyLocation();
|
||||
$filename = "ssh_key@{$privateKey->uuid}";
|
||||
$disk = Storage::disk('ssh-keys');
|
||||
|
||||
$needsRewrite = false;
|
||||
|
||||
if (! $disk->exists($filename)) {
|
||||
$needsRewrite = true;
|
||||
} else {
|
||||
$diskContent = $disk->get($filename);
|
||||
if ($diskContent !== $privateKey->private_key) {
|
||||
Log::warning('SSH key file content does not match database, resyncing', [
|
||||
'key_uuid' => $privateKey->uuid,
|
||||
]);
|
||||
$needsRewrite = true;
|
||||
}
|
||||
}
|
||||
|
||||
if ($needsRewrite) {
|
||||
$privateKey->storeInFileSystem();
|
||||
}
|
||||
|
||||
// Ensure correct permissions (SSH requires 0600)
|
||||
if (file_exists($keyLocation)) {
|
||||
$currentPerms = fileperms($keyLocation) & 0777;
|
||||
if ($currentPerms !== 0600) {
|
||||
chmod($keyLocation, 0600);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static function getCommonSshOptions(Server $server, string $sshKeyLocation, int $connectionTimeout, int $serverInterval, bool $isScp = false): string
|
||||
|
||||
Reference in New Issue
Block a user