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