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