]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
a45c07c2f8109323ece256234ed400d108ee4072
[bookstack] / app / Auth / Access / LdapService.php
1 <?php
2
3 namespace BookStack\Auth\Access;
4
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\JsonDebugException;
7 use BookStack\Exceptions\LdapException;
8 use BookStack\Uploads\UserAvatars;
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     protected Ldap $ldap;
19     protected GroupSyncService $groupSyncService;
20     protected UserAvatars $userAvatars;
21
22     /**
23      * @var resource
24      */
25     protected $ldapConnection;
26
27     protected array $config;
28     protected bool $enabled;
29
30     /**
31      * LdapService constructor.
32      */
33     public function __construct(Ldap $ldap, UserAvatars $userAvatars, GroupSyncService $groupSyncService)
34     {
35         $this->ldap = $ldap;
36         $this->userAvatars = $userAvatars;
37         $this->groupSyncService = $groupSyncService;
38         $this->config = config('services.ldap');
39         $this->enabled = config('auth.method') === 'ldap';
40     }
41
42     /**
43      * Check if groups should be synced.
44      */
45     public function shouldSyncGroups(): bool
46     {
47         return $this->enabled && $this->config['user_to_groups'] !== false;
48     }
49
50     /**
51      * Search for attributes for a specific user on the ldap.
52      *
53      * @throws LdapException
54      */
55     private function getUserWithAttributes(string $userName, array $attributes): ?array
56     {
57         $ldapConnection = $this->getConnection();
58         $this->bindSystemUser($ldapConnection);
59
60         // Clean attributes
61         foreach ($attributes as $index => $attribute) {
62             if (strpos($attribute, 'BIN;') === 0) {
63                 $attributes[$index] = substr($attribute, strlen('BIN;'));
64             }
65         }
66
67         // Find user
68         $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
69         $baseDn = $this->config['base_dn'];
70
71         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
72         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
73         $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
74         if ($users['count'] === 0) {
75             return null;
76         }
77
78         return $users[0];
79     }
80
81     /**
82      * Get the details of a user from LDAP using the given username.
83      * User found via configurable user filter.
84      *
85      * @throws LdapException
86      */
87     public function getUserDetails(string $userName): ?array
88     {
89         $idAttr = $this->config['id_attribute'];
90         $emailAttr = $this->config['email_attribute'];
91         $displayNameAttr = $this->config['display_name_attribute'];
92         $thumbnailAttr = $this->config['thumbnail_attribute'];
93
94         $user = $this->getUserWithAttributes($userName, array_filter([
95             'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
96         ]));
97
98         if (is_null($user)) {
99             return null;
100         }
101
102         $userCn = $this->getUserResponseProperty($user, 'cn', null);
103         $formatted = [
104             'uid'   => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
105             'name'  => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
106             'dn'    => $user['dn'],
107             'email' => $this->getUserResponseProperty($user, $emailAttr, null),
108             'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
109         ];
110
111         if ($this->config['dump_user_details']) {
112             throw new JsonDebugException([
113                 'details_from_ldap'        => $user,
114                 'details_bookstack_parsed' => $formatted,
115             ]);
116         }
117
118         return $formatted;
119     }
120
121     /**
122      * Get a property from an LDAP user response fetch.
123      * Handles properties potentially being part of an array.
124      * If the given key is prefixed with 'BIN;', that indicator will be stripped
125      * from the key and any fetched values will be converted from binary to hex.
126      */
127     protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
128     {
129         $isBinary = strpos($propertyKey, 'BIN;') === 0;
130         $propertyKey = strtolower($propertyKey);
131         $value = $defaultValue;
132
133         if ($isBinary) {
134             $propertyKey = substr($propertyKey, strlen('BIN;'));
135         }
136
137         if (isset($userDetails[$propertyKey])) {
138             $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
139             if ($isBinary) {
140                 $value = bin2hex($value);
141             }
142         }
143
144         return $value;
145     }
146
147     /**
148      * Check if the given credentials are valid for the given user.
149      *
150      * @throws LdapException
151      */
152     public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
153     {
154         if (is_null($ldapUserDetails)) {
155             return false;
156         }
157
158         $ldapConnection = $this->getConnection();
159
160         try {
161             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
162         } catch (ErrorException $e) {
163             $ldapBind = false;
164         }
165
166         return $ldapBind;
167     }
168
169     /**
170      * Bind the system user to the LDAP connection using the given credentials
171      * otherwise anonymous access is attempted.
172      *
173      * @param resource $connection
174      *
175      * @throws LdapException
176      */
177     protected function bindSystemUser($connection)
178     {
179         $ldapDn = $this->config['dn'];
180         $ldapPass = $this->config['pass'];
181
182         $isAnonymous = ($ldapDn === false || $ldapPass === false);
183         if ($isAnonymous) {
184             $ldapBind = $this->ldap->bind($connection);
185         } else {
186             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
187         }
188
189         if (!$ldapBind) {
190             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
191         }
192     }
193
194     /**
195      * Get the connection to the LDAP server.
196      * Creates a new connection if one does not exist.
197      *
198      * @throws LdapException
199      *
200      * @return resource
201      */
202     protected function getConnection()
203     {
204         if ($this->ldapConnection !== null) {
205             return $this->ldapConnection;
206         }
207
208         // Check LDAP extension in installed
209         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
210             throw new LdapException(trans('errors.ldap_extension_not_installed'));
211         }
212
213         // Disable certificate verification.
214         // This option works globally and must be set before a connection is created.
215         if ($this->config['tls_insecure']) {
216             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
217         }
218
219         $serverDetails = $this->parseEnvironmentServer($this->config['server']);
220         $this->ldapConnection = $this->prepareServerConnection($serverDetails);
221
222         return $this->ldapConnection;
223     }
224
225     /**
226      * Processes an array of received servers and returns the first working connection.
227      *
228      * @param  array  $serverDetails
229      * @return resource
230      * @throws LdapException
231      */
232     protected function prepareServerConnection(array $serverDetails)
233     {
234         $lastException = null;
235         foreach ($serverDetails as $server) {
236             try {
237                 $ldapConnection = $this->ldap->connect($server['host'], $server['port']);
238
239                 if (!$ldapConnection) {
240                     throw new LdapException(trans('errors.ldap_cannot_connect'));
241                 }
242
243                 // Set any required options
244                 if ($this->config['version']) {
245                     $this->ldap->setVersion($ldapConnection, $this->config['version']);
246                 }
247
248                 // Start and verify TLS if it's enabled
249                 if ($this->config['start_tls']) {
250                     try {
251                         $tlsStarted = $this->ldap->startTls($ldapConnection);
252                     } catch (ErrorException $exception) {
253                         $tlsStarted = false;
254                     }
255
256                     if (!$tlsStarted) {
257                         throw new LdapException('Could not start TLS connection');
258                     }
259                 }
260
261                 return $ldapConnection;
262             } catch (LdapException $exception) {
263                 $lastException = $exception;
264             }
265         }
266
267         throw $lastException;
268     }
269
270     /**
271      * Parse environment variable with LDAP server and returns an array of recognized servers.
272      * If you need to use multiple addresses, separate them with a semicolon.
273      * Ex: 'ldap.example.com:8069;ldaps://ldap.example.com'
274      */
275     protected function parseEnvironmentServer(string $environmentServer): array
276     {
277         $explodedEnvironmentServer = explode(';', $environmentServer);
278         $result_servers = [];
279
280         foreach ($explodedEnvironmentServer as $serverString) {
281             $result_servers[] = $this->parseServerString($serverString);
282         }
283
284         return $result_servers;
285     }
286
287     /**
288      * Parse a LDAP server string and return the host and port for a connection.
289      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
290      */
291     protected function parseServerString(string $serverString): array
292     {
293         $serverNameParts = explode(':', $serverString);
294
295         // If we have a protocol just return the full string since PHP will ignore a separate port.
296         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
297             return ['host' => $serverString, 'port' => 389];
298         }
299
300         // Otherwise, extract the port out
301         $hostName = $serverNameParts[0];
302         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
303
304         return ['host' => $hostName, 'port' => $ldapPort];
305     }
306
307     /**
308      * Build a filter string by injecting common variables.
309      */
310     protected function buildFilter(string $filterString, array $attrs): string
311     {
312         $newAttrs = [];
313         foreach ($attrs as $key => $attrText) {
314             $newKey = '${' . $key . '}';
315             $newAttrs[$newKey] = $this->ldap->escape($attrText);
316         }
317
318         return strtr($filterString, $newAttrs);
319     }
320
321     /**
322      * Get the groups a user is a part of on ldap.
323      *
324      * @throws LdapException
325      * @throws JsonDebugException
326      */
327     public function getUserGroups(string $userName): array
328     {
329         $groupsAttr = $this->config['group_attribute'];
330         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
331
332         if ($user === null) {
333             return [];
334         }
335
336         $userGroups = $this->groupFilter($user);
337         $allGroups = $this->getGroupsRecursive($userGroups, []);
338
339         if ($this->config['dump_user_groups']) {
340             throw new JsonDebugException([
341                 'details_from_ldap'             => $user,
342                 'parsed_direct_user_groups'     => $userGroups,
343                 'parsed_recursive_user_groups'  => $allGroups,
344             ]);
345         }
346
347         return $allGroups;
348     }
349
350     /**
351      * Get the parent groups of an array of groups.
352      *
353      * @throws LdapException
354      */
355     private function getGroupsRecursive(array $groupsArray, array $checked): array
356     {
357         $groupsToAdd = [];
358         foreach ($groupsArray as $groupName) {
359             if (in_array($groupName, $checked)) {
360                 continue;
361             }
362
363             $parentGroups = $this->getGroupGroups($groupName);
364             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
365             $checked[] = $groupName;
366         }
367
368         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
369
370         if (empty($groupsToAdd)) {
371             return $groupsArray;
372         }
373
374         return $this->getGroupsRecursive($groupsArray, $checked);
375     }
376
377     /**
378      * Get the parent groups of a single group.
379      *
380      * @throws LdapException
381      */
382     private function getGroupGroups(string $groupName): array
383     {
384         $ldapConnection = $this->getConnection();
385         $this->bindSystemUser($ldapConnection);
386
387         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
388         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
389
390         $baseDn = $this->config['base_dn'];
391         $groupsAttr = strtolower($this->config['group_attribute']);
392
393         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
394         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
395         if ($groups['count'] === 0) {
396             return [];
397         }
398
399         return $this->groupFilter($groups[0]);
400     }
401
402     /**
403      * Filter out LDAP CN and DN language in a ldap search return.
404      * Gets the base CN (common name) of the string.
405      */
406     protected function groupFilter(array $userGroupSearchResponse): array
407     {
408         $groupsAttr = strtolower($this->config['group_attribute']);
409         $ldapGroups = [];
410         $count = 0;
411
412         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
413             $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
414         }
415
416         for ($i = 0; $i < $count; $i++) {
417             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
418             if (!in_array($dnComponents[0], $ldapGroups)) {
419                 $ldapGroups[] = $dnComponents[0];
420             }
421         }
422
423         return $ldapGroups;
424     }
425
426     /**
427      * Sync the LDAP groups to the user roles for the current user.
428      *
429      * @throws LdapException
430      * @throws JsonDebugException
431      */
432     public function syncGroups(User $user, string $username)
433     {
434         $userLdapGroups = $this->getUserGroups($username);
435         $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
436     }
437
438     /**
439      * Save and attach an avatar image, if found in the ldap details, and attach
440      * to the given user model.
441      */
442     public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
443     {
444         if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
445             return;
446         }
447
448         try {
449             $imageData = $ldapUserDetails['avatar'];
450             $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
451         } catch (\Exception $exception) {
452             Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");
453         }
454     }
455 }