-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathUnityLDAP.php
More file actions
448 lines (402 loc) · 14.3 KB
/
UnityLDAP.php
File metadata and controls
448 lines (402 loc) · 14.3 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
<?php
namespace UnityWebPortal\lib;
use UnityWebPortal\lib\exceptions\EntryNotFoundException;
use PHPOpenLDAPer\LDAPConn;
use PHPOpenLDAPer\LDAPEntry;
/**
* An LDAP connection class which extends LDAPConn tailored for the Unity Cluster
*/
class UnityLDAP extends LDAPConn
{
private const string RDN = "cn"; // The defauls RDN for LDAP entries is set to "common name"
public const array POSIX_ACCOUNT_CLASS = [
"inetorgperson",
"posixAccount",
"top",
"ldapPublicKey",
];
public const array POSIX_GROUP_CLASS = ["posixGroup", "top"];
private string $custom_mappings_path =
__DIR__ . "/../../" . CONFIG["ldap"]["custom_user_mappings_dir"];
private string $def_user_shell = CONFIG["ldap"]["def_user_shell"];
private int $offset_UIDGID = CONFIG["ldap"]["offset_UIDGID"];
private int $offset_PIGID = CONFIG["ldap"]["offset_PIGID"];
private int $offset_ORGGID = CONFIG["ldap"]["offset_ORGGID"];
// Instance vars for various ldapEntry objects
private LDAPEntry $baseOU;
private LDAPEntry $userOU;
private LDAPEntry $groupOU;
private LDAPEntry $pi_groupOU;
private LDAPEntry $org_groupOU;
private LDAPEntry $adminGroup;
private LDAPEntry $qualifiedUserGroup;
public function __construct()
{
parent::__construct(CONFIG["ldap"]["uri"], CONFIG["ldap"]["user"], CONFIG["ldap"]["pass"]);
$this->baseOU = $this->getEntry(CONFIG["ldap"]["basedn"]);
$this->userOU = $this->getEntry(CONFIG["ldap"]["user_ou"]);
$this->groupOU = $this->getEntry(CONFIG["ldap"]["group_ou"]);
$this->pi_groupOU = $this->getEntry(CONFIG["ldap"]["pigroup_ou"]);
$this->org_groupOU = $this->getEntry(CONFIG["ldap"]["orggroup_ou"]);
$this->adminGroup = $this->getEntry(CONFIG["ldap"]["admin_group"]);
$this->qualifiedUserGroup = $this->getEntry(CONFIG["ldap"]["qualified_user_group"]);
}
public function getUserOU(): LDAPEntry
{
return $this->userOU;
}
public function getGroupOU(): LDAPEntry
{
return $this->groupOU;
}
public function getPIGroupOU(): LDAPEntry
{
return $this->pi_groupOU;
}
public function getOrgGroupOU(): LDAPEntry
{
return $this->org_groupOU;
}
public function getAdminGroup(): LDAPEntry
{
return $this->adminGroup;
}
public function getQualifiedUserGroup(): LDAPEntry
{
return $this->qualifiedUserGroup;
}
public function getDefUserShell(): string
{
return $this->def_user_shell;
}
public function getNextUIDGIDNumber(string $uid): int
{
$IDNumsInUse = array_merge($this->getAllUIDNumbersInUse(), $this->getAllGIDNumbersInUse());
$customIDMappings = $this->getCustomIDMappings();
$customMappedID = $customIDMappings[$uid] ?? null;
if (!is_null($customMappedID) && !in_array($customMappedID, $IDNumsInUse)) {
return $customMappedID;
}
if (!is_null($customMappedID) && in_array($customMappedID, $IDNumsInUse)) {
UnityHTTPD::errorLog(
"warning",
"user '$uid' has a custom mapped IDNumber $customMappedID but it's already in use!",
);
}
return $this->getNextIDNumber(
$this->offset_UIDGID,
array_merge($IDNumsInUse, array_values($this->getCustomIDMappings())),
);
}
public function getNextPIGIDNumber(): int
{
return $this->getNextIDNumber(
$this->offset_PIGID,
array_merge($this->getAllGIDNumbersInUse(), array_values($this->getCustomIDMappings())),
);
}
public function getNextOrgGIDNumber(): int
{
return $this->getNextIDNumber(
$this->offset_ORGGID,
array_merge($this->getAllGIDNumbersInUse(), array_values($this->getCustomIDMappings())),
);
}
private function isIDNumberForbidden($id): bool
{
// 0-99 are probably going to be used for local system accounts instead of LDAP accounts
// 100-999, 60000-64999 are reserved for debian packages
return $id <= 999 || ($id >= 60000 && $id <= 64999);
}
private function getNextIDNumber($start, $IDsToSkip): int
{
$new_id = $start;
while ($this->isIDNumberForbidden($new_id) || in_array($new_id, $IDsToSkip)) {
$new_id++;
}
return $new_id;
}
private function getCustomIDMappings(): array
{
$output = [];
$dir = new \DirectoryIterator($this->custom_mappings_path);
foreach ($dir as $fileinfo) {
$filename = $fileinfo->getFilename();
if ($fileinfo->isDot() || $filename == "README.md") {
continue;
}
if ($fileinfo->getExtension() == "csv") {
$handle = fopen($fileinfo->getPathname(), "r");
while (($row = fgetcsv($handle, null, ",")) !== false) {
array_push($output, $row);
}
} else {
UnityHTTPD::errorLog(
"warning",
"custom ID mapping file '$filename' ignored, extension != .csv",
);
}
}
$output_map = [];
foreach ($output as [$uid, $uidNumber_str]) {
$output_map[$uid] = intval($uidNumber_str);
}
return $output_map;
}
private function getAllUIDNumbersInUse(): array
{
// use baseOU for awareness of externally managed entries
return array_map(
fn($x) => $x["uidnumber"][0],
$this->baseOU->getChildrenArrayStrict(
["uidNumber"],
true,
"(objectClass=posixAccount)",
),
);
}
private function getAllGIDNumbersInUse(): array
{
// use baseOU for awareness of externally managed entries
return array_map(
fn($x) => $x["gidnumber"][0],
$this->baseOU->getChildrenArrayStrict(["gidNumber"], true, "(objectClass=posixGroup)"),
);
}
public function getQualifiedUsersUIDs(): array
{
// should not use $user_ou->getChildren or $base_ou->getChildren(objectClass=posixAccount)
// qualified users might be outside user ou, and not all users in LDAP tree are qualified users
return $this->qualifiedUserGroup->getAttribute("memberuid");
}
public function getQualifiedUsers($UnitySQL, $UnityMailer, $UnityWebhook): array
{
$out = [];
$qualifiedUsers = $this->getQualifiedUsersUIDs();
sort($qualifiedUsers);
foreach ($qualifiedUsers as $user) {
$params = [$user, $this, $UnitySQL, $UnityMailer, $UnityWebhook];
array_push($out, new UnityUser(...$params));
}
return $out;
}
public function getQualifiedUsersAttributes(
array $attributes,
array $default_values = [],
): array {
$include_uids = $this->getQualifiedUsersUIDs();
$user_attributes = $this->baseOU->getChildrenArrayStrict(
$attributes,
true, // recursive
"(objectClass=posixAccount)",
$default_values,
);
foreach ($user_attributes as $i => $attributes) {
if (!in_array($attributes["uid"][0], $include_uids)) {
unset($user_attributes[$i]);
}
}
return array_values($user_attributes); // reindex
}
public function getAllPIGroups(
UnitySQL $UnitySQL,
UnityMailer $UnityMailer,
UnityWebhook $UnityWebhook,
) {
$out = [];
$pi_groups = $this->pi_groupOU->getChildren(true);
foreach ($pi_groups as $pi_group) {
array_push(
$out,
new UnityGroup(
$pi_group->getAttribute("cn")[0],
$this,
$UnitySQL,
$UnityMailer,
$UnityWebhook,
),
);
}
return $out;
}
public function getAllPIGroupsAttributes(array $attributes, array $default_values = []): array
{
return $this->pi_groupOU->getChildrenArrayStrict(
$attributes,
false, // non-recursive
"objectClass=posixGroup",
$default_values,
);
}
public function getPIGroupGIDsWithMemberUID(string $uid): array
{
return array_map(
fn($x) => $x["cn"][0],
$this->pi_groupOU->getChildrenArrayStrict(
["cn"],
false,
"(memberuid=" . ldap_escape($uid, LDAP_ESCAPE_FILTER) . ")",
),
);
}
public function getAllPIGroupOwnerAttributes(
array $attributes,
array $default_values = [],
): array {
// get the PI groups, filter for just the GIDs, then map the GIDs to owner UIDs
$owner_uids = array_map(
fn($x) => UnityGroup::GID2OwnerUID($x),
array_map(fn($x) => $x["cn"][0], $this->pi_groupOU->getChildrenArrayStrict(["cn"])),
);
$owner_attributes = $this->getQualifiedUsersAttributes($attributes, $default_values);
foreach ($owner_attributes as $i => $attributes) {
if (!in_array($attributes["uid"][0], $owner_uids)) {
unset($owner_attributes[$i]);
}
}
$owner_attributes = array_values($owner_attributes); // reindex
$owners_not_found = array_diff(
$owner_uids,
array_map(fn($x) => $x["uid"][0], $owner_attributes),
);
if (count($owners_not_found) > 0) {
UnityHTTPD::errorLog(
"warning",
"PI group owners not found: " . \jsonEncode($owners_not_found) . "\n",
);
}
return $owner_attributes;
}
/**
* Returns an associative array where keys are UIDs and values are arrays of PI GIDs
*/
public function getQualifiedUID2PIGIDs(): array
{
// initialize output so each UID is a key with an empty array as its value
$uids = $this->getQualifiedUsersUIDs();
$uid2pigids = array_combine($uids, array_fill(0, count($uids), []));
// for each PI group, append that GID to the member list for each of its member UIDs
foreach (
$this->getAllPIGroupsAttributes(
["cn", "memberuid"],
default_values: ["memberuid" => []],
)
as $array
) {
$gid = $array["cn"][0];
foreach ($array["memberuid"] as $uid) {
if (array_key_exists($uid, $uid2pigids)) {
array_push($uid2pigids[$uid], $gid);
} else {
UnityHTTPD::errorLog(
"warning",
"user '$uid' is a member of a PI group but is not a qualified user!",
);
}
}
}
return $uid2pigids;
}
public function getAllOrgGroups($UnitySQL, $UnityMailer, $UnityWebhook): array
{
$out = [];
$org_groups = $this->org_groupOU->getChildren(true);
foreach ($org_groups as $org_group) {
array_push(
$out,
new UnityOrg(
$org_group->getAttribute("cn")[0],
$this,
$UnitySQL,
$UnityMailer,
$UnityWebhook,
),
);
}
return $out;
}
public function getAllOrgGroupsAttributes(array $attributes, array $default_values = []): array
{
return $this->org_groupOU->getChildrenArrayStrict(
$attributes,
default_values: $default_values,
);
}
public function getUserDN(string $uid): string
{
$uid = ldap_escape($uid, "", LDAP_ESCAPE_DN);
return UnityLDAP::RDN . "=$uid," . CONFIG["ldap"]["user_ou"];
}
public function getUserGroupDN(string $gid): string
{
$gid = ldap_escape($gid, "", LDAP_ESCAPE_DN);
return UnityLDAP::RDN . "=$gid," . CONFIG["ldap"]["group_ou"];
}
public function getPIGroupDN(string $gid): string
{
$gid = ldap_escape($gid, "", LDAP_ESCAPE_DN);
return UnityLDAP::RDN . "=$gid," . CONFIG["ldap"]["pigroup_ou"];
}
public function getOrgGroupDN(string $gid): string
{
$gid = ldap_escape($gid, "", LDAP_ESCAPE_DN);
return UnityLDAP::RDN . "=$gid," . CONFIG["ldap"]["orggroup_ou"];
}
/**
* @throws \UnityWebPortal\lib\exceptions\EntryNotFoundException
*/
public function getUidFromEmail(string $email): LDAPEntry
{
$email = ldap_escape($email, "", LDAP_ESCAPE_FILTER);
$cn = $this->search("mail=$email", CONFIG["ldap"]["user_ou"], ["cn"]);
if ($cn && count($cn) == 1) {
return $cn[0];
}
throw new exceptions\EntryNotFoundException($email);
}
/**
* returns an array with each UID as an array key
* @throws \UnityWebPortal\lib\exceptions\EntryNotFoundException
*/
public function getUsersAttributes(
array $uids,
array $attributes,
array $default_values = [],
): array {
if (count($uids) === 0) {
return [];
}
$attributes = array_map("strtolower", $attributes);
if (in_array("uid", $attributes)) {
$asked_for_uid_attribute = true;
} else {
$asked_for_uid_attribute = false;
array_push($attributes, "uid");
}
$uids_escaped = array_map(fn($x) => ldap_escape($x, "", LDAP_ESCAPE_FILTER), $uids);
$filter =
"(&(objectClass=posixAccount)(|" .
implode("", array_map(fn($x) => "(uid=$x)", $uids_escaped)) .
"))";
$entries = $this->baseOU->getChildrenArrayStrict(
$attributes,
true,
$filter,
$default_values,
);
$output = [];
foreach ($entries as $entry) {
$uid = $entry["uid"][0];
if (!$asked_for_uid_attribute) {
unset($entry["uid"]);
}
$output[$uid] = $entry;
}
$uids_not_found = array_diff($uids, array_keys($output));
if (count($uids_not_found) > 0) {
throw new EntryNotFoundException(jsonEncode($uids_not_found));
}
ksort($output);
return $output;
}
}