]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
Fixes tooltip on the image manager.
[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         $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr]);
84
85         if ($user === null) {
86             return null;
87         }
88
89         return [
90             'uid'   => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
91             'name'  => $user['cn'][0],
92             'dn'    => $user['dn'],
93             'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
94         ];
95     }
96
97     /**
98      * @param Authenticatable $user
99      * @param string          $username
100      * @param string          $password
101      * @return bool
102      * @throws LdapException
103      */
104     public function validateUserCredentials(Authenticatable $user, $username, $password)
105     {
106         $ldapUser = $this->getUserDetails($username);
107         if ($ldapUser === null) {
108             return false;
109         }
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
174         /*
175          * Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
176          * the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not
177          * per handle.
178          */
179         if($this->config['tls_insecure']) {
180             $this->ldap->setOption(NULL, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
181         }
182
183         $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
184
185         if ($ldapConnection === false) {
186             throw new LdapException(trans('errors.ldap_cannot_connect'));
187         }
188
189         // Set any required options
190         if ($this->config['version']) {
191             $this->ldap->setVersion($ldapConnection, $this->config['version']);
192         }
193
194         $this->ldapConnection = $ldapConnection;
195         return $this->ldapConnection;
196     }
197
198     /**
199      * Build a filter string by injecting common variables.
200      * @param string $filterString
201      * @param array $attrs
202      * @return string
203      */
204     protected function buildFilter($filterString, array $attrs)
205     {
206         $newAttrs = [];
207         foreach ($attrs as $key => $attrText) {
208             $newKey = '${' . $key . '}';
209             $newAttrs[$newKey] = $this->ldap->escape($attrText);
210         }
211         return strtr($filterString, $newAttrs);
212     }
213
214     /**
215      * Get the groups a user is a part of on ldap
216      * @param string $userName
217      * @return array
218      * @throws LdapException
219      */
220     public function getUserGroups($userName)
221     {
222         $groupsAttr = $this->config['group_attribute'];
223         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
224
225         if ($user === null) {
226             return [];
227         }
228
229         $userGroups = $this->groupFilter($user);
230         $userGroups = $this->getGroupsRecursive($userGroups, []);
231         return $userGroups;
232     }
233
234     /**
235      * Get the parent groups of an array of groups
236      * @param array $groupsArray
237      * @param array $checked
238      * @return array
239      * @throws LdapException
240      */
241     private function getGroupsRecursive($groupsArray, $checked)
242     {
243         $groups_to_add = [];
244         foreach ($groupsArray as $groupName) {
245             if (in_array($groupName, $checked)) {
246                 continue;
247             }
248
249             $groupsToAdd = $this->getGroupGroups($groupName);
250             $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
251             $checked[] = $groupName;
252         }
253         $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
254
255         if (!empty($groups_to_add)) {
256             return $this->getGroupsRecursive($groupsArray, $checked);
257         } else {
258             return $groupsArray;
259         }
260     }
261
262     /**
263      * Get the parent groups of a single group
264      * @param string $groupName
265      * @return array
266      * @throws LdapException
267      */
268     private function getGroupGroups($groupName)
269     {
270         $ldapConnection = $this->getConnection();
271         $this->bindSystemUser($ldapConnection);
272
273         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
274         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
275
276         $baseDn = $this->config['base_dn'];
277         $groupsAttr = strtolower($this->config['group_attribute']);
278
279         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
280         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
281         if ($groups['count'] === 0) {
282             return [];
283         }
284
285         $groupGroups = $this->groupFilter($groups[0]);
286         return $groupGroups;
287     }
288
289     /**
290      * Filter out LDAP CN and DN language in a ldap search return
291      * Gets the base CN (common name) of the string
292      * @param array $userGroupSearchResponse
293      * @return array
294      */
295     protected function groupFilter(array $userGroupSearchResponse)
296     {
297         $groupsAttr = strtolower($this->config['group_attribute']);
298         $ldapGroups = [];
299         $count = 0;
300
301         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
302             $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
303         }
304
305         for ($i=0; $i<$count; $i++) {
306             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
307             if (!in_array($dnComponents[0], $ldapGroups)) {
308                 $ldapGroups[] = $dnComponents[0];
309             }
310         }
311
312         return $ldapGroups;
313     }
314
315     /**
316      * Sync the LDAP groups to the user roles for the current user
317      * @param \BookStack\Auth\User $user
318      * @param string $username
319      * @throws LdapException
320      */
321     public function syncGroups(User $user, string $username)
322     {
323         $userLdapGroups = $this->getUserGroups($username);
324
325         // Get the ids for the roles from the names
326         $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
327
328         // Sync groups
329         if ($this->config['remove_from_groups']) {
330             $user->roles()->sync($ldapGroupsAsRoles);
331             $this->userRepo->attachDefaultRole($user);
332         } else {
333             $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
334         }
335     }
336
337     /**
338      * Match an array of group names from LDAP to BookStack system roles.
339      * Formats LDAP group names to be lower-case and hyphenated.
340      * @param array $groupNames
341      * @return \Illuminate\Support\Collection
342      */
343     protected function matchLdapGroupsToSystemsRoles(array $groupNames)
344     {
345         foreach ($groupNames as $i => $groupName) {
346             $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
347         }
348
349         $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
350             $query->whereIn('name', $groupNames);
351             foreach ($groupNames as $groupName) {
352                 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
353             }
354         })->get();
355
356         $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
357             return $this->roleMatchesGroupNames($role, $groupNames);
358         });
359
360         return $matchedRoles->pluck('id');
361     }
362
363     /**
364      * Check a role against an array of group names to see if it matches.
365      * Checked against role 'external_auth_id' if set otherwise the name of the role.
366      * @param \BookStack\Auth\Role $role
367      * @param array $groupNames
368      * @return bool
369      */
370     protected function roleMatchesGroupNames(Role $role, array $groupNames)
371     {
372         if ($role->external_auth_id) {
373             $externalAuthIds = explode(',', strtolower($role->external_auth_id));
374             foreach ($externalAuthIds as $externalAuthId) {
375                 if (in_array(trim($externalAuthId), $groupNames)) {
376                     return true;
377                 }
378             }
379             return false;
380         }
381
382         $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
383         return in_array($roleName, $groupNames);
384     }
385 }