Files

84 lines
2.5 KiB
PHP
Raw Permalink Normal View History

2026-10-11 03:18:48 -04:00
<?php
declare(strict_types=1);
namespace Pterodactyl\Actions\Users;
2026-10-11 09:47:32 -04:00
use Illuminate\Support\Facades\Validator;
2026-10-11 03:18:48 -04:00
use Pterodactyl\Contracts\Users\CreatesSshKeys;
2026-10-11 14:24:52 -04:00
use Pterodactyl\Facades\Activity;
2026-10-11 03:18:48 -04:00
use Pterodactyl\Models\User;
use Pterodactyl\Models\UserSSHKey;
final readonly class CreateSshKey implements CreatesSshKeys
{
2026-10-11 09:47:32 -04:00
/**
* The longest public key, in bytes, that is accepted or parsed.
*/
public const int PUBLIC_KEY_MAX_LENGTH = 16384;
/**
* The prefixes of the public key formats users may add.
*
* @var list<string>
*/
private const array PUBLIC_KEY_PREFIXES = [
'ssh-rsa ',
'ssh-ed25519 ',
'ecdsa-sha2-',
'sk-ssh-ed25519@openssh.com ',
'sk-ecdsa-sha2-nistp256@openssh.com ',
'-----BEGIN PUBLIC KEY-----',
'-----BEGIN RSA PUBLIC KEY-----',
'-----BEGIN EC PUBLIC KEY-----',
'-----BEGIN DSA PUBLIC KEY-----',
'---- BEGIN SSH2 PUBLIC KEY ----',
];
/**
2026-10-11 23:50:53 -04:00
* A key a request parses is first held to PUBLIC_KEY_MAX_LENGTH and isSupportedPublicKey().
2026-10-11 09:47:32 -04:00
*
* @return NormalizedValidationRules
*/
public static function rules(): array
{
return [
'name' => ['required', 'string'],
'public_key' => ['required', 'string'],
'fingerprint' => ['required', 'string'],
];
}
/**
* Whether a value is a supported public key format that is safe to parse: not empty,
* no longer than the limit, without NUL bytes, and starting with a known key prefix.
* Certificates are not public keys and are rejected.
*/
public static function isSupportedPublicKey(string $value): bool
{
$value = mb_trim($value);
if ($value === '' || mb_strlen($value) > self::PUBLIC_KEY_MAX_LENGTH || str_contains($value, "\0")) {
return false;
}
foreach (self::PUBLIC_KEY_PREFIXES as $prefix) {
if (str_starts_with($value, $prefix)) {
return true;
}
}
return false;
}
2026-10-11 03:18:48 -04:00
public function create(User $user, string $name, string $publicKey, string $fingerprint): UserSSHKey
{
2026-10-11 23:12:13 -04:00
$attributes = Validator::validate(['name' => $name, 'public_key' => $publicKey, 'fingerprint' => $fingerprint], self::rules());
$key = $user->sshKeys()->create($attributes);
2026-10-11 14:24:52 -04:00
Activity::event('user:ssh-key.create')->subject($user, $key)->property('fingerprint', $key->fingerprint)->log();
return $key;
2026-10-11 03:18:48 -04:00
}
}