-
Notifications
You must be signed in to change notification settings - Fork 0
/
functions.php
354 lines (275 loc) · 13.7 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
<?php
defined('_SFTPGO') or die;
use Amp\Http\Server\Response;
use Amp\Http\Status;
function isAllowedIP($remoteIP) {
global $allowed_ips;
logMessage('Starting Execution Process');
if (array_search($remoteIP, $allowed_ips) !== false) {
logMessage('Web Execution Mode...' . $remoteIP . ' is allowed.');
return true;
}
logMessage('Web Execution Mode...' . $remoteIP . ' is not allowed.');
return false;
}
function authenticateUser($data) {
logMessage('Before getData()');
$data = getData($data);
logMessage('After getData()');
if (!empty($data)) {
try {
global $connections, $domains_to_strip_automatically, $convert_username_to_lowercase, $username_minimum_length, $username_blacklist;
// Convert username to lowercase if setting is enabled:
if (isset($convert_username_to_lowercase) && $convert_username_to_lowercase === true) {
$beforeUsername = $data['username'];
$data['username'] = strtolower($data['username']);
if ($beforeUsername !== $data['username']) {
logMessage('Converted ' . $beforeUsername . ' to ' . $data['username']);
}
}
// Strip specific organization email domains if provided:
if (isset($domains_to_strip_automatically)) {
logMessage('Username before domain stripping: ' . $data['username']);
foreach($domains_to_strip_automatically as $domain) {
$domain = '@'.str_replace('@', '', $domain);
logMessage('Attempting to strip ' . $domain . ' from provided username.');
$data['username'] = str_replace($domain, '', $data['username']);
}
}
// Prevent short usernames from being processed:
if (isset($username_minimum_length) && $username_minimum_length > 0) {
if (strlen($data['username']) < $username_minimum_length) {
logMessage('Denying ' . $data['username'] . ' since length is less than minimum allowed (' . $username_minimum_length . ')');
return denyRequest();
}
}
// Prevent blacklisted usernames from being processed:
if (isset($username_blacklist) && !empty($username_blacklist)) {
if (array_search($data['username'], $username_blacklist) !== false) {
logMessage('Denying ' . $data['username'] . ' since it is in the username blacklist');
return denyRequest();
}
}
foreach($connections as $connectionName => $connection) {
logMessage('Before connection attempt to ' . $connectionName);
$connection->reconnect();
logMessage('After connection attempt to ' . $connectionName);
$configuration = $connection->getConfiguration();
$baseDn = $configuration->get('base_dn');
$organizationalUnit = $baseDn;
$user = $connection->query()
->in($organizationalUnit)
->where('samaccountname', '=', $data['username'])
->first();
if ($user) {
logMessage('Username exists: ' . $data['username']);
// Our user is a member of one of the allowed groups.
// Continue with authentication.
$userDistinguishedName = $user['distinguishedname'][0];
logMessage('Before authentication attempt for: ' . $data['username']);
if ($connection->auth()->attempt($userDistinguishedName, $data['password'])) {
$groups = getUserGroups($user);
// User has been successfully authenticated.
logMessage('After authentication attempt for: ' . $data['username'] . ' (success!)');
$output = createResponseObject($connectionName, $data['username'], $groups);
logMessage('Disconnecting from ' . $connectionName);
$connection->disconnect();
return createResponse($output);
} else {
// Username or password is incorrect.
logMessage('After authentication attempt for: ' . $data['username'] . ' (failed!)');
logMessage('Disconnecting from ' . $connectionName);
$connection->disconnect();
return denyRequest();
}
} else {
logMessage('Disconnecting from ' . $connectionName);
$connection->disconnect();
}
logMessage('User lookup failed for: ' . $data['username']);
}
} catch (\LdapRecord\Auth\BindException $e) {
$error = $e->getDetailedError();
logMessage($error->getErrorMessage());
//echo $error->getErrorCode();
//echo $error->getErrorMessage();
//echo $error->getDiagnosticMessage();
}
}
return denyRequest();
}
function createResponseObject($connectionName, $username, $groups = []) {
global $home_directories,
$virtual_folders,
$default_output_object,
$connection_output_objects,
$user_output_objects,
$allowed_groups,
$auto_groups_mode,
$auto_groups_mode_virtual_folder_template,
$allowed_group_prefixes;
$userHomeDirectory = str_replace('#USERNAME#', $username, $home_directories[$connectionName]);
$output = $default_output_object;
// Connection-specific output objects override the default one:
if (isset($connection_output_objects[$connectionName])) {
logMessage('Using connection-specific output object override.');
$output = $connection_output_objects[$connectionName];
}
// Username-specific output objects override the default and connection-specific ones:
if (isset($user_output_objects[$username])) {
logMessage('Using username-specific output object override.');
$output = $user_output_objects[$username];
}
$output['username'] = $username;
$output['home_dir'] = $userHomeDirectory;
// Allow for username-specific folders in Remote SFTP Proxy:
if (isset($output['filesystem']['sftpconfig'])) {
logMessage('Reviewing Remote SFTP Config for user to see if username replacement is needed');
// Home Directory doesn't seem needed when using Remote SFTP Proxy option:
$output['home_dir'] = '';
$output['filesystem']['sftpconfig']['endpoint'] = str_replace('#USERNAME#', $username, $output['filesystem']['sftpconfig']['endpoint']);
$output['filesystem']['sftpconfig']['username'] = str_replace('#USERNAME#', $username, $output['filesystem']['sftpconfig']['username']);
if ($output['filesystem']['sftpconfig']['password']['status'] === 'Plain') {
if (strpos($output['filesystem']['sftpconfig']['password']['payload'], '#PASSWORD#') === 0) {
logMessage('Retrieving User Password from Request for Dynamic Replacement');
$data = getData();
$password = $data['password'];
unset($data);
logMessage('Retrieved User Password from Request for Dynamic Replacement');
$output['filesystem']['sftpconfig']['password']['payload'] = str_replace('#PASSWORD#', $password, $output['filesystem']['sftpconfig']['password']['payload']);
}
}
$output['filesystem']['sftpconfig']['password']['additional_data'] = str_replace('#USERNAME#', $username, $output['filesystem']['sftpconfig']['password']['additional_data']);
$output['filesystem']['sftpconfig']['prefix'] = str_replace('#USERNAME#', $username, $output['filesystem']['sftpconfig']['prefix']);
}
if (isset($virtual_folders[$connectionName])) {
$output['virtual_folders'] = $virtual_folders[$connectionName];
foreach ($output['virtual_folders'] as &$virtual_folder) {
$virtual_folder['name'] = str_replace('#USERNAME#', $username, $virtual_folder['name']);
$virtual_folder['mapped_path'] = str_replace('#USERNAME#', $username, $virtual_folder['mapped_path']);
}
}
// Support for automatically creating virtual folders for allowed groups the user may be a member of:
if (!empty($groups)) {
if ($auto_groups_mode) {
foreach($groups as $group) {
$allowed = true;
if (!empty($allowed_group_prefixes)) {
$allowed = false;
foreach($allowed_group_prefixes as $allowed_group_prefix) {
if (strpos($group, $allowed_group_prefix) === 0) {
$allowed = true;
$group = str_replace($allowed_group_prefix, '', $group);
}
}
}
if ($allowed) {
if (isset($auto_groups_mode_virtual_folder_template)) {
foreach($auto_groups_mode_virtual_folder_template as $virtual_group_folder) {
$virtual_group_folder['name'] = str_replace('#GROUP#', $group, $virtual_group_folder['name']);
$virtual_group_folder['mapped_path'] = str_replace('#GROUP#', $group, $virtual_group_folder['mapped_path']);
$virtual_group_folder['virtual_path'] = str_replace('#GROUP#', $group, $virtual_group_folder['virtual_path']);
$output['virtual_folders'][] = $virtual_group_folder;
// Defaulting to open permissions on the virtual group folder:
$output['permissions'][$virtual_group_folder['virtual_path']] = ["*"];
}
}
}
}
} else {
if (!empty($allowed_groups)) {
foreach($groups as $group) {
if (isset($allowed_groups[$group])) {
foreach($allowed_groups[$group] as $virtual_group_folder) {
$virtual_group_folder['name'] = str_replace('#GROUP#', $group, $virtual_group_folder['name']);
$virtual_group_folder['mapped_path'] = str_replace('#GROUP#', $group, $virtual_group_folder['mapped_path']);
$virtual_group_folder['virtual_path'] = str_replace('#GROUP#', $group, $virtual_group_folder['virtual_path']);
$output['virtual_folders'][] = $virtual_group_folder;
// Defaulting to open permissions on the virtual group folder:
$output['permissions'][$virtual_group_folder['virtual_path']] = ["*"];
}
}
}
}
}
}
return $output;
}
function getData($data) {
if (defined('_SFTPGO_DEBUG') && _SFTPGO_DEBUG === true) {
global $debug_object;
logMessage('Using $debug_object from configuration.php (authentication may fail if this object does not have correct credentials at the moment.)');
$data = $debug_object;
}
if (is_string($data)) {
$data = json_decode($data, true);
}
return $data;
}
function createResponse($output) {
logMessage('Authentication Successful');
return new Response(Status::OK, [
"content-type" => "application/json",
], json_encode($output)
);
}
function denyRequest() {
logMessage('Authentication Failed');
return new Response(Status::INTERNAL_SERVER_ERROR);
}
function canConnectToDirectories() {
try {
global $connections;
foreach($connections as $connectionName => $connection) {
$connection->connect();
echo "Can connect to: " . $connectionName . '<br />';
}
} catch (\LdapRecord\Auth\BindException $e) {
$error = $e->getDetailedError();
echo "Can't connect to: " . $connectionName . '<br />';
echo $error->getErrorCode() . '<br />';
echo $error->getErrorMessage() . '<br />';
echo $error->getDiagnosticMessage() . '<br />';
}
}
function homeDirectoryEntriesExist() {
global $connections, $home_directories;
foreach($connections as $connectionName => $connection) {
if (isset($home_directories[$connectionName])) {
echo "Home Directory Entry Exists for: " . $connectionName . '<br />';
} else {
echo "Missing Home Directory Entry for: " . $connectionName . '<br />';
}
}
}
function getUserGroups($user) {
$groups = array();
if (isset($user['memberof'])) {
if (isset($user['memberof']['count'])) {
unset($user['memberof']['count']);
}
foreach($user['memberof'] as $group) {
$group = str_replace('CN=', '', $group);
$endGroupName = strpos($group, ',OU');
$group = substr($group, 0, $endGroupName);
// Perform uniformity transformations:
$group = strtolower($group);
$group = str_replace('#', '', $group);
$group = str_replace('(', '', $group);
$group = str_replace(')', '', $group);
$group = str_replace(' ', '-', $group);
$group = str_replace('&', 'and', $group);
$group = preg_replace('/[^a-zA-Z0-9\-\._]/','', $group);
if (!empty($group)) {
$groups[] = $group;
}
}
}
return $groups;
}
function logMessage($message, $extra = []) {
if (defined('_SFTPGO_LOG') && _SFTPGO_LOG === true) {
global $log;
$log->info($message, $extra);
}
}