3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\JsonDebugException;
7 use BookStack\Exceptions\LdapException;
8 use BookStack\Exceptions\LdapFailedBindException;
9 use BookStack\Uploads\UserAvatars;
11 use Illuminate\Support\Facades\Log;
15 * Handles any app-specific LDAP tasks.
20 protected GroupSyncService $groupSyncService;
21 protected UserAvatars $userAvatars;
23 protected array $config;
24 protected bool $enabled;
27 * LdapService constructor.
29 public function __construct(Ldap $ldap, UserAvatars $userAvatars, GroupSyncService $groupSyncService)
32 $this->userAvatars = $userAvatars;
33 $this->groupSyncService = $groupSyncService;
34 $this->config = config('services.ldap');
35 $this->enabled = config('auth.method') === 'ldap';
39 * Check if groups should be synced.
41 public function shouldSyncGroups(): bool
43 return $this->enabled && $this->config['user_to_groups'] !== false;
47 * Search for attributes for a specific user on the ldap.
49 * @throws LdapException
51 protected function getUserWithAttributes(string $userName, array $attributes): ?array
53 $ldapConnection = $this->bindConnection();
56 foreach ($attributes as $index => $attribute) {
57 if (strpos($attribute, 'BIN;') === 0) {
58 $attributes[$index] = substr($attribute, strlen('BIN;'));
63 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
64 $baseDn = $this->config['base_dn'];
66 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
67 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
68 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
69 if ($users['count'] === 0) {
77 * Get the details of a user from LDAP using the given username.
78 * User found via configurable user filter.
80 * @throws LdapException
82 public function getUserDetails(string $userName): ?array
84 $idAttr = $this->config['id_attribute'];
85 $emailAttr = $this->config['email_attribute'];
86 $displayNameAttr = $this->config['display_name_attribute'];
87 $thumbnailAttr = $this->config['thumbnail_attribute'];
89 $user = $this->getUserWithAttributes($userName, array_filter([
90 'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
97 $userCn = $this->getUserResponseProperty($user, 'cn', null);
99 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
100 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
102 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
103 'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
106 if ($this->config['dump_user_details']) {
107 throw new JsonDebugException([
108 'details_from_ldap' => $user,
109 'details_bookstack_parsed' => $formatted,
117 * Get a property from an LDAP user response fetch.
118 * Handles properties potentially being part of an array.
119 * If the given key is prefixed with 'BIN;', that indicator will be stripped
120 * from the key and any fetched values will be converted from binary to hex.
122 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
124 $isBinary = strpos($propertyKey, 'BIN;') === 0;
125 $propertyKey = strtolower($propertyKey);
126 $value = $defaultValue;
129 $propertyKey = substr($propertyKey, strlen('BIN;'));
132 if (isset($userDetails[$propertyKey])) {
133 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
135 $value = bin2hex($value);
143 * Check if the given credentials are valid for the given user.
145 * @throws LdapException
147 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
149 if (is_null($ldapUserDetails)) {
154 $this->bindConnection($ldapUserDetails['dn'], $password);
155 } catch (LdapFailedBindException $e) {
157 } catch (LdapException $e) {
166 * Attempted to start and bind to a new LDAP connection.
167 * Will attempt against multiple defined fail-over hosts if set.
169 * Throws a LdapFailedBindException error if the bind connected but failed.
170 * Otherwise, generic LdapException errors would be thrown.
173 * @throws LdapException
175 protected function bindConnection(string $dn = null, string $password = null)
177 $systemBind = ($dn === null && $password === null);
179 // Check LDAP extension in installed
180 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
181 throw new LdapException(trans('errors.ldap_extension_not_installed'));
184 // Disable certificate verification.
185 // This option works globally and must be set before a connection is created.
186 if ($this->config['tls_insecure']) {
187 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
190 $serverDetails = $this->parseMultiServerString($this->config['server']);
191 $lastException = null;
193 foreach ($serverDetails as $server) {
195 $connection = $this->startServerConnection($server);
196 } catch (LdapException $exception) {
197 $lastException = $exception;
203 $this->bindSystemUser($connection);
205 $this->bindGivenUser($connection, $dn, $password);
207 } catch (LdapFailedBindException $exception) {
208 // Rethrow simply to indicate the importance of handling this exception case
209 // to indicate auth status. We skip past attempting fail-over hosts in this case since it's
210 // likely the connection worked here but the bind was unauthorised.
212 } catch (ErrorException $exception) {
213 Log::error('LDAP bind error: ' . $exception->getMessage());
214 $lastException = new LdapException('Encountered error during LDAP bind');
221 throw $lastException;
225 * Bind to the given LDAP connection using the given credentials.
226 * MUST throw an exception on failure.
228 * @param resource $connection
230 * @throws LdapFailedBindException
232 protected function bindGivenUser($connection, string $dn = null, string $password = null): void
234 $ldapBind = $this->ldap->bind($connection, $dn, $password);
237 throw new LdapFailedBindException('Failed to bind with given user details');
242 * Bind the system user to the LDAP connection using the configured credentials otherwise anonymous
243 * access is attempted. MUST throw an exception on failure.
245 * @param resource $connection
247 * @throws LdapFailedBindException
249 protected function bindSystemUser($connection): void
251 $ldapDn = $this->config['dn'];
252 $ldapPass = $this->config['pass'];
254 $isAnonymous = ($ldapDn === false || $ldapPass === false);
256 $ldapBind = $this->ldap->bind($connection);
258 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
262 throw new LdapFailedBindException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
267 * Attempt to start a server connection from the provided details.
269 * @param array{host: string, port: int} $serverDetail
271 * @throws LdapException
273 protected function startServerConnection(array $serverDetail)
275 $ldapConnection = $this->ldap->connect($serverDetail['host'], $serverDetail['port']);
277 if (!$ldapConnection) {
278 throw new LdapException(trans('errors.ldap_cannot_connect'));
281 // Set any required options
282 if ($this->config['version']) {
283 $this->ldap->setVersion($ldapConnection, $this->config['version']);
286 // Start and verify TLS if it's enabled
287 if ($this->config['start_tls']) {
289 $tlsStarted = $this->ldap->startTls($ldapConnection);
290 } catch (ErrorException $exception) {
295 throw new LdapException('Could not start TLS connection');
299 return $ldapConnection;
303 * Parse a potentially multi-value LDAP server host string and return an array of host/port detail pairs.
304 * Multiple hosts are separated with a semicolon, for example: 'ldap.example.com:8069;ldaps://ldap.example.com'
306 * @return array<array{host: string, port: int}>
308 protected function parseMultiServerString(string $serversString): array
310 $serverStringList = explode(';', $serversString);
312 return array_map(fn ($serverStr) => $this->parseSingleServerString($serverStr), $serverStringList);
316 * Parse an LDAP server string and return the host and port for a connection.
317 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
319 * @return array{host: string, port: int}
321 protected function parseSingleServerString(string $serverString): array
323 $serverNameParts = explode(':', $serverString);
325 // If we have a protocol just return the full string since PHP will ignore a separate port.
326 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
327 return ['host' => $serverString, 'port' => 389];
330 // Otherwise, extract the port out
331 $hostName = $serverNameParts[0];
332 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
334 return ['host' => $hostName, 'port' => $ldapPort];
338 * Build a filter string by injecting common variables.
340 protected function buildFilter(string $filterString, array $attrs): string
343 foreach ($attrs as $key => $attrText) {
344 $newKey = '${' . $key . '}';
345 $newAttrs[$newKey] = $this->ldap->escape($attrText);
348 return strtr($filterString, $newAttrs);
352 * Get the groups a user is a part of on ldap.
354 * @throws LdapException
355 * @throws JsonDebugException
357 public function getUserGroups(string $userName): array
359 $groupsAttr = $this->config['group_attribute'];
360 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
362 if ($user === null) {
366 $userGroups = $this->groupFilter($user);
367 $allGroups = $this->getGroupsRecursive($userGroups, []);
369 if ($this->config['dump_user_groups']) {
370 throw new JsonDebugException([
371 'details_from_ldap' => $user,
372 'parsed_direct_user_groups' => $userGroups,
373 'parsed_recursive_user_groups' => $allGroups,
381 * Get the parent groups of an array of groups.
383 * @throws LdapException
385 private function getGroupsRecursive(array $groupsArray, array $checked): array
388 foreach ($groupsArray as $groupName) {
389 if (in_array($groupName, $checked)) {
393 $parentGroups = $this->getGroupGroups($groupName);
394 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
395 $checked[] = $groupName;
398 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
400 if (empty($groupsToAdd)) {
404 return $this->getGroupsRecursive($groupsArray, $checked);
408 * Get the parent groups of a single group.
410 * @throws LdapException
412 private function getGroupGroups(string $groupName): array
414 $ldapConnection = $this->bindConnection();
416 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
417 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
419 $baseDn = $this->config['base_dn'];
420 $groupsAttr = strtolower($this->config['group_attribute']);
422 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
423 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
424 if ($groups['count'] === 0) {
428 return $this->groupFilter($groups[0]);
432 * Filter out LDAP CN and DN language in a ldap search return.
433 * Gets the base CN (common name) of the string.
435 protected function groupFilter(array $userGroupSearchResponse): array
437 $groupsAttr = strtolower($this->config['group_attribute']);
441 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
442 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
445 for ($i = 0; $i < $count; $i++) {
446 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
447 if (!in_array($dnComponents[0], $ldapGroups)) {
448 $ldapGroups[] = $dnComponents[0];
456 * Sync the LDAP groups to the user roles for the current user.
458 * @throws LdapException
459 * @throws JsonDebugException
461 public function syncGroups(User $user, string $username)
463 $userLdapGroups = $this->getUserGroups($username);
464 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
468 * Save and attach an avatar image, if found in the ldap details, and attach
469 * to the given user model.
471 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
473 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
478 $imageData = $ldapUserDetails['avatar'];
479 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
480 } catch (\Exception $exception) {
481 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");