]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
Merge branch 'master' of https://github.com/jasonhoule/BookStack into jasonhoule...
[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         $thumbnailAttr = $this->config['thumbnail_attribute'];
80
81         $user = $this->getUserWithAttributes($userName, ['cn', 'dn', $idAttr, $emailAttr, $displayNameAttr]);
82
83         if ($user === null) {
84             return null;
85         }
86
87         $userCn = $this->getUserResponseProperty($user, 'cn', null);
88         $formatted = [
89             'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
90             'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
91             'dn' => $user['dn'],
92             'email' => $this->getUserResponseProperty($user, $emailAttr, null),
93             'avatar'=> $this->getUserResponseProperty($user, $thumbnailAttr, null),
94         ];
95
96         if ($this->config['dump_user_details']) {
97             throw new JsonDebugException([
98                 'details_from_ldap' => $user,
99                 'details_bookstack_parsed' => $formatted,
100             ]);
101         }
102
103         return $formatted;
104     }
105
106     /**
107      * Get a property from an LDAP user response fetch.
108      * Handles properties potentially being part of an array.
109      * If the given key is prefixed with 'BIN;', that indicator will be stripped
110      * from the key and any fetched values will be converted from binary to hex.
111      */
112     protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
113     {
114         $isBinary = strpos($propertyKey, 'BIN;') === 0;
115         $propertyKey = strtolower($propertyKey);
116         $value = $defaultValue;
117
118         if ($isBinary) {
119             $propertyKey = substr($propertyKey, strlen('BIN;'));
120         }
121
122         if (isset($userDetails[$propertyKey])) {
123             $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
124             if ($isBinary) {
125                 $value = bin2hex($value);
126             }
127         }
128
129         return $value;
130     }
131
132     /**
133      * Check if the given credentials are valid for the given user.
134      * @throws LdapException
135      */
136     public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
137     {
138         if (is_null($ldapUserDetails)) {
139             return false;
140         }
141
142         $ldapConnection = $this->getConnection();
143         try {
144             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
145         } catch (ErrorException $e) {
146             $ldapBind = false;
147         }
148
149         return $ldapBind;
150     }
151
152     /**
153      * Bind the system user to the LDAP connection using the given credentials
154      * otherwise anonymous access is attempted.
155      * @param $connection
156      * @throws LdapException
157      */
158     protected function bindSystemUser($connection)
159     {
160         $ldapDn = $this->config['dn'];
161         $ldapPass = $this->config['pass'];
162
163         $isAnonymous = ($ldapDn === false || $ldapPass === false);
164         if ($isAnonymous) {
165             $ldapBind = $this->ldap->bind($connection);
166         } else {
167             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
168         }
169
170         if (!$ldapBind) {
171             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
172         }
173     }
174
175     /**
176      * Get the connection to the LDAP server.
177      * Creates a new connection if one does not exist.
178      * @return resource
179      * @throws LdapException
180      */
181     protected function getConnection()
182     {
183         if ($this->ldapConnection !== null) {
184             return $this->ldapConnection;
185         }
186
187         // Check LDAP extension in installed
188         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
189             throw new LdapException(trans('errors.ldap_extension_not_installed'));
190         }
191
192         // Disable certificate verification.
193         // This option works globally and must be set before a connection is created.
194         if ($this->config['tls_insecure']) {
195             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
196         }
197
198         $serverDetails = $this->parseServerString($this->config['server']);
199         $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
200
201         if ($ldapConnection === false) {
202             throw new LdapException(trans('errors.ldap_cannot_connect'));
203         }
204
205         // Set any required options
206         if ($this->config['version']) {
207             $this->ldap->setVersion($ldapConnection, $this->config['version']);
208         }
209
210         // Start and verify TLS if it's enabled
211         if ($this->config['start_tls']) {
212             $started = $this->ldap->startTls($ldapConnection);
213             if (!$started) {
214                 throw new LdapException('Could not start TLS connection');
215             }
216         }
217
218         $this->ldapConnection = $ldapConnection;
219         return $this->ldapConnection;
220     }
221
222     /**
223      * Parse a LDAP server string and return the host and port for a connection.
224      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
225      */
226     protected function parseServerString(string $serverString): array
227     {
228         $serverNameParts = explode(':', $serverString);
229
230         // If we have a protocol just return the full string since PHP will ignore a separate port.
231         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
232             return ['host' => $serverString, 'port' => 389];
233         }
234
235         // Otherwise, extract the port out
236         $hostName = $serverNameParts[0];
237         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
238         return ['host' => $hostName, 'port' => $ldapPort];
239     }
240
241     /**
242      * Build a filter string by injecting common variables.
243      */
244     protected function buildFilter(string $filterString, array $attrs): string
245     {
246         $newAttrs = [];
247         foreach ($attrs as $key => $attrText) {
248             $newKey = '${' . $key . '}';
249             $newAttrs[$newKey] = $this->ldap->escape($attrText);
250         }
251         return strtr($filterString, $newAttrs);
252     }
253
254     /**
255      * Get the groups a user is a part of on ldap.
256      * @throws LdapException
257      */
258     public function getUserGroups(string $userName): array
259     {
260         $groupsAttr = $this->config['group_attribute'];
261         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
262
263         if ($user === null) {
264             return [];
265         }
266
267         $userGroups = $this->groupFilter($user);
268         $userGroups = $this->getGroupsRecursive($userGroups, []);
269         return $userGroups;
270     }
271
272     /**
273      * Get the parent groups of an array of groups.
274      * @throws LdapException
275      */
276     private function getGroupsRecursive(array $groupsArray, array $checked): array
277     {
278         $groupsToAdd = [];
279         foreach ($groupsArray as $groupName) {
280             if (in_array($groupName, $checked)) {
281                 continue;
282             }
283
284             $parentGroups = $this->getGroupGroups($groupName);
285             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
286             $checked[] = $groupName;
287         }
288
289         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
290
291         if (empty($groupsToAdd)) {
292             return $groupsArray;
293         }
294
295         return $this->getGroupsRecursive($groupsArray, $checked);
296     }
297
298     /**
299      * Get the parent groups of a single group.
300      * @throws LdapException
301      */
302     private function getGroupGroups(string $groupName): array
303     {
304         $ldapConnection = $this->getConnection();
305         $this->bindSystemUser($ldapConnection);
306
307         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
308         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
309
310         $baseDn = $this->config['base_dn'];
311         $groupsAttr = strtolower($this->config['group_attribute']);
312
313         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
314         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
315         if ($groups['count'] === 0) {
316             return [];
317         }
318
319         return $this->groupFilter($groups[0]);
320     }
321
322     /**
323      * Filter out LDAP CN and DN language in a ldap search return.
324      * Gets the base CN (common name) of the string.
325      */
326     protected function groupFilter(array $userGroupSearchResponse): array
327     {
328         $groupsAttr = strtolower($this->config['group_attribute']);
329         $ldapGroups = [];
330         $count = 0;
331
332         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
333             $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
334         }
335
336         for ($i = 0; $i < $count; $i++) {
337             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
338             if (!in_array($dnComponents[0], $ldapGroups)) {
339                 $ldapGroups[] = $dnComponents[0];
340             }
341         }
342
343         return $ldapGroups;
344     }
345
346     /**
347      * Sync the LDAP groups to the user roles for the current user.
348      * @throws LdapException
349      */
350     public function syncGroups(User $user, string $username)
351     {
352         $userLdapGroups = $this->getUserGroups($username);
353         $this->syncWithGroups($user, $userLdapGroups);
354     }
355 }