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