]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
Preserve original display_name_attribute configuration values.
[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         return [
92             'uid'   => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
93             'name'  => (isset($user[$displayNameAttr])) ? (is_array($user[$displayNameAttr]) ? $user[$displayNameAttr][0] : $user[$displayNameAttr]) : $user['cn'][0],
94             'dn'    => $user['dn'],
95             'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
96         ];
97     }
98
99     /**
100      * @param Authenticatable $user
101      * @param string          $username
102      * @param string          $password
103      * @return bool
104      * @throws LdapException
105      */
106     public function validateUserCredentials(Authenticatable $user, $username, $password)
107     {
108         $ldapUser = $this->getUserDetails($username);
109         if ($ldapUser === null) {
110             return false;
111         }
112
113         if ($ldapUser['uid'] !== $user->external_auth_id) {
114             return false;
115         }
116
117         $ldapConnection = $this->getConnection();
118         try {
119             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
120         } catch (\ErrorException $e) {
121             $ldapBind = false;
122         }
123
124         return $ldapBind;
125     }
126
127     /**
128      * Bind the system user to the LDAP connection using the given credentials
129      * otherwise anonymous access is attempted.
130      * @param $connection
131      * @throws LdapException
132      */
133     protected function bindSystemUser($connection)
134     {
135         $ldapDn = $this->config['dn'];
136         $ldapPass = $this->config['pass'];
137
138         $isAnonymous = ($ldapDn === false || $ldapPass === false);
139         if ($isAnonymous) {
140             $ldapBind = $this->ldap->bind($connection);
141         } else {
142             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
143         }
144
145         if (!$ldapBind) {
146             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
147         }
148     }
149
150     /**
151      * Get the connection to the LDAP server.
152      * Creates a new connection if one does not exist.
153      * @return resource
154      * @throws LdapException
155      */
156     protected function getConnection()
157     {
158         if ($this->ldapConnection !== null) {
159             return $this->ldapConnection;
160         }
161
162         // Check LDAP extension in installed
163         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
164             throw new LdapException(trans('errors.ldap_extension_not_installed'));
165         }
166
167         // Get port from server string and protocol if specified.
168         $ldapServer = explode(':', $this->config['server']);
169         $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
170         if (!$hasProtocol) {
171             array_unshift($ldapServer, '');
172         }
173         $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
174         $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
175
176         /*
177          * Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
178          * the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not
179          * per handle.
180          */
181         if ($this->config['tls_insecure']) {
182             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
183         }
184
185         $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
186
187         if ($ldapConnection === false) {
188             throw new LdapException(trans('errors.ldap_cannot_connect'));
189         }
190
191         // Set any required options
192         if ($this->config['version']) {
193             $this->ldap->setVersion($ldapConnection, $this->config['version']);
194         }
195
196         $this->ldapConnection = $ldapConnection;
197         return $this->ldapConnection;
198     }
199
200     /**
201      * Build a filter string by injecting common variables.
202      * @param string $filterString
203      * @param array $attrs
204      * @return string
205      */
206     protected function buildFilter($filterString, array $attrs)
207     {
208         $newAttrs = [];
209         foreach ($attrs as $key => $attrText) {
210             $newKey = '${' . $key . '}';
211             $newAttrs[$newKey] = $this->ldap->escape($attrText);
212         }
213         return strtr($filterString, $newAttrs);
214     }
215
216     /**
217      * Get the groups a user is a part of on ldap
218      * @param string $userName
219      * @return array
220      * @throws LdapException
221      */
222     public function getUserGroups($userName)
223     {
224         $groupsAttr = $this->config['group_attribute'];
225         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
226
227         if ($user === null) {
228             return [];
229         }
230
231         $userGroups = $this->groupFilter($user);
232         $userGroups = $this->getGroupsRecursive($userGroups, []);
233         return $userGroups;
234     }
235
236     /**
237      * Get the parent groups of an array of groups
238      * @param array $groupsArray
239      * @param array $checked
240      * @return array
241      * @throws LdapException
242      */
243     private function getGroupsRecursive($groupsArray, $checked)
244     {
245         $groups_to_add = [];
246         foreach ($groupsArray as $groupName) {
247             if (in_array($groupName, $checked)) {
248                 continue;
249             }
250
251             $groupsToAdd = $this->getGroupGroups($groupName);
252             $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
253             $checked[] = $groupName;
254         }
255         $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
256
257         if (!empty($groups_to_add)) {
258             return $this->getGroupsRecursive($groupsArray, $checked);
259         } else {
260             return $groupsArray;
261         }
262     }
263
264     /**
265      * Get the parent groups of a single group
266      * @param string $groupName
267      * @return array
268      * @throws LdapException
269      */
270     private function getGroupGroups($groupName)
271     {
272         $ldapConnection = $this->getConnection();
273         $this->bindSystemUser($ldapConnection);
274
275         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
276         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
277
278         $baseDn = $this->config['base_dn'];
279         $groupsAttr = strtolower($this->config['group_attribute']);
280
281         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
282         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
283         if ($groups['count'] === 0) {
284             return [];
285         }
286
287         $groupGroups = $this->groupFilter($groups[0]);
288         return $groupGroups;
289     }
290
291     /**
292      * Filter out LDAP CN and DN language in a ldap search return
293      * Gets the base CN (common name) of the string
294      * @param array $userGroupSearchResponse
295      * @return array
296      */
297     protected function groupFilter(array $userGroupSearchResponse)
298     {
299         $groupsAttr = strtolower($this->config['group_attribute']);
300         $ldapGroups = [];
301         $count = 0;
302
303         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
304             $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
305         }
306
307         for ($i=0; $i<$count; $i++) {
308             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
309             if (!in_array($dnComponents[0], $ldapGroups)) {
310                 $ldapGroups[] = $dnComponents[0];
311             }
312         }
313
314         return $ldapGroups;
315     }
316
317     /**
318      * Sync the LDAP groups to the user roles for the current user
319      * @param \BookStack\Auth\User $user
320      * @param string $username
321      * @throws LdapException
322      */
323     public function syncGroups(User $user, string $username)
324     {
325         $userLdapGroups = $this->getUserGroups($username);
326
327         // Get the ids for the roles from the names
328         $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
329
330         // Sync groups
331         if ($this->config['remove_from_groups']) {
332             $user->roles()->sync($ldapGroupsAsRoles);
333             $this->userRepo->attachDefaultRole($user);
334         } else {
335             $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
336         }
337     }
338
339     /**
340      * Match an array of group names from LDAP to BookStack system roles.
341      * Formats LDAP group names to be lower-case and hyphenated.
342      * @param array $groupNames
343      * @return \Illuminate\Support\Collection
344      */
345     protected function matchLdapGroupsToSystemsRoles(array $groupNames)
346     {
347         foreach ($groupNames as $i => $groupName) {
348             $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
349         }
350
351         $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
352             $query->whereIn('name', $groupNames);
353             foreach ($groupNames as $groupName) {
354                 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
355             }
356         })->get();
357
358         $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
359             return $this->roleMatchesGroupNames($role, $groupNames);
360         });
361
362         return $matchedRoles->pluck('id');
363     }
364
365     /**
366      * Check a role against an array of group names to see if it matches.
367      * Checked against role 'external_auth_id' if set otherwise the name of the role.
368      * @param \BookStack\Auth\Role $role
369      * @param array $groupNames
370      * @return bool
371      */
372     protected function roleMatchesGroupNames(Role $role, array $groupNames)
373     {
374         if ($role->external_auth_id) {
375             $externalAuthIds = explode(',', strtolower($role->external_auth_id));
376             foreach ($externalAuthIds as $externalAuthId) {
377                 if (in_array(trim($externalAuthId), $groupNames)) {
378                     return true;
379                 }
380             }
381             return false;
382         }
383
384         $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
385         return in_array($roleName, $groupNames);
386     }
387 }