]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
Added locale and text direction to html templates
[bookstack] / app / Auth / Access / LdapService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\Access;
4 use BookStack\Auth\Role;
5 use BookStack\Auth\User;
6 use BookStack\Auth\UserRepo;
7 use BookStack\Exceptions\LdapException;
8 use Illuminate\Contracts\Auth\Authenticatable;
9 use Illuminate\Database\Eloquent\Builder;
10
11 /**
12  * Class LdapService
13  * Handles any app-specific LDAP tasks.
14  * @package BookStack\Services
15  */
16 class LdapService
17 {
18
19     protected $ldap;
20     protected $ldapConnection;
21     protected $config;
22     protected $userRepo;
23     protected $enabled;
24
25     /**
26      * LdapService constructor.
27      * @param Ldap $ldap
28      * @param \BookStack\Auth\UserRepo $userRepo
29      */
30     public function __construct(Access\Ldap $ldap, UserRepo $userRepo)
31     {
32         $this->ldap = $ldap;
33         $this->config = config('services.ldap');
34         $this->userRepo = $userRepo;
35         $this->enabled = config('auth.method') === 'ldap';
36     }
37
38     /**
39      * Check if groups should be synced.
40      * @return bool
41      */
42     public function shouldSyncGroups()
43     {
44         return $this->enabled && $this->config['user_to_groups'] !== false;
45     }
46
47     /**
48      * Search for attributes for a specific user on the ldap
49      * @param string $userName
50      * @param array $attributes
51      * @return null|array
52      * @throws LdapException
53      */
54     private function getUserWithAttributes($userName, $attributes)
55     {
56         $ldapConnection = $this->getConnection();
57         $this->bindSystemUser($ldapConnection);
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      * @param $userName
77      * @return array|null
78      * @throws LdapException
79      */
80     public function getUserDetails($userName)
81     {
82         $emailAttr = $this->config['email_attribute'];
83         $displayNameAttr = $this->config['display_name_attribute'];
84
85         $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr, $displayNameAttr]);
86
87         if ($user === null) {
88             return null;
89         }
90
91         $userCn = $this->getUserResponseProperty($user, 'cn', null);
92         return [
93             'uid'   => $this->getUserResponseProperty($user, 'uid', $user['dn']),
94             'name'  => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
95             'dn'    => $user['dn'],
96             'email' => $this->getUserResponseProperty($user, $emailAttr, null),
97         ];
98     }
99
100     /**
101      * Get a property from an LDAP user response fetch.
102      * Handles properties potentially being part of an array.
103      * @param array $userDetails
104      * @param string $propertyKey
105      * @param $defaultValue
106      * @return mixed
107      */
108     protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
109     {
110         if (isset($userDetails[$propertyKey])) {
111             return (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
112         }
113
114         return $defaultValue;
115     }
116
117     /**
118      * @param Authenticatable $user
119      * @param string $username
120      * @param string $password
121      * @return bool
122      * @throws LdapException
123      */
124     public function validateUserCredentials(Authenticatable $user, $username, $password)
125     {
126         $ldapUser = $this->getUserDetails($username);
127         if ($ldapUser === null) {
128             return false;
129         }
130
131         if ($ldapUser['uid'] !== $user->external_auth_id) {
132             return false;
133         }
134
135         $ldapConnection = $this->getConnection();
136         try {
137             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
138         } catch (\ErrorException $e) {
139             $ldapBind = false;
140         }
141
142         return $ldapBind;
143     }
144
145     /**
146      * Bind the system user to the LDAP connection using the given credentials
147      * otherwise anonymous access is attempted.
148      * @param $connection
149      * @throws LdapException
150      */
151     protected function bindSystemUser($connection)
152     {
153         $ldapDn = $this->config['dn'];
154         $ldapPass = $this->config['pass'];
155
156         $isAnonymous = ($ldapDn === false || $ldapPass === false);
157         if ($isAnonymous) {
158             $ldapBind = $this->ldap->bind($connection);
159         } else {
160             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
161         }
162
163         if (!$ldapBind) {
164             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
165         }
166     }
167
168     /**
169      * Get the connection to the LDAP server.
170      * Creates a new connection if one does not exist.
171      * @return resource
172      * @throws LdapException
173      */
174     protected function getConnection()
175     {
176         if ($this->ldapConnection !== null) {
177             return $this->ldapConnection;
178         }
179
180         // Check LDAP extension in installed
181         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
182             throw new LdapException(trans('errors.ldap_extension_not_installed'));
183         }
184
185          // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
186          // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
187         if ($this->config['tls_insecure']) {
188             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
189         }
190
191         $serverDetails = $this->parseServerString($this->config['server']);
192         $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
193
194         if ($ldapConnection === false) {
195             throw new LdapException(trans('errors.ldap_cannot_connect'));
196         }
197
198         // Set any required options
199         if ($this->config['version']) {
200             $this->ldap->setVersion($ldapConnection, $this->config['version']);
201         }
202
203         $this->ldapConnection = $ldapConnection;
204         return $this->ldapConnection;
205     }
206
207     /**
208      * Parse a LDAP server string and return the host and port for
209      * a connection. Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'
210      * @param $serverString
211      * @return array
212      */
213     protected function parseServerString($serverString)
214     {
215         $serverNameParts = explode(':', $serverString);
216
217         // If we have a protocol just return the full string since PHP will ignore a separate port.
218         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
219             return ['host' => $serverString, 'port' => 389];
220         }
221
222         // Otherwise, extract the port out
223         $hostName = $serverNameParts[0];
224         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
225         return ['host' => $hostName, 'port' => $ldapPort];
226     }
227
228     /**
229      * Build a filter string by injecting common variables.
230      * @param string $filterString
231      * @param array $attrs
232      * @return string
233      */
234     protected function buildFilter($filterString, array $attrs)
235     {
236         $newAttrs = [];
237         foreach ($attrs as $key => $attrText) {
238             $newKey = '${' . $key . '}';
239             $newAttrs[$newKey] = $this->ldap->escape($attrText);
240         }
241         return strtr($filterString, $newAttrs);
242     }
243
244     /**
245      * Get the groups a user is a part of on ldap
246      * @param string $userName
247      * @return array
248      * @throws LdapException
249      */
250     public function getUserGroups($userName)
251     {
252         $groupsAttr = $this->config['group_attribute'];
253         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
254
255         if ($user === null) {
256             return [];
257         }
258
259         $userGroups = $this->groupFilter($user);
260         $userGroups = $this->getGroupsRecursive($userGroups, []);
261         return $userGroups;
262     }
263
264     /**
265      * Get the parent groups of an array of groups
266      * @param array $groupsArray
267      * @param array $checked
268      * @return array
269      * @throws LdapException
270      */
271     private function getGroupsRecursive($groupsArray, $checked)
272     {
273         $groups_to_add = [];
274         foreach ($groupsArray as $groupName) {
275             if (in_array($groupName, $checked)) {
276                 continue;
277             }
278
279             $groupsToAdd = $this->getGroupGroups($groupName);
280             $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
281             $checked[] = $groupName;
282         }
283         $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
284
285         if (!empty($groups_to_add)) {
286             return $this->getGroupsRecursive($groupsArray, $checked);
287         } else {
288             return $groupsArray;
289         }
290     }
291
292     /**
293      * Get the parent groups of a single group
294      * @param string $groupName
295      * @return array
296      * @throws LdapException
297      */
298     private function getGroupGroups($groupName)
299     {
300         $ldapConnection = $this->getConnection();
301         $this->bindSystemUser($ldapConnection);
302
303         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
304         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
305
306         $baseDn = $this->config['base_dn'];
307         $groupsAttr = strtolower($this->config['group_attribute']);
308
309         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
310         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
311         if ($groups['count'] === 0) {
312             return [];
313         }
314
315         $groupGroups = $this->groupFilter($groups[0]);
316         return $groupGroups;
317     }
318
319     /**
320      * Filter out LDAP CN and DN language in a ldap search return
321      * Gets the base CN (common name) of the string
322      * @param array $userGroupSearchResponse
323      * @return array
324      */
325     protected function groupFilter(array $userGroupSearchResponse)
326     {
327         $groupsAttr = strtolower($this->config['group_attribute']);
328         $ldapGroups = [];
329         $count = 0;
330
331         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
332             $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
333         }
334
335         for ($i = 0; $i < $count; $i++) {
336             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
337             if (!in_array($dnComponents[0], $ldapGroups)) {
338                 $ldapGroups[] = $dnComponents[0];
339             }
340         }
341
342         return $ldapGroups;
343     }
344
345     /**
346      * Sync the LDAP groups to the user roles for the current user
347      * @param \BookStack\Auth\User $user
348      * @param string $username
349      * @throws LdapException
350      */
351     public function syncGroups(User $user, string $username)
352     {
353         $userLdapGroups = $this->getUserGroups($username);
354
355         // Get the ids for the roles from the names
356         $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
357
358         // Sync groups
359         if ($this->config['remove_from_groups']) {
360             $user->roles()->sync($ldapGroupsAsRoles);
361             $this->userRepo->attachDefaultRole($user);
362         } else {
363             $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
364         }
365     }
366
367     /**
368      * Match an array of group names from LDAP to BookStack system roles.
369      * Formats LDAP group names to be lower-case and hyphenated.
370      * @param array $groupNames
371      * @return \Illuminate\Support\Collection
372      */
373     protected function matchLdapGroupsToSystemsRoles(array $groupNames)
374     {
375         foreach ($groupNames as $i => $groupName) {
376             $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
377         }
378
379         $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
380             $query->whereIn('name', $groupNames);
381             foreach ($groupNames as $groupName) {
382                 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
383             }
384         })->get();
385
386         $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
387             return $this->roleMatchesGroupNames($role, $groupNames);
388         });
389
390         return $matchedRoles->pluck('id');
391     }
392
393     /**
394      * Check a role against an array of group names to see if it matches.
395      * Checked against role 'external_auth_id' if set otherwise the name of the role.
396      * @param \BookStack\Auth\Role $role
397      * @param array $groupNames
398      * @return bool
399      */
400     protected function roleMatchesGroupNames(Role $role, array $groupNames)
401     {
402         if ($role->external_auth_id) {
403             $externalAuthIds = explode(',', strtolower($role->external_auth_id));
404             foreach ($externalAuthIds as $externalAuthId) {
405                 if (in_array(trim($externalAuthId), $groupNames)) {
406                     return true;
407                 }
408             }
409             return false;
410         }
411
412         $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
413         return in_array($roleName, $groupNames);
414     }
415 }
Morty Proxy This is a proxified and sanitized view of the page, visit original site.