Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Http/Requests/Api/Client/Account/StoreSSHKeyRequest.php
10284 views
1
<?php
2
3
namespace Pterodactyl\Http\Requests\Api\Client\Account;
4
5
use phpseclib3\Crypt\DSA;
6
use phpseclib3\Crypt\RSA;
7
use Pterodactyl\Models\UserSSHKey;
8
use Illuminate\Validation\Validator;
9
use phpseclib3\Crypt\PublicKeyLoader;
10
use phpseclib3\Crypt\Common\PublicKey;
11
use phpseclib3\Exception\NoKeyLoadedException;
12
use Pterodactyl\Http\Requests\Api\Client\ClientApiRequest;
13
14
class StoreSSHKeyRequest extends ClientApiRequest
15
{
16
protected ?PublicKey $key;
17
18
/**
19
* Returns the rules for this request.
20
*/
21
public function rules(): array
22
{
23
return [
24
'name' => UserSSHKey::getRulesForField('name'),
25
'public_key' => UserSSHKey::getRulesForField('public_key'),
26
];
27
}
28
29
/**
30
* Check to see if this SSH key has already been added to the user's account
31
* and if so return an error.
32
*/
33
public function withValidator(Validator $validator): void
34
{
35
$validator->after(function () {
36
try {
37
$this->key = PublicKeyLoader::loadPublicKey($this->input('public_key'));
38
} catch (NoKeyLoadedException $exception) {
39
$this->validator->errors()->add('public_key', 'The public key provided is not valid.');
40
41
return;
42
}
43
44
if ($this->key instanceof DSA) {
45
$this->validator->errors()->add('public_key', 'DSA keys are not supported.');
46
}
47
48
if ($this->key instanceof RSA && $this->key->getLength() < 2048) {
49
$this->validator->errors()->add('public_key', 'RSA keys must be at least 2048 bytes in length.');
50
}
51
52
$fingerprint = $this->key->getFingerprint('sha256');
53
if ($this->user()->sshKeys()->where('fingerprint', $fingerprint)->exists()) {
54
$this->validator->errors()->add('public_key', 'The public key provided already exists on your account.');
55
}
56
});
57
}
58
59
/**
60
* Returns the public key but formatted in a consistent manner.
61
*/
62
public function getPublicKey(): string
63
{
64
return $this->key->toString('PKCS8');
65
}
66
67
/**
68
* Returns the SHA256 fingerprint of the key provided.
69
*/
70
public function getKeyFingerprint(): string
71
{
72
if (!$this->key) {
73
throw new \Exception('The public key was not properly loaded for this request.');
74
}
75
76
return $this->key->getFingerprint('sha256');
77
}
78
}
79
80