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