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