Fix 2 SFTP Lockout Ratelimit Bugs (#7257)

Fixes two SFTP lockout bugs:

- `ad374661f` moved the server lookup after the password check, so fake
server identifiers bypassed the rate limit.
- `24f340c9a` keyed the lockout on server + Wings IP, so anyone could
lock every user out of a server.

Unknown servers are now rejected before any credential check, and the
lockout is keyed on the normalised username + resolved server UUID.
This commit is contained in:
Joshua Piper
2026-10-06 22:46:46 -04:00
committed by GitHub
parent 4a6377c675
commit 66ce0f2a16
2 changed files with 123 additions and 15 deletions
@@ -9,6 +9,7 @@ use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Exception\NoKeyLoadedException;
use Pterodactyl\Enum\Permissions;
@@ -31,6 +32,9 @@ class SftpAuthenticationController extends Controller
{
use ThrottlesLogins;
/** 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
@@ -41,6 +45,8 @@ class SftpAuthenticationController extends Controller
$connection = $this->parseUsername(JsonValueGuard::string($request->validated('username')));
throw_if(empty($connection['server']), BadRequestHttpException::class, 'No valid server identifier was included in the request.');
$server = $this->getServer($request, $connection['server']);
if ($this->hasTooManyLoginAttempts($request)) {
$seconds = RateLimiter::availableIn($this->throttleKey($request));
@@ -84,8 +90,6 @@ class SftpAuthenticationController extends Controller
}
}
$server = $this->getServer($request, $connection['server']);
$this->validateSftpAccess($user, $server, $permissions);
return new JsonResponse([
@@ -106,7 +110,13 @@ class SftpAuthenticationController extends Controller
->where('node_id', RemoteRequestNode::get($request)->id)
->first();
return $server ?? $this->reject($request);
if ($server === null) {
$this->reject($request, false);
}
$this->throttleServer = $server;
return $server;
}
/**
@@ -127,7 +137,7 @@ class SftpAuthenticationController extends Controller
}
/**
* Rejects the request and increments the login attempts.
* Rejects the request, optionally incrementing the login attempts.
*/
protected function reject(Request $request, bool $increment = true): never
{
@@ -157,13 +167,13 @@ class SftpAuthenticationController extends Controller
}
/**
* Get the throttle key for the given request.
* Get the throttle key for the given request: normalised requested username plus server UUID
*/
protected function throttleKey(Request $request): string
{
$raw = JsonValueGuard::nullableString($request->input('username', '')) ?? '';
$username = explode('.', strrev($raw));
$username = Str::transliterate(mb_strtolower(mb_rtrim($this->parseUsername($raw)['username'], ' ')));
return mb_strtolower(strrev($username[0] ?? '').'|'.$request->ip()); // @phpstan-ignore nullCoalesce.offset
return $username.'|'.($this->throttleServer->uuid ?? '');
}
}
@@ -4,11 +4,15 @@ declare(strict_types=1);
namespace Pterodactyl\Tests\Pest\Integration\Api\Remote\SftpAuthenticationControllerTest;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
use phpseclib3\Crypt\EC;
use Pterodactyl\Enum\Permissions;
use Pterodactyl\Models\ActivityLog;
use Pterodactyl\Models\Node;
use Pterodactyl\Models\Server;
use Pterodactyl\Models\User;
use Pterodactyl\Models\UserSSHKey;
use Pterodactyl\Tests\Integration\IntegrationTestCase;
@@ -47,14 +51,63 @@ test('password is validated correctly', function () {
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'foobar'])->assertOk();
});
test('user is throttled if invalid credentials are provided', function () {
// Requests alternate between two usernames, so each throttle key is hit
// every other request and the lockout fires once the first key has
// recorded the configured number of attempts.
$limit = (int) config('auth.lockout.attempts') * 2;
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit; $i++) {
$this->postJson('/api/remote/sftp/auth', ['type' => 'public_key', 'username' => $i % 2 === 0 ? $this->user->username : getUsername(), 'password' => 'invalid key'])->assertStatus($i === $limit ? 429 : 403);
$this->postJson('/api/remote/sftp/auth', ['type' => 'public_key', 'username' => getUsername(), 'password' => 'invalid key'])->assertStatus($i === $limit ? 429 : 403);
}
});
test('a locked out user does not lock other users out of the same server', function () {
$other = User::factory()->create(['password' => 'foobar', 'root_admin' => true]);
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'wrong password'])->assertStatus($i === $limit ? 429 : 403);
}
$this->postJson('/api/remote/sftp/auth', ['username' => $other->username.'.'.$this->server->uuidShort, 'password' => 'foobar'])->assertOk();
});
test('a user locked out on one server can still use their other servers', function () {
$second = $this->createServerModel(['owner_id' => $this->user->id, 'node_id' => $this->server->node_id]);
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'wrong password'])->assertStatus($i === $limit ? 429 : 403);
}
$this->postJson('/api/remote/sftp/auth', ['username' => $this->user->username.'.'.$second->uuidShort, 'password' => 'foobar'])->assertOk();
});
test('attempts with the long uuid and the short identifier share one lockout', function () {
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i < $limit; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername($i % 2 === 0), 'password' => 'wrong password'])->assertForbidden();
}
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(true), 'password' => 'wrong password'])->assertStatus(429);
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(false), 'password' => 'wrong password'])->assertStatus(429);
});
test('username spelling variants share one lockout', function (bool $exists) {
$base = 'jane_ss_'.mb_strtolower(Str::random(8));
if ($exists) {
$this->user->update(['username' => $base]);
}
// The database collation ignores trailing spaces, case and accents, and treats 'ß' as 'ss'.
$variants = [$base.' ', mb_strtoupper($base), strtr($base, ['a' => 'ä', 'e' => 'é']), str_replace('ss', 'ß', $base)];
config(['auth.lockout.attempts' => count($variants)]);
foreach ($variants as $variant) {
$this->postJson('/api/remote/sftp/auth', ['username' => $variant.'.'.$this->server->uuidShort, 'password' => 'wrong password'])->assertForbidden();
}
$this->postJson('/api/remote/sftp/auth', ['username' => $base.'.'.$this->server->uuidShort, 'password' => 'wrong password'])->assertStatus(429);
})->with(['known user' => [true], 'unknown user' => [false]]);
test('the lockout does not depend on the requesting ip', function () {
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i < $limit; $i++) {
$this->withServerVariables(['REMOTE_ADDR' => '10.0.0.'.($i + 1)])->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'wrong password'])->assertForbidden();
}
$this->withServerVariables(['REMOTE_ADDR' => '10.0.1.1'])->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'wrong password'])->assertStatus(429);
});
test('wrong password for a real user on a real server is logged and counts toward the lockout', function () {
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'wrong password'])->assertStatus($i === $limit ? 429 : 403);
}
expect(failedSftpLogins($this->user)->count())->toBe($limit);
expect(failedSftpLogins($this->user)->first()->properties['method'])->toBe('password');
});
test('user is not throttled if no public key matches', function () {
for ($i = 0; $i <= 10; $i++) {
$this->postJson('/api/remote/sftp/auth', ['type' => 'public_key', 'username' => getUsername(), 'password' => EC::createKey('Ed25519')->getPublicKey()->toString('OpenSSH')])->assertForbidden();
@@ -70,10 +123,30 @@ test('unknown user password login still performs a password hash', function () {
$this->postJson('/api/remote/sftp/auth', ['username' => 'does-not-exist.'.$this->server->uuidShort, 'password' => 'foobar'])->assertForbidden();
Hash::shouldHaveReceived('make')->once()->with('foobar');
});
test('password is checked before the server is looked up', function () {
test('unknown server is rejected without hashing, lockout or activity', function () {
Hash::spy();
$this->postJson('/api/remote/sftp/auth', ['username' => $this->user->username.'.doesnotexist', 'password' => 'wrong password'])->assertForbidden();
Hash::shouldHaveReceived('check')->once();
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit + 2; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => $this->user->username.'.doesnotexist', 'password' => 'wrong password'])->assertForbidden();
}
Hash::shouldNotHaveReceived('check');
Hash::shouldNotHaveReceived('make');
expect(failedSftpLogins($this->user)->count())->toBe(0);
});
test('unknown username on an unknown server does not hash either', function () {
Hash::spy();
$this->postJson('/api/remote/sftp/auth', ['username' => 'does-not-exist.doesnotexist', 'password' => 'foobar'])->assertForbidden();
Hash::shouldNotHaveReceived('check');
Hash::shouldNotHaveReceived('make');
});
test('rotating made-up server identifiers never reaches a password check or throttles', function () {
Hash::spy();
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit * 3; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => $this->user->username.'.fake'.$i, 'password' => 'wrong password'])->assertForbidden();
}
Hash::shouldNotHaveReceived('check');
expect(failedSftpLogins($this->user)->count())->toBe(0);
});
test('an x509 certificate offered as a public key is rejected and throttled', function (): void {
$certificate = file_get_contents(base_path('tests/Fixtures/keys/x509-certificate.pem'));
@@ -85,9 +158,23 @@ test('an x509 certificate offered as a public key is rejected and throttled', fu
test('request is rejected if server belongs to different node', function (string $type) {
$node2 = $this->createServerModel()->node;
setAuthorization($node2);
Hash::spy();
$password = $type === 'public_key' ? UserSSHKey::factory()->for($this->user)->create()->public_key : 'foobar';
$this->postJson('/api/remote/sftp/auth', ['type' => $type, 'username' => getUsername(), 'password' => $password])->assertForbidden();
Hash::shouldNotHaveReceived('check');
Hash::shouldNotHaveReceived('make');
expect(failedSftpLogins($this->user)->count())->toBe(0);
})->with('authorizationTypeDataProvider');
test('wrong-node requests never lock the user out', function () {
$node2 = $this->createServerModel()->node;
setAuthorization($node2);
$limit = (int) config('auth.lockout.attempts');
for ($i = 0; $i <= $limit + 2; $i++) {
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'wrong password'])->assertForbidden();
}
setAuthorization();
$this->postJson('/api/remote/sftp/auth', ['username' => getUsername(), 'password' => 'foobar'])->assertOk();
});
test('request is denied if user lacks sftp permission', function () {
[$user, $server] = $this->generateTestAccount([Permissions::FileRead->value]);
$user->update(['password' => 'foobar']);
@@ -131,3 +218,14 @@ function setAuthorization(?Node $node = null): void
$this->withHeader('Authorization', 'Bearer '.$node->daemon_token_id.'.'.decrypt($node->daemon_token));
})->call(pterodactylTestCase());
}
/**
* Failed SFTP password login activity logged against a user.
*
* @return Builder<ActivityLog>
*/
function failedSftpLogins(User $user): Builder
{
return ActivityLog::query()
->where('event', 'auth:sftp.fail')
->whereHas('subjects', fn (Builder $query) => $query->where('subject_id', $user->id)->where('subject_type', $user->getMorphClass()));
}