Files
pterodactyl-panel/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php
T

180 lines
6.6 KiB
PHP
Raw Normal View History

<?php
2026-10-05 18:10:18 -04:00
declare(strict_types=1);
2018-01-19 19:58:57 -06:00
namespace Pterodactyl\Http\Controllers\Api\Remote;
2026-10-05 18:10:18 -04:00
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
2026-10-05 18:10:18 -04:00
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
2026-10-07 03:46:46 +01:00
use Illuminate\Support\Str;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Exception\NoKeyLoadedException;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Exceptions\Http\HttpForbiddenException;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Facades\Activity;
use Pterodactyl\Http\Controllers\Controller;
use Pterodactyl\Http\Requests\Api\Remote\RemoteRequestNode;
use Pterodactyl\Http\Requests\Api\Remote\SftpAuthenticationFormRequest;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use Pterodactyl\Models\UserSSHKey;
use Pterodactyl\Services\Servers\GetUserPermissionsService;
2026-10-05 18:10:18 -04:00
use Pterodactyl\Support\JsonValueGuard;
use Pterodactyl\Traits\Helpers\ThrottlesLogins;
use Pterodactyl\Validation\UserSSHKeyRules;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
2022-05-15 16:06:00 -04:00
class SftpAuthenticationController extends Controller
{
use ThrottlesLogins;
2026-10-07 03:46:46 +01:00
/** The server resolved for the current request, used to key the lockout. */
private ?Server $throttleServer = null;
/**
* Authenticate a set of credentials and return the associated server details
* for a SFTP connection on the daemon. This supports both public key and password
* based credentials.
*/
2026-10-05 18:10:18 -04:00
public function __invoke(SftpAuthenticationFormRequest $request, GetUserPermissionsService $permissions): JsonResponse
{
2026-10-05 18:10:18 -04:00
$connection = $this->parseUsername(JsonValueGuard::string($request->validated('username')));
throw_if(empty($connection['server']), BadRequestHttpException::class, 'No valid server identifier was included in the request.');
2026-10-07 03:46:46 +01:00
$server = $this->getServer($request, $connection['server']);
if ($this->hasTooManyLoginAttempts($request)) {
2026-10-05 18:10:18 -04:00
$seconds = RateLimiter::availableIn($this->throttleKey($request));
2022-10-14 10:59:20 -06:00
throw new TooManyRequestsHttpException($seconds, "Too many login attempts for this account, please try again in $seconds seconds.");
}
$user = User::query()->where('username', $connection['username'])->first();
2026-10-05 18:10:18 -04:00
if ($request->validated('type') !== 'public_key') {
$password = JsonValueGuard::string($request->validated('password'));
if ($user === null) {
Hash::make($password);
$this->reject($request);
}
if (! Hash::check($password, $user->password)) {
Activity::event('auth:sftp.fail')->property('method', 'password')->subject($user)->log();
$this->reject($request);
}
} else {
$key = null;
2026-10-05 18:10:18 -04:00
$publicKey = mb_trim(JsonValueGuard::string($request->validated('password')));
if (UserSSHKeyRules::isSupportedPublicKey($publicKey)) {
try {
$key = PublicKeyLoader::loadPublicKey($publicKey);
} catch (NoKeyLoadedException) {
// do nothing
}
}
$matched = $key !== null && UserSSHKey::query()
->where('user_id', $user?->id)
->where('fingerprint', $key->getFingerprint('sha256'))
->exists();
if ($user === null || ! $matched) {
2026-10-05 18:10:18 -04:00
// Don't log public key failures - this endpoint is hit once for every key the
// user offers, so only the (rarer, more meaningful) bad-password failures are logged.
$this->reject($request, ($key) === null);
}
}
2026-10-05 18:10:18 -04:00
$this->validateSftpAccess($user, $server, $permissions);
return new JsonResponse([
'user' => $user->uuid,
'server' => $server->uuid,
2026-10-05 18:10:18 -04:00
'permissions' => $permissions->handle($server, $user),
]);
}
/**
* Finds the server being requested and ensures that it belongs to the node this
* request stems from.
*/
protected function getServer(Request $request, string $uuid): Server
{
2026-10-05 18:10:18 -04:00
$server = Server::query()
->where(fn (Builder $builder) => $builder->where('uuid', $uuid)->orWhere('uuidShort', $uuid))
->where('node_id', RemoteRequestNode::get($request)->id)
->first();
2026-10-07 03:46:46 +01:00
if ($server === null) {
$this->reject($request, false);
}
$this->throttleServer = $server;
return $server;
}
/**
* Parses the username provided to the request.
*
* @return array{"username": string, "server": string}
*/
protected function parseUsername(string $value): array
{
2019-12-07 16:14:04 -08:00
// Reverse the string to avoid issues with usernames that contain periods.
$parts = explode('.', strrev($value), 2);
2019-12-07 16:14:04 -08:00
// Unreverse the strings after parsing them apart.
return [
2026-10-05 18:10:18 -04:00
'username' => strrev($parts[1] ?? ''),
'server' => strrev($parts[0]),
];
}
/**
2026-10-07 03:46:46 +01:00
* Rejects the request, optionally incrementing the login attempts.
*/
2026-10-05 18:10:18 -04:00
protected function reject(Request $request, bool $increment = true): never
{
if ($increment) {
$this->incrementLoginAttempts($request);
}
throw new HttpForbiddenException('Authorization credentials were not correct, please try again.');
}
/**
* Validates that a user should have permission to use SFTP for the given server.
*/
2026-10-05 18:10:18 -04:00
protected function validateSftpAccess(User $user, Server $server, GetUserPermissionsService $permissions): void
{
2026-10-05 18:10:18 -04:00
if (! $user->root_admin && $server->owner_id !== $user->id) {
$resolved = $permissions->handle($server, $user);
2026-10-05 18:10:18 -04:00
if (! in_array(Permissions::FileSftp->value, $resolved)) {
Activity::event('server:sftp.denied')->actor($user)->subject($server)->log();
2021-01-23 12:33:34 -08:00
throw new HttpForbiddenException('You do not have permission to access SFTP for this server.');
}
}
$server->validateCurrentState();
}
/**
2026-10-07 03:46:46 +01:00
* Get the throttle key for the given request: normalised requested username plus server UUID
*/
protected function throttleKey(Request $request): string
{
2026-10-05 18:10:18 -04:00
$raw = JsonValueGuard::nullableString($request->input('username', '')) ?? '';
2026-10-07 03:46:46 +01:00
$username = Str::transliterate(mb_strtolower(mb_rtrim($this->parseUsername($raw)['username'], ' ')));
2019-12-07 16:14:04 -08:00
2026-10-07 03:46:46 +01:00
return $username.'|'.($this->throttleServer->uuid ?? '');
}
}