]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
Apply fixes from StyleCI
[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 extends ExternalAuthService
17 {
18     protected $ldap;
19     protected $ldapConnection;
20     protected $userAvatars;
21     protected $config;
22     protected $enabled;
23
24     /**
25      * LdapService constructor.
26      */
27     public function __construct(Ldap $ldap, UserAvatars $userAvatars)
28     {
29         $this->ldap = $ldap;
30         $this->userAvatars = $userAvatars;
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      * @return bool
39      */
40     public function shouldSyncGroups()
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         $userGroups = $this->getGroupsRecursive($userGroups, []);
289
290         return $userGroups;
291     }
292
293     /**
294      * Get the parent groups of an array of groups.
295      *
296      * @throws LdapException
297      */
298     private function getGroupsRecursive(array $groupsArray, array $checked): array
299     {
300         $groupsToAdd = [];
301         foreach ($groupsArray as $groupName) {
302             if (in_array($groupName, $checked)) {
303                 continue;
304             }
305
306             $parentGroups = $this->getGroupGroups($groupName);
307             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
308             $checked[] = $groupName;
309         }
310
311         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
312
313         if (empty($groupsToAdd)) {
314             return $groupsArray;
315         }
316
317         return $this->getGroupsRecursive($groupsArray, $checked);
318     }
319
320     /**
321      * Get the parent groups of a single group.
322      *
323      * @throws LdapException
324      */
325     private function getGroupGroups(string $groupName): array
326     {
327         $ldapConnection = $this->getConnection();
328         $this->bindSystemUser($ldapConnection);
329
330         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
331         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
332
333         $baseDn = $this->config['base_dn'];
334         $groupsAttr = strtolower($this->config['group_attribute']);
335
336         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
337         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
338         if ($groups['count'] === 0) {
339             return [];
340         }
341
342         return $this->groupFilter($groups[0]);
343     }
344
345     /**
346      * Filter out LDAP CN and DN language in a ldap search return.
347      * Gets the base CN (common name) of the string.
348      */
349     protected function groupFilter(array $userGroupSearchResponse): array
350     {
351         $groupsAttr = strtolower($this->config['group_attribute']);
352         $ldapGroups = [];
353         $count = 0;
354
355         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
356             $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
357         }
358
359         for ($i = 0; $i < $count; $i++) {
360             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
361             if (!in_array($dnComponents[0], $ldapGroups)) {
362                 $ldapGroups[] = $dnComponents[0];
363             }
364         }
365
366         return $ldapGroups;
367     }
368
369     /**
370      * Sync the LDAP groups to the user roles for the current user.
371      *
372      * @throws LdapException
373      */
374     public function syncGroups(User $user, string $username)
375     {
376         $userLdapGroups = $this->getUserGroups($username);
377         $this->syncWithGroups($user, $userLdapGroups);
378     }
379
380     /**
381      * Save and attach an avatar image, if found in the ldap details, and attach
382      * to the given user model.
383      */
384     public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
385     {
386         if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
387             return;
388         }
389
390         try {
391             $imageData = $ldapUserDetails['avatar'];
392             $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
393         } catch (\Exception $exception) {
394             Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");
395         }
396     }
397 }