3 namespace BookStack\Access;
5 use BookStack\Exceptions\JsonDebugException;
6 use BookStack\Exceptions\LdapException;
7 use BookStack\Uploads\UserAvatars;
8 use BookStack\Users\Models\User;
10 use Illuminate\Support\Facades\Log;
14 * Handles any app-specific LDAP tasks.
19 * @var resource|\LDAP\Connection
21 protected $ldapConnection;
23 protected array $config;
24 protected bool $enabled;
26 public function __construct(
28 protected UserAvatars $userAvatars,
29 protected GroupSyncService $groupSyncService
31 $this->config = config('services.ldap');
32 $this->enabled = config('auth.method') === 'ldap';
36 * Check if groups should be synced.
38 public function shouldSyncGroups(): bool
40 return $this->enabled && $this->config['user_to_groups'] !== false;
44 * Search for attributes for a specific user on the ldap.
46 * @throws LdapException
48 private function getUserWithAttributes(string $userName, array $attributes): ?array
50 $ldapConnection = $this->getConnection();
51 $this->bindSystemUser($ldapConnection);
54 foreach ($attributes as $index => $attribute) {
55 if (str_starts_with($attribute, 'BIN;')) {
56 $attributes[$index] = substr($attribute, strlen('BIN;'));
61 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
62 $baseDn = $this->config['base_dn'];
64 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
65 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
66 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
67 if ($users['count'] === 0) {
75 * Build the user display name from the (potentially multiple) attributes defined by the configuration.
77 protected function getUserDisplayName(array $userDetails, array $displayNameAttrs, string $defaultValue): string
79 $displayNameParts = [];
80 foreach ($displayNameAttrs as $dnAttr) {
81 $dnComponent = $this->getUserResponseProperty($userDetails, $dnAttr, null);
83 $displayNameParts[] = $dnComponent;
87 if (empty($displayNameParts)) {
91 return implode(' ', $displayNameParts);
95 * Get the details of a user from LDAP using the given username.
96 * User found via configurable user filter.
98 * @throws LdapException|JsonDebugException
100 public function getUserDetails(string $userName): ?array
102 $idAttr = $this->config['id_attribute'];
103 $emailAttr = $this->config['email_attribute'];
104 $displayNameAttrs = explode('|', $this->config['display_name_attribute']);
105 $thumbnailAttr = $this->config['thumbnail_attribute'];
107 $user = $this->getUserWithAttributes($userName, array_filter([
108 'cn', 'dn', $idAttr, $emailAttr, ...$displayNameAttrs, $thumbnailAttr,
111 if (is_null($user)) {
115 $userCn = $this->getUserResponseProperty($user, 'cn', null);
117 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
118 'name' => $this->getUserDisplayName($user, $displayNameAttrs, $userCn),
120 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
121 'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
124 if ($this->config['dump_user_details']) {
125 throw new JsonDebugException([
126 'details_from_ldap' => $user,
127 'details_bookstack_parsed' => $formatted,
135 * Get a property from an LDAP user response fetch.
136 * Handles properties potentially being part of an array.
137 * If the given key is prefixed with 'BIN;', that indicator will be stripped
138 * from the key and any fetched values will be converted from binary to hex.
140 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
142 $isBinary = str_starts_with($propertyKey, 'BIN;');
143 $propertyKey = strtolower($propertyKey);
144 $value = $defaultValue;
147 $propertyKey = substr($propertyKey, strlen('BIN;'));
150 if (isset($userDetails[$propertyKey])) {
151 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
153 $value = bin2hex($value);
161 * Check if the given credentials are valid for the given user.
163 * @throws LdapException
165 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
167 if (is_null($ldapUserDetails)) {
171 $ldapConnection = $this->getConnection();
174 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
175 } catch (ErrorException $e) {
183 * Bind the system user to the LDAP connection using the given credentials
184 * otherwise anonymous access is attempted.
186 * @param resource|\LDAP\Connection $connection
188 * @throws LdapException
190 protected function bindSystemUser($connection): void
192 $ldapDn = $this->config['dn'];
193 $ldapPass = $this->config['pass'];
195 $isAnonymous = ($ldapDn === false || $ldapPass === false);
197 $ldapBind = $this->ldap->bind($connection);
199 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
203 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
208 * Get the connection to the LDAP server.
209 * Creates a new connection if one does not exist.
211 * @throws LdapException
213 * @return resource|\LDAP\Connection
215 protected function getConnection()
217 if ($this->ldapConnection !== null) {
218 return $this->ldapConnection;
221 // Check LDAP extension in installed
222 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
223 throw new LdapException(trans('errors.ldap_extension_not_installed'));
226 // Disable certificate verification.
227 // This option works globally and must be set before a connection is created.
228 if ($this->config['tls_insecure']) {
229 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
232 // Configure any user-provided CA cert files for LDAP.
233 // This option works globally and must be set before a connection is created.
234 if ($this->config['tls_ca_cert']) {
235 $this->configureTlsCaCerts($this->config['tls_ca_cert']);
238 $ldapHost = $this->parseServerString($this->config['server']);
239 $ldapConnection = $this->ldap->connect($ldapHost);
241 if ($ldapConnection === false) {
242 throw new LdapException(trans('errors.ldap_cannot_connect'));
245 // Set any required options
246 if ($this->config['version']) {
247 $this->ldap->setVersion($ldapConnection, $this->config['version']);
250 // Start and verify TLS if it's enabled
251 if ($this->config['start_tls']) {
253 $started = $this->ldap->startTls($ldapConnection);
254 } catch (\Exception $exception) {
255 $error = $exception->getMessage() . ' :: ' . ldap_error($ldapConnection);
256 ldap_get_option($ldapConnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $detail);
257 Log::info("LDAP STARTTLS failure: {$error} {$detail}");
258 throw new LdapException('Could not start TLS connection. Further details in the application log.');
261 throw new LdapException('Could not start TLS connection');
265 $this->ldapConnection = $ldapConnection;
267 return $this->ldapConnection;
271 * Configure TLS CA certs globally for ldap use.
272 * This will detect if the given path is a directory or file, and set the relevant
273 * LDAP TLS options appropriately otherwise throw an exception if no file/folder found.
275 * Note: When using a folder, certificates are expected to be correctly named by hash
276 * which can be done via the c_rehash utility.
278 * @throws LdapException
280 protected function configureTlsCaCerts(string $caCertPath): void
282 $errMessage = "Provided path [{$caCertPath}] for LDAP TLS CA certs could not be resolved to an existing location";
283 $path = realpath($caCertPath);
284 if ($path === false) {
285 throw new LdapException($errMessage);
289 $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTDIR, $path);
290 } else if (is_file($path)) {
291 $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTFILE, $path);
293 throw new LdapException($errMessage);
298 * Parse an LDAP server string and return the host suitable for a connection.
299 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
301 protected function parseServerString(string $serverString): string
303 if (str_starts_with($serverString, 'ldaps://') || str_starts_with($serverString, 'ldap://')) {
304 return $serverString;
307 return "ldap://{$serverString}";
311 * Build a filter string by injecting common variables.
312 * Both "${var}" and "{var}" style placeholders are supported.
313 * Dollar based are old format but supported for compatibility.
315 protected function buildFilter(string $filterString, array $attrs): string
318 foreach ($attrs as $key => $attrText) {
319 $escapedText = $this->ldap->escape($attrText);
320 $oldVarKey = '${' . $key . '}';
321 $newVarKey = '{' . $key . '}';
322 $newAttrs[$oldVarKey] = $escapedText;
323 $newAttrs[$newVarKey] = $escapedText;
326 return strtr($filterString, $newAttrs);
330 * Get the groups a user is a part of on ldap.
332 * @throws LdapException
333 * @throws JsonDebugException
335 public function getUserGroups(string $userName): array
337 $groupsAttr = $this->config['group_attribute'];
338 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
340 if ($user === null) {
344 $userGroups = $this->extractGroupsFromSearchResponseEntry($user);
345 $allGroups = $this->getGroupsRecursive($userGroups, []);
346 $formattedGroups = $this->extractGroupNamesFromLdapGroupDns($allGroups);
348 if ($this->config['dump_user_groups']) {
349 throw new JsonDebugException([
350 'details_from_ldap' => $user,
351 'parsed_direct_user_groups' => $userGroups,
352 'parsed_recursive_user_groups' => $allGroups,
353 'parsed_resulting_group_names' => $formattedGroups,
357 return $formattedGroups;
360 protected function extractGroupNamesFromLdapGroupDns(array $groupDNs): array
364 foreach ($groupDNs as $groupDN) {
365 $exploded = $this->ldap->explodeDn($groupDN, 1);
366 if ($exploded !== false && count($exploded) > 0) {
367 $names[] = $exploded[0];
371 return array_unique($names);
375 * Build an array of all relevant groups DNs after recursively scanning
376 * across parents of the groups given.
378 * @throws LdapException
380 protected function getGroupsRecursive(array $groupDNs, array $checked): array
383 foreach ($groupDNs as $groupDN) {
384 if (in_array($groupDN, $checked)) {
388 $parentGroups = $this->getParentsOfGroup($groupDN);
389 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
390 $checked[] = $groupDN;
393 $uniqueDNs = array_unique(array_merge($groupDNs, $groupsToAdd), SORT_REGULAR);
395 if (empty($groupsToAdd)) {
399 return $this->getGroupsRecursive($uniqueDNs, $checked);
403 * @throws LdapException
405 protected function getParentsOfGroup(string $groupDN): array
407 $groupsAttr = strtolower($this->config['group_attribute']);
408 $ldapConnection = $this->getConnection();
409 $this->bindSystemUser($ldapConnection);
411 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
412 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
413 $read = $this->ldap->read($ldapConnection, $groupDN, '(objectClass=*)', [$groupsAttr]);
414 $results = $this->ldap->getEntries($ldapConnection, $read);
415 if ($results['count'] === 0) {
419 return $this->extractGroupsFromSearchResponseEntry($results[0]);
423 * Extract an array of group DN values from the given LDAP search response entry
425 protected function extractGroupsFromSearchResponseEntry(array $ldapEntry): array
427 $groupsAttr = strtolower($this->config['group_attribute']);
431 if (isset($ldapEntry[$groupsAttr]['count'])) {
432 $count = (int) $ldapEntry[$groupsAttr]['count'];
435 for ($i = 0; $i < $count; $i++) {
436 $dn = $ldapEntry[$groupsAttr][$i];
437 if (!in_array($dn, $groupDNs)) {
446 * Sync the LDAP groups to the user roles for the current user.
448 * @throws LdapException
449 * @throws JsonDebugException
451 public function syncGroups(User $user, string $username): void
453 $userLdapGroups = $this->getUserGroups($username);
454 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
458 * Save and attach an avatar image, if found in the ldap details, and attach
459 * to the given user model.
461 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
463 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
468 $imageData = $ldapUserDetails['avatar'];
469 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
470 } catch (\Exception $exception) {
471 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");