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