]> BookStack Code Mirror - bookstack/blob - app/Access/LdapService.php
Opensearch: Fixed XML declaration when php short tags enabled
[bookstack] / app / Access / LdapService.php
1 <?php
2
3 namespace BookStack\Access;
4
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\LdapException;
7 use BookStack\Uploads\UserAvatars;
8 use BookStack\Users\Models\User;
9 use ErrorException;
10 use Illuminate\Support\Facades\Log;
11
12 /**
13  * Class LdapService
14  * Handles any app-specific LDAP tasks.
15  */
16 class LdapService
17 {
18     /**
19      * @var resource|\LDAP\Connection
20      */
21     protected $ldapConnection;
22
23     protected array $config;
24     protected bool $enabled;
25
26     public function __construct(
27         protected Ldap $ldap,
28         protected UserAvatars $userAvatars,
29         protected GroupSyncService $groupSyncService
30     ) {
31         $this->config = config('services.ldap');
32         $this->enabled = config('auth.method') === 'ldap';
33     }
34
35     /**
36      * Check if groups should be synced.
37      */
38     public function shouldSyncGroups(): bool
39     {
40         return $this->enabled && $this->config['user_to_groups'] !== false;
41     }
42
43     /**
44      * Search for attributes for a specific user on the ldap.
45      *
46      * @throws LdapException
47      */
48     private function getUserWithAttributes(string $userName, array $attributes): ?array
49     {
50         $ldapConnection = $this->getConnection();
51         $this->bindSystemUser($ldapConnection);
52
53         // Clean attributes
54         foreach ($attributes as $index => $attribute) {
55             if (str_starts_with($attribute, 'BIN;')) {
56                 $attributes[$index] = substr($attribute, strlen('BIN;'));
57             }
58         }
59
60         // Find user
61         $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
62         $baseDn = $this->config['base_dn'];
63
64         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
65         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
66         $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
67         if ($users['count'] === 0) {
68             return null;
69         }
70
71         return $users[0];
72     }
73
74     /**
75      * Build the user display name from the (potentially multiple) attributes defined by the configuration.
76      */
77     protected function getUserDisplayName(array $userDetails, array $displayNameAttrs, string $defaultValue): string
78     {
79         $displayNameParts = [];
80         foreach ($displayNameAttrs as $dnAttr) {
81             $dnComponent = $this->getUserResponseProperty($userDetails, $dnAttr, null);
82             if ($dnComponent) {
83                 $displayNameParts[] = $dnComponent;
84             }
85         }
86
87         if (empty($displayNameParts)) {
88             return $defaultValue;
89         }
90
91         return implode(' ', $displayNameParts);
92     }
93
94     /**
95      * Get the details of a user from LDAP using the given username.
96      * User found via configurable user filter.
97      *
98      * @throws LdapException|JsonDebugException
99      */
100     public function getUserDetails(string $userName): ?array
101     {
102         $idAttr = $this->config['id_attribute'];
103         $emailAttr = $this->config['email_attribute'];
104         $displayNameAttrs = explode('|', $this->config['display_name_attribute']);
105         $thumbnailAttr = $this->config['thumbnail_attribute'];
106
107         $user = $this->getUserWithAttributes($userName, array_filter([
108             'cn', 'dn', $idAttr, $emailAttr, ...$displayNameAttrs, $thumbnailAttr,
109         ]));
110
111         if (is_null($user)) {
112             return null;
113         }
114
115         $nameDefault = $this->getUserResponseProperty($user, 'cn', null);
116         if (is_null($nameDefault)) {
117             $nameDefault = ldap_explode_dn($user['dn'], 1)[0] ?? $user['dn'];
118         }
119
120         $formatted = [
121             'uid'   => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
122             'name'  => $this->getUserDisplayName($user, $displayNameAttrs, $nameDefault),
123             'dn'    => $user['dn'],
124             'email' => $this->getUserResponseProperty($user, $emailAttr, null),
125             'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
126         ];
127
128         if ($this->config['dump_user_details']) {
129             throw new JsonDebugException([
130                 'details_from_ldap'        => $user,
131                 'details_bookstack_parsed' => $formatted,
132             ]);
133         }
134
135         return $formatted;
136     }
137
138     /**
139      * Get a property from an LDAP user response fetch.
140      * Handles properties potentially being part of an array.
141      * If the given key is prefixed with 'BIN;', that indicator will be stripped
142      * from the key and any fetched values will be converted from binary to hex.
143      */
144     protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
145     {
146         $isBinary = str_starts_with($propertyKey, 'BIN;');
147         $propertyKey = strtolower($propertyKey);
148         $value = $defaultValue;
149
150         if ($isBinary) {
151             $propertyKey = substr($propertyKey, strlen('BIN;'));
152         }
153
154         if (isset($userDetails[$propertyKey])) {
155             $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
156             if ($isBinary) {
157                 $value = bin2hex($value);
158             }
159         }
160
161         return $value;
162     }
163
164     /**
165      * Check if the given credentials are valid for the given user.
166      *
167      * @throws LdapException
168      */
169     public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
170     {
171         if (is_null($ldapUserDetails)) {
172             return false;
173         }
174
175         $ldapConnection = $this->getConnection();
176
177         try {
178             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
179         } catch (ErrorException $e) {
180             $ldapBind = false;
181         }
182
183         return $ldapBind;
184     }
185
186     /**
187      * Bind the system user to the LDAP connection using the given credentials
188      * otherwise anonymous access is attempted.
189      *
190      * @param resource|\LDAP\Connection $connection
191      *
192      * @throws LdapException
193      */
194     protected function bindSystemUser($connection): void
195     {
196         $ldapDn = $this->config['dn'];
197         $ldapPass = $this->config['pass'];
198
199         $isAnonymous = ($ldapDn === false || $ldapPass === false);
200         if ($isAnonymous) {
201             $ldapBind = $this->ldap->bind($connection);
202         } else {
203             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
204         }
205
206         if (!$ldapBind) {
207             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
208         }
209     }
210
211     /**
212      * Get the connection to the LDAP server.
213      * Creates a new connection if one does not exist.
214      *
215      * @throws LdapException
216      *
217      * @return resource|\LDAP\Connection
218      */
219     protected function getConnection()
220     {
221         if ($this->ldapConnection !== null) {
222             return $this->ldapConnection;
223         }
224
225         // Check LDAP extension in installed
226         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
227             throw new LdapException(trans('errors.ldap_extension_not_installed'));
228         }
229
230         // Disable certificate verification.
231         // This option works globally and must be set before a connection is created.
232         if ($this->config['tls_insecure']) {
233             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
234         }
235
236         // Configure any user-provided CA cert files for LDAP.
237         // This option works globally and must be set before a connection is created.
238         if ($this->config['tls_ca_cert']) {
239             $this->configureTlsCaCerts($this->config['tls_ca_cert']);
240         }
241
242         $ldapHost = $this->parseServerString($this->config['server']);
243         $ldapConnection = $this->ldap->connect($ldapHost);
244
245         if ($ldapConnection === false) {
246             throw new LdapException(trans('errors.ldap_cannot_connect'));
247         }
248
249         // Set any required options
250         if ($this->config['version']) {
251             $this->ldap->setVersion($ldapConnection, $this->config['version']);
252         }
253
254         // Start and verify TLS if it's enabled
255         if ($this->config['start_tls']) {
256             try {
257                 $started = $this->ldap->startTls($ldapConnection);
258             } catch (\Exception $exception) {
259                 $error = $exception->getMessage() . ' :: ' . ldap_error($ldapConnection);
260                 ldap_get_option($ldapConnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $detail);
261                 Log::info("LDAP STARTTLS failure: {$error} {$detail}");
262                 throw new LdapException('Could not start TLS connection. Further details in the application log.');
263             }
264             if (!$started) {
265                 throw new LdapException('Could not start TLS connection');
266             }
267         }
268
269         $this->ldapConnection = $ldapConnection;
270
271         return $this->ldapConnection;
272     }
273
274     /**
275      * Configure TLS CA certs globally for ldap use.
276      * This will detect if the given path is a directory or file, and set the relevant
277      * LDAP TLS options appropriately otherwise throw an exception if no file/folder found.
278      *
279      * Note: When using a folder, certificates are expected to be correctly named by hash
280      * which can be done via the c_rehash utility.
281      *
282      * @throws LdapException
283      */
284     protected function configureTlsCaCerts(string $caCertPath): void
285     {
286         $errMessage = "Provided path [{$caCertPath}] for LDAP TLS CA certs could not be resolved to an existing location";
287         $path = realpath($caCertPath);
288         if ($path === false) {
289             throw new LdapException($errMessage);
290         }
291
292         if (is_dir($path)) {
293             $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTDIR, $path);
294         } else if (is_file($path)) {
295             $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTFILE, $path);
296         } else {
297             throw new LdapException($errMessage);
298         }
299     }
300
301     /**
302      * Parse an LDAP server string and return the host suitable for a connection.
303      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
304      */
305     protected function parseServerString(string $serverString): string
306     {
307         if (str_starts_with($serverString, 'ldaps://') || str_starts_with($serverString, 'ldap://')) {
308             return $serverString;
309         }
310
311         return "ldap://{$serverString}";
312     }
313
314     /**
315      * Build a filter string by injecting common variables.
316      * Both "${var}" and "{var}" style placeholders are supported.
317      * Dollar based are old format but supported for compatibility.
318      */
319     protected function buildFilter(string $filterString, array $attrs): string
320     {
321         $newAttrs = [];
322         foreach ($attrs as $key => $attrText) {
323             $escapedText = $this->ldap->escape($attrText);
324             $oldVarKey = '${' . $key . '}';
325             $newVarKey = '{' . $key . '}';
326             $newAttrs[$oldVarKey] = $escapedText;
327             $newAttrs[$newVarKey] = $escapedText;
328         }
329
330         return strtr($filterString, $newAttrs);
331     }
332
333     /**
334      * Get the groups a user is a part of on ldap.
335      *
336      * @throws LdapException
337      * @throws JsonDebugException
338      */
339     public function getUserGroups(string $userName): array
340     {
341         $groupsAttr = $this->config['group_attribute'];
342         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
343
344         if ($user === null) {
345             return [];
346         }
347
348         $userGroups = $this->extractGroupsFromSearchResponseEntry($user);
349         $allGroups = $this->getGroupsRecursive($userGroups, []);
350         $formattedGroups = $this->extractGroupNamesFromLdapGroupDns($allGroups);
351
352         if ($this->config['dump_user_groups']) {
353             throw new JsonDebugException([
354                 'details_from_ldap'            => $user,
355                 'parsed_direct_user_groups'    => $userGroups,
356                 'parsed_recursive_user_groups' => $allGroups,
357                 'parsed_resulting_group_names' => $formattedGroups,
358             ]);
359         }
360
361         return $formattedGroups;
362     }
363
364     protected function extractGroupNamesFromLdapGroupDns(array $groupDNs): array
365     {
366         $names = [];
367
368         foreach ($groupDNs as $groupDN) {
369             $exploded = $this->ldap->explodeDn($groupDN, 1);
370             if ($exploded !== false && count($exploded) > 0) {
371                 $names[] = $exploded[0];
372             }
373         }
374
375         return array_unique($names);
376     }
377
378     /**
379      * Build an array of all relevant groups DNs after recursively scanning
380      * across parents of the groups given.
381      *
382      * @throws LdapException
383      */
384     protected function getGroupsRecursive(array $groupDNs, array $checked): array
385     {
386         $groupsToAdd = [];
387         foreach ($groupDNs as $groupDN) {
388             if (in_array($groupDN, $checked)) {
389                 continue;
390             }
391
392             $parentGroups = $this->getParentsOfGroup($groupDN);
393             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
394             $checked[] = $groupDN;
395         }
396
397         $uniqueDNs = array_unique(array_merge($groupDNs, $groupsToAdd), SORT_REGULAR);
398
399         if (empty($groupsToAdd)) {
400             return $uniqueDNs;
401         }
402
403         return $this->getGroupsRecursive($uniqueDNs, $checked);
404     }
405
406     /**
407      * @throws LdapException
408      */
409     protected function getParentsOfGroup(string $groupDN): array
410     {
411         $groupsAttr = strtolower($this->config['group_attribute']);
412         $ldapConnection = $this->getConnection();
413         $this->bindSystemUser($ldapConnection);
414
415         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
416         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
417         $read = $this->ldap->read($ldapConnection, $groupDN, '(objectClass=*)', [$groupsAttr]);
418         $results = $this->ldap->getEntries($ldapConnection, $read);
419         if ($results['count'] === 0) {
420             return [];
421         }
422
423         return $this->extractGroupsFromSearchResponseEntry($results[0]);
424     }
425
426     /**
427      * Extract an array of group DN values from the given LDAP search response entry
428      */
429     protected function extractGroupsFromSearchResponseEntry(array $ldapEntry): array
430     {
431         $groupsAttr = strtolower($this->config['group_attribute']);
432         $groupDNs = [];
433         $count = 0;
434
435         if (isset($ldapEntry[$groupsAttr]['count'])) {
436             $count = (int) $ldapEntry[$groupsAttr]['count'];
437         }
438
439         for ($i = 0; $i < $count; $i++) {
440             $dn = $ldapEntry[$groupsAttr][$i];
441             if (!in_array($dn, $groupDNs)) {
442                 $groupDNs[] = $dn;
443             }
444         }
445
446         return $groupDNs;
447     }
448
449     /**
450      * Sync the LDAP groups to the user roles for the current user.
451      *
452      * @throws LdapException
453      * @throws JsonDebugException
454      */
455     public function syncGroups(User $user, string $username): void
456     {
457         $userLdapGroups = $this->getUserGroups($username);
458         $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
459     }
460
461     /**
462      * Save and attach an avatar image, if found in the ldap details, and attach
463      * to the given user model.
464      */
465     public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
466     {
467         if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
468             return;
469         }
470
471         try {
472             $imageData = $ldapUserDetails['avatar'];
473             $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
474         } catch (\Exception $exception) {
475             Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");
476         }
477     }
478 }