]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
Merge branch 'BookStackApp:development' into development
[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                     $started = $this->ldap->startTls($ldapConnection);
251                     if (!$started) {
252                         throw new LdapException('Could not start TLS connection');
253                     }
254                 }
255
256                 return $ldapConnection;
257             } catch (LdapException $exception) {
258                 $lastException = $exception;
259             }
260         }
261
262         throw $lastException;
263     }
264
265     /**
266      * Parse environment variable with LDAP server and returns an array of recognized servers.
267      * If you need to use multiple addresses, separate them with a semicolon.
268      * Ex: 'ldap.example.com:8069;ldaps://ldap.example.com'
269      */
270     protected function parseEnvironmentServer(string $environmentServer): array
271     {
272         $explodedEnvironmentServer = explode(';', $environmentServer);
273         $result_servers = [];
274
275         foreach ($explodedEnvironmentServer as $serverString) {
276             $result_servers[] = $this->parseServerString($serverString);
277         }
278
279         return $result_servers;
280     }
281
282     /**
283      * Parse a LDAP server string and return the host and port for a connection.
284      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
285      */
286     protected function parseServerString(string $serverString): array
287     {
288         $serverNameParts = explode(':', $serverString);
289
290         // If we have a protocol just return the full string since PHP will ignore a separate port.
291         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
292             return ['host' => $serverString, 'port' => 389];
293         }
294
295         // Otherwise, extract the port out
296         $hostName = $serverNameParts[0];
297         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
298
299         return ['host' => $hostName, 'port' => $ldapPort];
300     }
301
302     /**
303      * Build a filter string by injecting common variables.
304      */
305     protected function buildFilter(string $filterString, array $attrs): string
306     {
307         $newAttrs = [];
308         foreach ($attrs as $key => $attrText) {
309             $newKey = '${' . $key . '}';
310             $newAttrs[$newKey] = $this->ldap->escape($attrText);
311         }
312
313         return strtr($filterString, $newAttrs);
314     }
315
316     /**
317      * Get the groups a user is a part of on ldap.
318      *
319      * @throws LdapException
320      * @throws JsonDebugException
321      */
322     public function getUserGroups(string $userName): array
323     {
324         $groupsAttr = $this->config['group_attribute'];
325         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
326
327         if ($user === null) {
328             return [];
329         }
330
331         $userGroups = $this->groupFilter($user);
332         $allGroups = $this->getGroupsRecursive($userGroups, []);
333
334         if ($this->config['dump_user_groups']) {
335             throw new JsonDebugException([
336                 'details_from_ldap'             => $user,
337                 'parsed_direct_user_groups'     => $userGroups,
338                 'parsed_recursive_user_groups'  => $allGroups,
339             ]);
340         }
341
342         return $allGroups;
343     }
344
345     /**
346      * Get the parent groups of an array of groups.
347      *
348      * @throws LdapException
349      */
350     private function getGroupsRecursive(array $groupsArray, array $checked): array
351     {
352         $groupsToAdd = [];
353         foreach ($groupsArray as $groupName) {
354             if (in_array($groupName, $checked)) {
355                 continue;
356             }
357
358             $parentGroups = $this->getGroupGroups($groupName);
359             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
360             $checked[] = $groupName;
361         }
362
363         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
364
365         if (empty($groupsToAdd)) {
366             return $groupsArray;
367         }
368
369         return $this->getGroupsRecursive($groupsArray, $checked);
370     }
371
372     /**
373      * Get the parent groups of a single group.
374      *
375      * @throws LdapException
376      */
377     private function getGroupGroups(string $groupName): array
378     {
379         $ldapConnection = $this->getConnection();
380         $this->bindSystemUser($ldapConnection);
381
382         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
383         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
384
385         $baseDn = $this->config['base_dn'];
386         $groupsAttr = strtolower($this->config['group_attribute']);
387
388         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
389         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
390         if ($groups['count'] === 0) {
391             return [];
392         }
393
394         return $this->groupFilter($groups[0]);
395     }
396
397     /**
398      * Filter out LDAP CN and DN language in a ldap search return.
399      * Gets the base CN (common name) of the string.
400      */
401     protected function groupFilter(array $userGroupSearchResponse): array
402     {
403         $groupsAttr = strtolower($this->config['group_attribute']);
404         $ldapGroups = [];
405         $count = 0;
406
407         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
408             $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
409         }
410
411         for ($i = 0; $i < $count; $i++) {
412             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
413             if (!in_array($dnComponents[0], $ldapGroups)) {
414                 $ldapGroups[] = $dnComponents[0];
415             }
416         }
417
418         return $ldapGroups;
419     }
420
421     /**
422      * Sync the LDAP groups to the user roles for the current user.
423      *
424      * @throws LdapException
425      * @throws JsonDebugException
426      */
427     public function syncGroups(User $user, string $username)
428     {
429         $userLdapGroups = $this->getUserGroups($username);
430         $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
431     }
432
433     /**
434      * Save and attach an avatar image, if found in the ldap details, and attach
435      * to the given user model.
436      */
437     public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
438     {
439         if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
440             return;
441         }
442
443         try {
444             $imageData = $ldapUserDetails['avatar'];
445             $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
446         } catch (\Exception $exception) {
447             Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");
448         }
449     }
450 }