Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pterodactyl
GitHub Repository: pterodactyl/panel
Path: blob/1.0-develop/app/Http/Controllers/Api/Remote/SftpAuthenticationController.php
10280 views
1
<?php
2
3
namespace Pterodactyl\Http\Controllers\Api\Remote;
4
5
use Illuminate\Http\Request;
6
use Pterodactyl\Models\User;
7
use Pterodactyl\Models\Server;
8
use Illuminate\Http\JsonResponse;
9
use Pterodactyl\Facades\Activity;
10
use Pterodactyl\Models\Permission;
11
use phpseclib3\Crypt\PublicKeyLoader;
12
use Pterodactyl\Http\Controllers\Controller;
13
use phpseclib3\Exception\NoKeyLoadedException;
14
use Illuminate\Foundation\Auth\ThrottlesLogins;
15
use Pterodactyl\Exceptions\Http\HttpForbiddenException;
16
use Pterodactyl\Services\Servers\GetUserPermissionsService;
17
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
18
use Pterodactyl\Http\Requests\Api\Remote\SftpAuthenticationFormRequest;
19
use Symfony\Component\HttpKernel\Exception\TooManyRequestsHttpException;
20
21
class SftpAuthenticationController extends Controller
22
{
23
use ThrottlesLogins;
24
25
public function __construct(protected GetUserPermissionsService $permissions)
26
{
27
}
28
29
/**
30
* Authenticate a set of credentials and return the associated server details
31
* for a SFTP connection on the daemon. This supports both public key and password
32
* based credentials.
33
*/
34
public function __invoke(SftpAuthenticationFormRequest $request): JsonResponse
35
{
36
$connection = $this->parseUsername($request->input('username'));
37
if (empty($connection['server'])) {
38
throw new BadRequestHttpException('No valid server identifier was included in the request.');
39
}
40
41
if ($this->hasTooManyLoginAttempts($request)) {
42
$seconds = $this->limiter()->availableIn($this->throttleKey($request));
43
44
throw new TooManyRequestsHttpException($seconds, "Too many login attempts for this account, please try again in $seconds seconds.");
45
}
46
47
$user = $this->getUser($request, $connection['username']);
48
$server = $this->getServer($request, $connection['server']);
49
50
if ($request->input('type') !== 'public_key') {
51
if (!password_verify($request->input('password'), $user->password)) {
52
Activity::event('auth:sftp.fail')->property('method', 'password')->subject($user)->log();
53
54
$this->reject($request);
55
}
56
} else {
57
$key = null;
58
try {
59
$key = PublicKeyLoader::loadPublicKey(trim($request->input('password')));
60
} catch (NoKeyLoadedException) {
61
// do nothing
62
}
63
64
if (!$key || !$user->sshKeys()->where('fingerprint', $key->getFingerprint('sha256'))->exists()) {
65
// We don't log here because of the way the SFTP system works. This endpoint
66
// will get hit for every key the user provides, which could be 4 or 5. That is
67
// a lot of unnecessary log noise.
68
//
69
// For now, we'll only log failures due to a bad password as those are not likely
70
// to occur more than once in a session for the user, and are more likely to be of
71
// value to the end user.
72
$this->reject($request, is_null($key));
73
}
74
}
75
76
$this->validateSftpAccess($user, $server);
77
78
return new JsonResponse([
79
'user' => $user->uuid,
80
'server' => $server->uuid,
81
'permissions' => $this->permissions->handle($server, $user),
82
]);
83
}
84
85
/**
86
* Finds the server being requested and ensures that it belongs to the node this
87
* request stems from.
88
*/
89
protected function getServer(Request $request, string $uuid): Server
90
{
91
return Server::query()
92
->where(fn ($builder) => $builder->where('uuid', $uuid)->orWhere('uuidShort', $uuid))
93
->where('node_id', $request->attributes->get('node')->id)
94
->firstOr(function () use ($request) {
95
$this->reject($request);
96
});
97
}
98
99
/**
100
* Finds a user with the given username or increments the login attempts.
101
*/
102
protected function getUser(Request $request, string $username): User
103
{
104
return User::query()->where('username', $username)->firstOr(function () use ($request) {
105
$this->reject($request);
106
});
107
}
108
109
/**
110
* Parses the username provided to the request.
111
*
112
* @return array{"username": string, "server": string}
113
*/
114
protected function parseUsername(string $value): array
115
{
116
// Reverse the string to avoid issues with usernames that contain periods.
117
$parts = explode('.', strrev($value), 2);
118
119
// Unreverse the strings after parsing them apart.
120
return [
121
'username' => strrev(array_get($parts, 1)),
122
'server' => strrev(array_get($parts, 0)),
123
];
124
}
125
126
/**
127
* Rejects the request and increments the login attempts.
128
*/
129
protected function reject(Request $request, bool $increment = true): void
130
{
131
if ($increment) {
132
$this->incrementLoginAttempts($request);
133
}
134
135
throw new HttpForbiddenException('Authorization credentials were not correct, please try again.');
136
}
137
138
/**
139
* Validates that a user should have permission to use SFTP for the given server.
140
*/
141
protected function validateSftpAccess(User $user, Server $server): void
142
{
143
if (!$user->root_admin && $server->owner_id !== $user->id) {
144
$permissions = $this->permissions->handle($server, $user);
145
146
if (!in_array(Permission::ACTION_FILE_SFTP, $permissions)) {
147
Activity::event('server:sftp.denied')->actor($user)->subject($server)->log();
148
149
throw new HttpForbiddenException('You do not have permission to access SFTP for this server.');
150
}
151
}
152
153
$server->validateCurrentState();
154
}
155
156
/**
157
* Get the throttle key for the given request.
158
*/
159
protected function throttleKey(Request $request): string
160
{
161
$username = explode('.', strrev($request->input('username', '')));
162
163
return strtolower(strrev($username[0] ?? '') . '|' . $request->ip()); // @phpstan-ignore nullCoalesce.offset
164
}
165
}
166
167