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