diff --git a/app/Console/Commands/Extensions/InstallCommand.php b/app/Console/Commands/Extensions/InstallCommand.php index 020a0710c..de37665bb 100644 --- a/app/Console/Commands/Extensions/InstallCommand.php +++ b/app/Console/Commands/Extensions/InstallCommand.php @@ -7,26 +7,42 @@ namespace Pterodactyl\Console\Commands\Extensions; use Illuminate\Console\Attributes\Description; use Illuminate\Console\Attributes\Signature; use Illuminate\Console\Command; +use Illuminate\Support\Facades\File; use Pterodactyl\Contracts\Extensions\InstallsExtensions; use Pterodactyl\Exceptions\Extensions\ExtensionAlreadyInstalledException; use Pterodactyl\Exceptions\Extensions\InvalidExtensionException; use Pterodactyl\Services\Extensions\ExtensionManifest; +use Pterodactyl\Services\Extensions\ExtensionUrlDownloader; #[Description('Install an extension package into the extensions directory.')] #[Signature('p:extension:install - {path : Path to a .pteroext/.zip archive or an unpacked extension directory.} + {path : Path to a .pteroext/.zip archive or an unpacked extension directory, or a signed install URL.} {--enable : Enable the extension (and run its migrations) after installing.} {--replace : Replace an installed extension with the same id without asking.}')] class InstallCommand extends Command { - public function handle(InstallsExtensions $installer): int + public function handle(InstallsExtensions $installer, ExtensionUrlDownloader $urls): int { + $download = null; + try { - $manifest = $this->install($installer); + $path = $this->argument('path'); + // A URL is only ever a signed install URL: its signature is verified before + // anything is downloaded, so the panel never installs from an arbitrary address. + if ($urls->isUrl($path)) { + $this->components->info('Verifying the install URL and downloading the extension.'); + $path = $download = $urls->download($path); + } + + $manifest = $this->install($installer, $path); } catch (InvalidExtensionException $invalidExtensionException) { $this->components->error($invalidExtensionException->getMessage()); return self::FAILURE; + } finally { + if ($download !== null) { + rescue(fn () => File::delete($download)); + } } $this->components->info(sprintf( @@ -41,9 +57,8 @@ class InstallCommand extends Command } /** Replacing an installed extension needs --replace, or a yes when run interactively. */ - private function install(InstallsExtensions $installer): ExtensionManifest + private function install(InstallsExtensions $installer, string $path): ExtensionManifest { - $path = $this->argument('path'); $enable = (bool) $this->option('enable'); try { diff --git a/app/Services/Extensions/ExtensionUrlDownloader.php b/app/Services/Extensions/ExtensionUrlDownloader.php new file mode 100644 index 000000000..52529b37c --- /dev/null +++ b/app/Services/Extensions/ExtensionUrlDownloader.php @@ -0,0 +1,148 @@ +verifiedUrl($link); + $path = storage_path('app'.DIRECTORY_SEPARATOR.'extensions-tmp'.DIRECTORY_SEPARATOR.Str::random(12).'.pteroext'); + File::ensureDirectoryExists(dirname($path)); + + try { + $response = Http::withHeaders([self::INSTALL_HEADER => (string) config('extensions.panel_version')]) + ->connectTimeout(10) + ->timeout(120) + ->sink($path) + ->withOptions(['on_headers' => $this->assertWithinSizeLimit(...)]) + ->get($url); + + throw_unless($response->successful(), InvalidExtensionException::class, $this->failureMessage($path, $response->status())); + throw_if(File::size($path) > self::MAX_PACKAGE_BYTES, InvalidExtensionException::class, 'The extension package is larger than the panel accepts.'); + } catch (Throwable $throwable) { + rescue(fn () => File::delete($path)); + + // Guzzle wraps whatever the on_headers check throws. + $refusal = $throwable instanceof InvalidExtensionException ? $throwable : $throwable->getPrevious(); + throw_if($refusal instanceof InvalidExtensionException, $refusal); + throw_unless($throwable instanceof ConnectionException || $throwable instanceof TransferException, $throwable); + + throw new InvalidExtensionException('Could not download the extension. Please try again.', previous: $throwable); + } + + return $path; + } + + /** + * The address to fetch a package from, taken from the URL's signed token. + * + * @throws InvalidExtensionException + */ + public function verifiedUrl(string $link): string + { + throw_unless((bool) config('extensions.signed_urls.enabled'), InvalidExtensionException::class, 'Installing extensions from a URL is disabled on this panel.'); + throw_unless(extension_loaded('sodium'), InvalidExtensionException::class, 'The PHP sodium extension is required to verify signed install URLs.'); + + $jwt = Str::afterLast((string) preg_replace('/[?#].*$/', '', trim($link)), '/'); + + $token = null; + + try { + $token = (new Parser(new JoseEncoder))->parse($jwt); + $key = InMemory::base64Encoded((string) config('extensions.signed_urls.public_key')); + $signed = $token instanceof UnencryptedToken && (new Validator)->validate($token, new SignedWith(new Eddsa, $key)); + } catch (Throwable) { + $signed = false; + } + + // Nothing in the token is trusted, or even reported back, before its signature verifies. + throw_unless( + $signed && $token instanceof UnencryptedToken, + InvalidExtensionException::class, + 'This is not a signed install URL. Extensions can only be installed from a URL that Pterodactyl has signed.', + ); + + $claims = $token->claims(); + throw_unless( + $token->hasBeenIssuedBy((string) config('extensions.signed_urls.issuer')) && $token->isPermittedFor((string) config('extensions.signed_urls.audience')), + InvalidExtensionException::class, + 'This signed URL is not an extension install URL.', + ); + // A token without an expiry never reports itself as expired, so one is required. + throw_if( + ! $claims->has('exp') || $token->isExpired(CarbonImmutable::now()), + InvalidExtensionException::class, + 'This install URL has expired. Copy a new install command.', + ); + + $base = $claims->get('url'); + throw_unless(is_string($base) && $this->isUrl($base), InvalidExtensionException::class, 'This install URL does not say where to download the extension from.'); + + return $base.$jwt; + } + + /** Refuse a package that declares itself too large before any of it is written to disk. */ + private function assertWithinSizeLimit(ResponseInterface $response): void + { + throw_if( + (int) $response->getHeaderLine('Content-Length') > self::MAX_PACKAGE_BYTES, + InvalidExtensionException::class, + 'The extension package is larger than the panel accepts.', + ); + } + + /** The server explains refusals in a JSON body, which was written to the sink file. */ + private function failureMessage(string $path, int $status): string + { + $body = rescue(fn (): mixed => json_decode(File::get($path), true), report: false); + $message = is_array($body) ? ($body['error']['message'] ?? null) : null; + + return is_string($message) + ? "The download was refused: {$message}" + : "The download was refused (HTTP {$status})."; + } +} diff --git a/config/extensions.php b/config/extensions.php index d0985b114..2fc27780a 100644 --- a/config/extensions.php +++ b/config/extensions.php @@ -33,6 +33,13 @@ return [ // Where enabled extensions' built frontend assets are published. 'assets_directory' => public_path('assets/extensions'), + 'signed_urls' => [ + 'enabled' => env('PTERODACTYL_EXTENSIONS_URL_INSTALLS_ENABLED', true), + 'public_key' => 'eMHrvRiVVicU1SwUF8yeV3KXkQq6qAOZpmpilO0dg/o=', + 'issuer' => 'Infraly, LLC', + 'audience' => 'pterodactyl-panel', + ], + // The filesystem disk that holds files uploaded through `file` settings. They are // served by the panel from /extension-files with sandboxing headers, so the disk must // be private: a public disk (such as `public`) is refused. diff --git a/tests/Integration/Services/Extensions/ExtensionUrlDownloaderTest.php b/tests/Integration/Services/Extensions/ExtensionUrlDownloaderTest.php new file mode 100644 index 000000000..df9667c34 --- /dev/null +++ b/tests/Integration/Services/Extensions/ExtensionUrlDownloaderTest.php @@ -0,0 +1,133 @@ +keypair = sodium_crypto_sign_keypair(); + $this->base = rtrim($this->faker->url(), '/').'/'; + $this->other = rtrim($this->faker->url(), '/').'/'; + config(['extensions.signed_urls.public_key' => base64_encode(sodium_crypto_sign_publickey($this->keypair))]); + $this->downloader = $this->app->make(ExtensionUrlDownloader::class); +}); + +/** + * @param array{iss?: string, aud?: string, exp?: CarbonImmutable|null, url?: string|null} $claims + */ +function signed(string $keypair, string $prefix, array $claims = []): string +{ + $key = InMemory::plainText(sodium_crypto_sign_secretkey($keypair)); + $builder = Configuration::forAsymmetricSigner(new Eddsa, $key, $key)->builder() + ->issuedBy($claims['iss'] ?? config('extensions.signed_urls.issuer')) + ->permittedFor($claims['aud'] ?? config('extensions.signed_urls.audience')) + ->relatedTo('1234'); + + $expires = array_key_exists('exp', $claims) ? $claims['exp'] : CarbonImmutable::now()->addMinutes(15); + if ($expires instanceof CarbonImmutable) { + $builder = $builder->expiresAt($expires); + } + + if (($claims['url'] ?? null) !== null) { + $builder = $builder->withClaim('url', $claims['url']); + } + + return $prefix.$builder->getToken(new Eddsa, $key)->toString(); +} + +test('a valid token is accepted', function (): void { + $source = signed($this->keypair, $this->base, ['url' => $this->base]); + + expect($this->downloader->verifiedUrl($source))->toBe($source); +}); + +test('the signed claim wins over the host it was handed with', function (): void { + $source = signed($this->keypair, $this->other, ['url' => $this->base]); + + expect($this->downloader->verifiedUrl($source))->toStartWith($this->base); +}); + +test('a valid token is refused when disabled', function (): void { + config(['extensions.signed_urls.enabled' => false]); + Http::fake(); + + expect(fn () => $this->downloader->download(signed($this->keypair, $this->base, ['url' => $this->base]))) + ->toThrow(InvalidExtensionException::class, 'disabled on this panel'); + Http::assertNothingSent(); +}); + +test('a token signed with another key is refused', function (): void { + $this->downloader->verifiedUrl(signed(sodium_crypto_sign_keypair(), $this->base, ['url' => $this->base])); +})->throws(InvalidExtensionException::class, 'not a signed install URL'); + +test('a source that carries no token is refused', function (): void { + $this->downloader->verifiedUrl($this->other.'extension.pteroext'); +})->throws(InvalidExtensionException::class, 'not a signed install URL'); + +test('a tampered token is refused', function (): void { + $source = signed($this->keypair, $this->base, ['url' => $this->base]); + [$header, $claims, $signature] = explode('.', mb_substr($source, mb_strlen($this->base))); + $forged = json_decode((string) base64_decode(strtr($claims, '-_', '+/'), true), true); + $forged['url'] = $this->other; + $claims = rtrim(strtr(base64_encode((string) json_encode($forged)), '+/', '-_'), '='); + + $this->downloader->verifiedUrl($this->base."{$header}.{$claims}.{$signature}"); +})->throws(InvalidExtensionException::class, 'not a signed install URL'); + +test('an expired token is refused', function (): void { + $this->downloader->verifiedUrl(signed($this->keypair, $this->base, ['url' => $this->base, 'exp' => CarbonImmutable::now()->subSecond()])); +})->throws(InvalidExtensionException::class, 'expired'); + +test('a token without an expiry is refused', function (): void { + $this->downloader->verifiedUrl(signed($this->keypair, $this->base, ['url' => $this->base, 'exp' => null])); +})->throws(InvalidExtensionException::class, 'expired'); + +test('a signed token for another purpose is refused', function (): void { + $this->downloader->verifiedUrl(signed($this->keypair, $this->base, ['url' => $this->base, 'aud' => 'something-else'])); +})->throws(InvalidExtensionException::class, 'not an extension install URL'); + +test('a token without a source claim is refused', function (): void { + $this->downloader->verifiedUrl(signed($this->keypair, $this->base)); +})->throws(InvalidExtensionException::class, 'does not say where to download'); + +test('it downloads the package with the install header', function (): void { + Http::fake([$this->base.'*' => Http::response('package-bytes')]); + + $path = $this->downloader->download(signed($this->keypair, $this->base, ['url' => $this->base])); + + try { + expect(File::get($path))->toBe('package-bytes'); + Http::assertSent(fn ($request): bool => $request->hasHeader(ExtensionUrlDownloader::INSTALL_HEADER)); + } finally { + File::delete($path); + } +}); + +test('nothing is requested for a token that does not verify', function (): void { + Http::fake(); + + expect(fn () => $this->downloader->download(signed(sodium_crypto_sign_keypair(), $this->base, ['url' => $this->base]))) + ->toThrow(InvalidExtensionException::class); + Http::assertNothingSent(); +}); + +test('a refusal from the server is reported and leaves no file behind', function (): void { + Http::fake([$this->base.'*' => Http::response(['error' => ['message' => 'Refused.']], 403)]); + $before = File::glob(storage_path('app/extensions-tmp/*.pteroext')); + + expect(fn () => $this->downloader->download(signed($this->keypair, $this->base, ['url' => $this->base]))) + ->toThrow(InvalidExtensionException::class, 'Refused.'); + expect(File::glob(storage_path('app/extensions-tmp/*.pteroext')))->toBe($before); +});