blob: ba8e3b72b2403df86a938844d2a150763b3bb775 (
plain) (
blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
|
<?php
class SSHKey
{
/**
* Retrieves the private key from storage or generates a new one if it does not exist.
*
* @param bool|null &$regen A reference parameter that indicates whether a new private
* key was generated (true if regenerated, false otherwise).
* @return string|null Returns the private key as a string if successful, or null if the key could not be generated.
*/
public static function getPrivateKey(?bool &$regen = false): ?string
{
$regen = false;
$privKey = Property::get("rebootcontrol-private-key");
if (!$privKey) {
$rsaKey = openssl_pkey_new([
'private_key_bits' => 2048,
'private_key_type' => OPENSSL_KEYTYPE_RSA]);
if (!openssl_pkey_export( openssl_pkey_get_private($rsaKey), $privKey)) {
return null;
}
Property::set("rebootcontrol-private-key", $privKey);
if (Module::isAvailable('sysconfig')) {
ConfigTgz::rebuildAllConfigs();
}
$regen = true;
}
return $privKey;
}
public static function getPublicKey(): ?string
{
$pkImport = openssl_pkey_get_private(self::getPrivateKey());
if ($pkImport === false)
return null;
return self::sshEncodePublicKey($pkImport);
}
private static function sshEncodePublicKey($privKey): ?string
{
$keyInfo = openssl_pkey_get_details($privKey);
if ($keyInfo === false)
return null;
$buffer = pack("N", 7) . "ssh-rsa" .
self::sshEncodeBuffer($keyInfo['rsa']['e']) .
self::sshEncodeBuffer($keyInfo['rsa']['n']);
return "ssh-rsa " . base64_encode($buffer);
}
private static function sshEncodeBuffer(string $buffer): string
{
$len = strlen($buffer);
// Prefix with extra null byte if the MSB is set, to ensure
// nobody will ever interpret this as a negative number
if (ord($buffer[0]) & 0x80) {
$len++;
$buffer = "\x00" . $buffer;
}
return pack("Na*", $len, $buffer);
}
}
|