Fix: Make sure invalid private keys can not be added

This commit is contained in:
peaklabs-dev
2024-09-16 13:02:48 +02:00
parent f9b7841572
commit 02017334e5
2 changed files with 31 additions and 14 deletions

View File

@@ -59,13 +59,11 @@ class Create extends Component
{ {
if ($updateProperty === 'value') { if ($updateProperty === 'value') {
try { try {
$this->publicKey = PublicKeyLoader::load($this->$updateProperty)->getPublicKey()->toString('OpenSSH', ['comment' => '']); $key = PublicKeyLoader::load($this->$updateProperty);
$this->publicKey = $key->getPublicKey()->toString('OpenSSH', ['comment' => '']);
} catch (\Throwable $e) { } catch (\Throwable $e) {
if ($this->$updateProperty === '') {
$this->publicKey = ''; $this->publicKey = '';
} else { $this->addError('value', 'Invalid private key');
$this->publicKey = 'Invalid private key';
}
} }
} }
$this->validateOnly($updateProperty); $this->validateOnly($updateProperty);
@@ -73,7 +71,21 @@ class Create extends Component
public function createPrivateKey() public function createPrivateKey()
{ {
$this->validate(); $this->validate([
'name' => 'required|string',
'value' => [
'required',
'string',
function ($attribute, $value, $fail) {
try {
PublicKeyLoader::load($value);
} catch (\Throwable $e) {
$fail('The private key is invalid.');
}
},
],
]);
try { try {
$this->value = trim($this->value); $this->value = trim($this->value);
if (! str_ends_with($this->value, "\n")) { if (! str_ends_with($this->value, "\n")) {

View File

@@ -4,6 +4,7 @@ namespace App\Models;
use OpenApi\Attributes as OA; use OpenApi\Attributes as OA;
use phpseclib3\Crypt\PublicKeyLoader; use phpseclib3\Crypt\PublicKeyLoader;
use Illuminate\Validation\ValidationException;
#[OA\Schema( #[OA\Schema(
description: 'Private Key model', description: 'Private Key model',
@@ -38,7 +39,15 @@ class PrivateKey extends BaseModel
if (substr($privateKey, -1) !== "\n") { if (substr($privateKey, -1) !== "\n") {
$key->private_key = $privateKey . "\n"; $key->private_key = $privateKey . "\n";
} }
$key->fingerprint = $key->generateFingerprint();
try {
$publicKey = PublicKeyLoader::load($key->private_key)->getPublicKey();
$key->fingerprint = $publicKey->getFingerprint('sha256');
} catch (\Throwable $e) {
throw ValidationException::withMessages([
'private_key' => ['The private key is invalid.'],
]);
}
}); });
} }
@@ -89,11 +98,7 @@ class PrivateKey extends BaseModel
public function generateFingerprint() public function generateFingerprint()
{ {
try {
$key = PublicKeyLoader::load($this->private_key); $key = PublicKeyLoader::load($this->private_key);
return $key->getPublicKey()->getFingerprint('sha256'); return $key->getPublicKey()->getFingerprint('sha256');
} catch (\Throwable $e) {
return 'invalid_' . md5($this->private_key); // TODO: DO NOT ALLOW SAVING IF INVALID SSH KEYS SAY SSH KEY IS INVALID
}
} }
} }