Skip to content

Commit 9022958

Browse files
committed
improve ssh key validation
1 parent ea1e294 commit 9022958

File tree

3 files changed

+52
-9
lines changed

3 files changed

+52
-9
lines changed

resources/lib/UnitySite.php

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,20 @@ public static function getGithubKeys($username)
5252

5353
public static function testValidSSHKey($key_str)
5454
{
55+
$key_str = trim($key_str);
56+
if ($key_str == "") {
57+
return false;
58+
}
59+
// https://github.com/phpseclib/phpseclib/issues/2077
60+
// key loader still throws exception, this just mutes a warning for phpunit
61+
if (preg_match("/^[0-9]+$/", $key_str)) {
62+
return false;
63+
}
64+
// https://github.com/phpseclib/phpseclib/issues/2076
65+
// key loader still throws exception, this just mutes a warning for phpunit
66+
if (!is_null(@json_decode($key_str))) {
67+
return false;
68+
}
5569
try {
5670
PublicKeyLoader::load($key_str);
5771
return true;

test/unit/AjaxSshValidateTest.php

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
<?php
2+
3+
namespace UnityWebPortal\lib;
4+
5+
use PHPUnit\Framework\TestCase;
6+
use PHPUnit\Framework\Attributes\DataProvider;
7+
8+
class AjaxSshValidateTest extends TestCase
9+
{
10+
public static function providerTestSshValidate()
11+
{
12+
// sanity check only, see UnitySiteTest for more comprehensive test cases
13+
return [
14+
[false, "foobar"],
15+
// phpcs:disable
16+
[true, "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIB+XqO25MUB9x/pS04I3JQ7rMGboWyGXh0GUzkOrTi7a"],
17+
// phpcs:enable
18+
];
19+
}
20+
21+
#[DataProvider("providerTestSshValidate")]
22+
public function testSshValidate(bool $is_valid, string $pubkey)
23+
{
24+
$_SERVER["REQUEST_METHOD"] = "POST";
25+
$_POST["key"] = $pubkey;
26+
ob_start();
27+
include __DIR__ . "/../../webroot/js/ajax/ssh_validate.php";
28+
$output = ob_get_clean();
29+
if ($is_valid) {
30+
$this->assertEquals("true", $output);
31+
} else {
32+
$this->assertEquals("false", $output);
33+
}
34+
}
35+
}

webroot/js/ajax/ssh_validate.php

Lines changed: 3 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,6 @@
11
<?php
22

3-
require "../../../resources/autoload.php";
3+
require_once __DIR__ . "/../../../resources/lib/UnitySite.php";
4+
use UnityWebPortal\lib\UnitySite;
45

5-
use phpseclib3\Crypt\PublicKeyLoader;
6-
7-
try {
8-
PublicKeyLoader::load($_POST['key'], $password = false);
9-
echo "true";
10-
} catch (Exception $e) {
11-
echo "false";
12-
}
6+
echo UnitySite::testValidSSHKey($_POST["key"]) ? "true" : "false";

0 commit comments

Comments
 (0)