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