]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
47dc24532864ec61e722005fafee8c7c796f73b9
[bookstack] / app / Auth / Access / LdapService.php
1 <?php namespace BookStack\Auth\Access;
2
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\LdapException;
6 use ErrorException;
7
8 /**
9  * Class LdapService
10  * Handles any app-specific LDAP tasks.
11  */
12 class LdapService extends ExternalAuthService
13 {
14
15     protected $ldap;
16     protected $ldapConnection;
17     protected $config;
18     protected $enabled;
19
20     /**
21      * LdapService constructor.
22      */
23     public function __construct(Ldap $ldap)
24     {
25         $this->ldap = $ldap;
26         $this->config = config('services.ldap');
27         $this->enabled = config('auth.method') === 'ldap';
28     }
29
30     /**
31      * Check if groups should be synced.
32      * @return bool
33      */
34     public function shouldSyncGroups()
35     {
36         return $this->enabled && $this->config['user_to_groups'] !== false;
37     }
38
39     /**
40      * Search for attributes for a specific user on the ldap.
41      * @throws LdapException
42      */
43     private function getUserWithAttributes(string $userName, array $attributes): ?array
44     {
45         $ldapConnection = $this->getConnection();
46         $this->bindSystemUser($ldapConnection);
47
48         // Clean attributes
49         foreach ($attributes as $index => $attribute) {
50             if (strpos($attribute, 'BIN;') === 0) {
51                 $attributes[$index] = substr($attribute, strlen('BIN;'));
52             }
53         }
54
55         // Find user
56         $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
57         $baseDn = $this->config['base_dn'];
58
59         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
60         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
61         $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
62         if ($users['count'] === 0) {
63             return null;
64         }
65
66         return $users[0];
67     }
68
69     /**
70      * Get the details of a user from LDAP using the given username.
71      * User found via configurable user filter.
72      * @throws LdapException
73      */
74     public function getUserDetails(string $userName): ?array
75     {
76         $idAttr = $this->config['id_attribute'];
77         $emailAttr = $this->config['email_attribute'];
78         $displayNameAttr = $this->config['display_name_attribute'];
79
80         $user = $this->getUserWithAttributes($userName, ['cn', 'dn', $idAttr, $emailAttr, $displayNameAttr]);
81
82         if ($user === null) {
83             return null;
84         }
85
86         $userCn = $this->getUserResponseProperty($user, 'cn', null);
87         $formatted = [
88             'uid'   => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
89             'name'  => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
90             'dn'    => $user['dn'],
91             'email' => $this->getUserResponseProperty($user, $emailAttr, null),
92             'avatar'=> $this->getUserResponseProperty($user, $thumbnailAttr, null),
93         ];
94
95         if ($this->config['dump_user_details']) {
96             throw new JsonDebugException([
97                 'details_from_ldap' => $user,
98                 'details_bookstack_parsed' => $formatted,
99             ]);
100         }
101
102         return $formatted;
103     }
104
105     /**
106      * Get a property from an LDAP user response fetch.
107      * Handles properties potentially being part of an array.
108      * If the given key is prefixed with 'BIN;', that indicator will be stripped
109      * from the key and any fetched values will be converted from binary to hex.
110      */
111     protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
112     {
113         $isBinary = strpos($propertyKey, 'BIN;') === 0;
114         $propertyKey = strtolower($propertyKey);
115         $value = $defaultValue;
116
117         if ($isBinary) {
118             $propertyKey = substr($propertyKey, strlen('BIN;'));
119         }
120
121         if (isset($userDetails[$propertyKey])) {
122             $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
123             if ($isBinary) {
124                 $value = bin2hex($value);
125             }
126         }
127
128         return $value;
129     }
130
131     /**
132      * Check if the given credentials are valid for the given user.
133      * @throws LdapException
134      */
135     public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
136     {
137         if (is_null($ldapUserDetails)) {
138             return false;
139         }
140
141         $ldapConnection = $this->getConnection();
142         try {
143             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
144         } catch (ErrorException $e) {
145             $ldapBind = false;
146         }
147
148         return $ldapBind;
149     }
150
151     /**
152      * Bind the system user to the LDAP connection using the given credentials
153      * otherwise anonymous access is attempted.
154      * @param $connection
155      * @throws LdapException
156      */
157     protected function bindSystemUser($connection)
158     {
159         $ldapDn = $this->config['dn'];
160         $ldapPass = $this->config['pass'];
161
162         $isAnonymous = ($ldapDn === false || $ldapPass === false);
163         if ($isAnonymous) {
164             $ldapBind = $this->ldap->bind($connection);
165         } else {
166             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
167         }
168
169         if (!$ldapBind) {
170             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
171         }
172     }
173
174     /**
175      * Get the connection to the LDAP server.
176      * Creates a new connection if one does not exist.
177      * @return resource
178      * @throws LdapException
179      */
180     protected function getConnection()
181     {
182         if ($this->ldapConnection !== null) {
183             return $this->ldapConnection;
184         }
185
186         // Check LDAP extension in installed
187         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
188             throw new LdapException(trans('errors.ldap_extension_not_installed'));
189         }
190
191          // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
192          // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
193         if ($this->config['tls_insecure']) {
194             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
195         }
196
197         $serverDetails = $this->parseServerString($this->config['server']);
198         $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
199
200         if ($ldapConnection === false) {
201             throw new LdapException(trans('errors.ldap_cannot_connect'));
202         }
203
204         // Set any required options
205         if ($this->config['version']) {
206             $this->ldap->setVersion($ldapConnection, $this->config['version']);
207         }
208
209         $this->ldapConnection = $ldapConnection;
210         return $this->ldapConnection;
211     }
212
213     /**
214      * Parse a LDAP server string and return the host and port for a connection.
215      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
216      */
217     protected function parseServerString(string $serverString): array
218     {
219         $serverNameParts = explode(':', $serverString);
220
221         // If we have a protocol just return the full string since PHP will ignore a separate port.
222         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
223             return ['host' => $serverString, 'port' => 389];
224         }
225
226         // Otherwise, extract the port out
227         $hostName = $serverNameParts[0];
228         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
229         return ['host' => $hostName, 'port' => $ldapPort];
230     }
231
232     /**
233      * Build a filter string by injecting common variables.
234      */
235     protected function buildFilter(string $filterString, array $attrs): string
236     {
237         $newAttrs = [];
238         foreach ($attrs as $key => $attrText) {
239             $newKey = '${' . $key . '}';
240             $newAttrs[$newKey] = $this->ldap->escape($attrText);
241         }
242         return strtr($filterString, $newAttrs);
243     }
244
245     /**
246      * Get the groups a user is a part of on ldap.
247      * @throws LdapException
248      */
249     public function getUserGroups(string $userName): array
250     {
251         $groupsAttr = $this->config['group_attribute'];
252         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
253
254         if ($user === null) {
255             return [];
256         }
257
258         $userGroups = $this->groupFilter($user);
259         $userGroups = $this->getGroupsRecursive($userGroups, []);
260         return $userGroups;
261     }
262
263     /**
264      * Get the parent groups of an array of groups.
265      * @throws LdapException
266      */
267     private function getGroupsRecursive(array $groupsArray, array $checked): array
268     {
269         $groupsToAdd = [];
270         foreach ($groupsArray as $groupName) {
271             if (in_array($groupName, $checked)) {
272                 continue;
273             }
274
275             $parentGroups = $this->getGroupGroups($groupName);
276             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
277             $checked[] = $groupName;
278         }
279
280         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
281
282         if (empty($groupsToAdd)) {
283             return $groupsArray;
284         }
285
286         return $this->getGroupsRecursive($groupsArray, $checked);
287     }
288
289     /**
290      * Get the parent groups of a single group.
291      * @throws LdapException
292      */
293     private function getGroupGroups(string $groupName): array
294     {
295         $ldapConnection = $this->getConnection();
296         $this->bindSystemUser($ldapConnection);
297
298         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
299         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
300
301         $baseDn = $this->config['base_dn'];
302         $groupsAttr = strtolower($this->config['group_attribute']);
303
304         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
305         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
306         if ($groups['count'] === 0) {
307             return [];
308         }
309
310         return $this->groupFilter($groups[0]);
311     }
312
313     /**
314      * Filter out LDAP CN and DN language in a ldap search return.
315      * Gets the base CN (common name) of the string.
316      */
317     protected function groupFilter(array $userGroupSearchResponse): array
318     {
319         $groupsAttr = strtolower($this->config['group_attribute']);
320         $ldapGroups = [];
321         $count = 0;
322
323         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
324             $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
325         }
326
327         for ($i = 0; $i < $count; $i++) {
328             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
329             if (!in_array($dnComponents[0], $ldapGroups)) {
330                 $ldapGroups[] = $dnComponents[0];
331             }
332         }
333
334         return $ldapGroups;
335     }
336
337     /**
338      * Sync the LDAP groups to the user roles for the current user.
339      * @throws LdapException
340      */
341     public function syncGroups(User $user, string $username)
342     {
343         $userLdapGroups = $this->getUserGroups($username);
344         $this->syncWithGroups($user, $userLdapGroups);
345     }
346 }