]> BookStack Code Mirror - bookstack/blob - app/Auth/Access/LdapService.php
New translations validation.php (German Informal)
[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(Authenticatable $user, string $username, string $password): bool
110     {
111         $ldapUser = $this->getUserDetails($username);
112         if ($ldapUser === null) {
113             return false;
114         }
115
116         if ($ldapUser['uid'] !== $user->external_auth_id) {
117             return false;
118         }
119
120         $ldapConnection = $this->getConnection();
121         try {
122             $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
123         } catch (ErrorException $e) {
124             $ldapBind = false;
125         }
126
127         return $ldapBind;
128     }
129
130     /**
131      * Bind the system user to the LDAP connection using the given credentials
132      * otherwise anonymous access is attempted.
133      * @param $connection
134      * @throws LdapException
135      */
136     protected function bindSystemUser($connection)
137     {
138         $ldapDn = $this->config['dn'];
139         $ldapPass = $this->config['pass'];
140
141         $isAnonymous = ($ldapDn === false || $ldapPass === false);
142         if ($isAnonymous) {
143             $ldapBind = $this->ldap->bind($connection);
144         } else {
145             $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
146         }
147
148         if (!$ldapBind) {
149             throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
150         }
151     }
152
153     /**
154      * Get the connection to the LDAP server.
155      * Creates a new connection if one does not exist.
156      * @return resource
157      * @throws LdapException
158      */
159     protected function getConnection()
160     {
161         if ($this->ldapConnection !== null) {
162             return $this->ldapConnection;
163         }
164
165         // Check LDAP extension in installed
166         if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
167             throw new LdapException(trans('errors.ldap_extension_not_installed'));
168         }
169
170          // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
171          // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
172         if ($this->config['tls_insecure']) {
173             $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
174         }
175
176         $serverDetails = $this->parseServerString($this->config['server']);
177         $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
178
179         if ($ldapConnection === false) {
180             throw new LdapException(trans('errors.ldap_cannot_connect'));
181         }
182
183         // Set any required options
184         if ($this->config['version']) {
185             $this->ldap->setVersion($ldapConnection, $this->config['version']);
186         }
187
188         $this->ldapConnection = $ldapConnection;
189         return $this->ldapConnection;
190     }
191
192     /**
193      * Parse a LDAP server string and return the host and port for a connection.
194      * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
195      */
196     protected function parseServerString(string $serverString): array
197     {
198         $serverNameParts = explode(':', $serverString);
199
200         // If we have a protocol just return the full string since PHP will ignore a separate port.
201         if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
202             return ['host' => $serverString, 'port' => 389];
203         }
204
205         // Otherwise, extract the port out
206         $hostName = $serverNameParts[0];
207         $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
208         return ['host' => $hostName, 'port' => $ldapPort];
209     }
210
211     /**
212      * Build a filter string by injecting common variables.
213      */
214     protected function buildFilter(string $filterString, array $attrs): string
215     {
216         $newAttrs = [];
217         foreach ($attrs as $key => $attrText) {
218             $newKey = '${' . $key . '}';
219             $newAttrs[$newKey] = $this->ldap->escape($attrText);
220         }
221         return strtr($filterString, $newAttrs);
222     }
223
224     /**
225      * Get the groups a user is a part of on ldap.
226      * @throws LdapException
227      */
228     public function getUserGroups(string $userName): array
229     {
230         $groupsAttr = $this->config['group_attribute'];
231         $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
232
233         if ($user === null) {
234             return [];
235         }
236
237         $userGroups = $this->groupFilter($user);
238         $userGroups = $this->getGroupsRecursive($userGroups, []);
239         return $userGroups;
240     }
241
242     /**
243      * Get the parent groups of an array of groups.
244      * @throws LdapException
245      */
246     private function getGroupsRecursive(array $groupsArray, array $checked): array
247     {
248         $groupsToAdd = [];
249         foreach ($groupsArray as $groupName) {
250             if (in_array($groupName, $checked)) {
251                 continue;
252             }
253
254             $parentGroups = $this->getGroupGroups($groupName);
255             $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
256             $checked[] = $groupName;
257         }
258
259         $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
260
261         if (empty($groupsToAdd)) {
262             return $groupsArray;
263         }
264
265         return $this->getGroupsRecursive($groupsArray, $checked);
266     }
267
268     /**
269      * Get the parent groups of a single group.
270      * @throws LdapException
271      */
272     private function getGroupGroups(string $groupName): array
273     {
274         $ldapConnection = $this->getConnection();
275         $this->bindSystemUser($ldapConnection);
276
277         $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
278         $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
279
280         $baseDn = $this->config['base_dn'];
281         $groupsAttr = strtolower($this->config['group_attribute']);
282
283         $groupFilter = 'CN=' . $this->ldap->escape($groupName);
284         $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
285         if ($groups['count'] === 0) {
286             return [];
287         }
288
289         return $this->groupFilter($groups[0]);
290     }
291
292     /**
293      * Filter out LDAP CN and DN language in a ldap search return.
294      * Gets the base CN (common name) of the string.
295      */
296     protected function groupFilter(array $userGroupSearchResponse): array
297     {
298         $groupsAttr = strtolower($this->config['group_attribute']);
299         $ldapGroups = [];
300         $count = 0;
301
302         if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
303             $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
304         }
305
306         for ($i = 0; $i < $count; $i++) {
307             $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
308             if (!in_array($dnComponents[0], $ldapGroups)) {
309                 $ldapGroups[] = $dnComponents[0];
310             }
311         }
312
313         return $ldapGroups;
314     }
315
316     /**
317      * Sync the LDAP groups to the user roles for the current user.
318      * @throws LdapException
319      */
320     public function syncGroups(User $user, string $username)
321     {
322         $userLdapGroups = $this->getUserGroups($username);
323         $this->syncWithGroups($user, $userLdapGroups);
324     }
325 }