]> BookStack Code Mirror - bookstack/blob - app/Access/LdapService.php
Played around with a new app structure
[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     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->parseServerString($this->config['server']);
220         $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
221
222         if ($ldapConnection === false) {
223             throw new LdapException(trans('errors.ldap_cannot_connect'));
224         }
225
226         // Set any required options
227         if ($this->config['version']) {
228             $this->ldap->setVersion($ldapConnection, $this->config['version']);
229         }
230
231         // Start and verify TLS if it's enabled
232         if ($this->config['start_tls']) {
233             $started = $this->ldap->startTls($ldapConnection);
234             if (!$started) {
235                 throw new LdapException('Could not start TLS connection');
236             }
237         }
238
239         $this->ldapConnection = $ldapConnection;
240
241         return $this->ldapConnection;
242     }
243
244     /**
245      * Parse a LDAP server string and return the host and port for a connection.
246      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
247      */
248     protected function parseServerString(string $serverString): array
249     {
250         $serverNameParts = explode(':', $serverString);
251
252         // If we have a protocol just return the full string since PHP will ignore a separate port.
253         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
254             return ['host' => $serverString, 'port' => 389];
255         }
256
257         // Otherwise, extract the port out
258         $hostName = $serverNameParts[0];
259         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
260
261         return ['host' => $hostName, 'port' => $ldapPort];
262     }
263
264     /**
265      * Build a filter string by injecting common variables.
266      */
267     protected function buildFilter(string $filterString, array $attrs): string
268     {
269         $newAttrs = [];
270         foreach ($attrs as $key => $attrText) {
271             $newKey = '${' . $key . '}';
272             $newAttrs[$newKey] = $this->ldap->escape($attrText);
273         }
274
275         return strtr($filterString, $newAttrs);
276     }
277
278     /**
279      * Get the groups a user is a part of on ldap.
280      *
281      * @throws LdapException
282      * @throws JsonDebugException
283      */
284     public function getUserGroups(string $userName): array
285     {
286         $groupsAttr = $this->config['group_attribute'];
287         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
288
289         if ($user === null) {
290             return [];
291         }
292
293         $userGroups = $this->groupFilter($user);
294         $allGroups = $this->getGroupsRecursive($userGroups, []);
295
296         if ($this->config['dump_user_groups']) {
297             throw new JsonDebugException([
298                 'details_from_ldap'             => $user,
299                 'parsed_direct_user_groups'     => $userGroups,
300                 'parsed_recursive_user_groups'  => $allGroups,
301             ]);
302         }
303
304         return $allGroups;
305     }
306
307     /**
308      * Get the parent groups of an array of groups.
309      *
310      * @throws LdapException
311      */
312     private function getGroupsRecursive(array $groupsArray, array $checked): array
313     {
314         $groupsToAdd = [];
315         foreach ($groupsArray as $groupName) {
316             if (in_array($groupName, $checked)) {
317                 continue;
318             }
319
320             $parentGroups = $this->getGroupGroups($groupName);
321             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
322             $checked[] = $groupName;
323         }
324
325         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
326
327         if (empty($groupsToAdd)) {
328             return $groupsArray;
329         }
330
331         return $this->getGroupsRecursive($groupsArray, $checked);
332     }
333
334     /**
335      * Get the parent groups of a single group.
336      *
337      * @throws LdapException
338      */
339     private function getGroupGroups(string $groupName): array
340     {
341         $ldapConnection = $this->getConnection();
342         $this->bindSystemUser($ldapConnection);
343
344         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
345         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
346
347         $baseDn = $this->config['base_dn'];
348         $groupsAttr = strtolower($this->config['group_attribute']);
349
350         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
351         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
352         if ($groups['count'] === 0) {
353             return [];
354         }
355
356         return $this->groupFilter($groups[0]);
357     }
358
359     /**
360      * Filter out LDAP CN and DN language in a ldap search return.
361      * Gets the base CN (common name) of the string.
362      */
363     protected function groupFilter(array $userGroupSearchResponse): array
364     {
365         $groupsAttr = strtolower($this->config['group_attribute']);
366         $ldapGroups = [];
367         $count = 0;
368
369         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
370             $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
371         }
372
373         for ($i = 0; $i < $count; $i++) {
374             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
375             if (!in_array($dnComponents[0], $ldapGroups)) {
376                 $ldapGroups[] = $dnComponents[0];
377             }
378         }
379
380         return $ldapGroups;
381     }
382
383     /**
384      * Sync the LDAP groups to the user roles for the current user.
385      *
386      * @throws LdapException
387      * @throws JsonDebugException
388      */
389     public function syncGroups(User $user, string $username)
390     {
391         $userLdapGroups = $this->getUserGroups($username);
392         $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
393     }
394
395     /**
396      * Save and attach an avatar image, if found in the ldap details, and attach
397      * to the given user model.
398      */
399     public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
400     {
401         if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
402             return;
403         }
404
405         try {
406             $imageData = $ldapUserDetails['avatar'];
407             $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
408         } catch (\Exception $exception) {
409             Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");
410         }
411     }
412 }