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 $nameDefault = $this->getUserResponseProperty($user, 'cn', null);
116 if (is_null($nameDefault)) {
117 $nameDefault = ldap_explode_dn($user['dn'], 1)[0] ?? $user['dn'];
121 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
122 'name' => $this->getUserDisplayName($user, $displayNameAttrs, $nameDefault),
124 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
125 'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
128 if ($this->config['dump_user_details']) {
129 throw new JsonDebugException([
130 'details_from_ldap' => $user,
131 'details_bookstack_parsed' => $formatted,
139 * Get a property from an LDAP user response fetch.
140 * Handles properties potentially being part of an array.
141 * If the given key is prefixed with 'BIN;', that indicator will be stripped
142 * from the key and any fetched values will be converted from binary to hex.
144 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
146 $isBinary = str_starts_with($propertyKey, 'BIN;');
147 $propertyKey = strtolower($propertyKey);
148 $value = $defaultValue;
151 $propertyKey = substr($propertyKey, strlen('BIN;'));
154 if (isset($userDetails[$propertyKey])) {
155 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
157 $value = bin2hex($value);
165 * Check if the given credentials are valid for the given user.
167 * @throws LdapException
169 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
171 if (is_null($ldapUserDetails)) {
175 $ldapConnection = $this->getConnection();
178 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
179 } catch (ErrorException $e) {
187 * Bind the system user to the LDAP connection using the given credentials
188 * otherwise anonymous access is attempted.
190 * @param resource|\LDAP\Connection $connection
192 * @throws LdapException
194 protected function bindSystemUser($connection): void
196 $ldapDn = $this->config['dn'];
197 $ldapPass = $this->config['pass'];
199 $isAnonymous = ($ldapDn === false || $ldapPass === false);
201 $ldapBind = $this->ldap->bind($connection);
203 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
207 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
212 * Get the connection to the LDAP server.
213 * Creates a new connection if one does not exist.
215 * @throws LdapException
217 * @return resource|\LDAP\Connection
219 protected function getConnection()
221 if ($this->ldapConnection !== null) {
222 return $this->ldapConnection;
225 // Check LDAP extension in installed
226 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
227 throw new LdapException(trans('errors.ldap_extension_not_installed'));
230 // Disable certificate verification.
231 // This option works globally and must be set before a connection is created.
232 if ($this->config['tls_insecure']) {
233 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
236 // Configure any user-provided CA cert files for LDAP.
237 // This option works globally and must be set before a connection is created.
238 if ($this->config['tls_ca_cert']) {
239 $this->configureTlsCaCerts($this->config['tls_ca_cert']);
242 $ldapHost = $this->parseServerString($this->config['server']);
243 $ldapConnection = $this->ldap->connect($ldapHost);
245 if ($ldapConnection === false) {
246 throw new LdapException(trans('errors.ldap_cannot_connect'));
249 // Set any required options
250 if ($this->config['version']) {
251 $this->ldap->setVersion($ldapConnection, $this->config['version']);
254 // Start and verify TLS if it's enabled
255 if ($this->config['start_tls']) {
257 $started = $this->ldap->startTls($ldapConnection);
258 } catch (\Exception $exception) {
259 $error = $exception->getMessage() . ' :: ' . ldap_error($ldapConnection);
260 ldap_get_option($ldapConnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $detail);
261 Log::info("LDAP STARTTLS failure: {$error} {$detail}");
262 throw new LdapException('Could not start TLS connection. Further details in the application log.');
265 throw new LdapException('Could not start TLS connection');
269 $this->ldapConnection = $ldapConnection;
271 return $this->ldapConnection;
275 * Configure TLS CA certs globally for ldap use.
276 * This will detect if the given path is a directory or file, and set the relevant
277 * LDAP TLS options appropriately otherwise throw an exception if no file/folder found.
279 * Note: When using a folder, certificates are expected to be correctly named by hash
280 * which can be done via the c_rehash utility.
282 * @throws LdapException
284 protected function configureTlsCaCerts(string $caCertPath): void
286 $errMessage = "Provided path [{$caCertPath}] for LDAP TLS CA certs could not be resolved to an existing location";
287 $path = realpath($caCertPath);
288 if ($path === false) {
289 throw new LdapException($errMessage);
293 $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTDIR, $path);
294 } else if (is_file($path)) {
295 $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTFILE, $path);
297 throw new LdapException($errMessage);
302 * Parse an LDAP server string and return the host suitable for a connection.
303 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
305 protected function parseServerString(string $serverString): string
307 if (str_starts_with($serverString, 'ldaps://') || str_starts_with($serverString, 'ldap://')) {
308 return $serverString;
311 return "ldap://{$serverString}";
315 * Build a filter string by injecting common variables.
316 * Both "${var}" and "{var}" style placeholders are supported.
317 * Dollar based are old format but supported for compatibility.
319 protected function buildFilter(string $filterString, array $attrs): string
322 foreach ($attrs as $key => $attrText) {
323 $escapedText = $this->ldap->escape($attrText);
324 $oldVarKey = '${' . $key . '}';
325 $newVarKey = '{' . $key . '}';
326 $newAttrs[$oldVarKey] = $escapedText;
327 $newAttrs[$newVarKey] = $escapedText;
330 return strtr($filterString, $newAttrs);
334 * Get the groups a user is a part of on ldap.
336 * @throws LdapException
337 * @throws JsonDebugException
339 public function getUserGroups(string $userName): array
341 $groupsAttr = $this->config['group_attribute'];
342 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
344 if ($user === null) {
348 $userGroups = $this->extractGroupsFromSearchResponseEntry($user);
349 $allGroups = $this->getGroupsRecursive($userGroups, []);
350 $formattedGroups = $this->extractGroupNamesFromLdapGroupDns($allGroups);
352 if ($this->config['dump_user_groups']) {
353 throw new JsonDebugException([
354 'details_from_ldap' => $user,
355 'parsed_direct_user_groups' => $userGroups,
356 'parsed_recursive_user_groups' => $allGroups,
357 'parsed_resulting_group_names' => $formattedGroups,
361 return $formattedGroups;
364 protected function extractGroupNamesFromLdapGroupDns(array $groupDNs): array
368 foreach ($groupDNs as $groupDN) {
369 $exploded = $this->ldap->explodeDn($groupDN, 1);
370 if ($exploded !== false && count($exploded) > 0) {
371 $names[] = $exploded[0];
375 return array_unique($names);
379 * Build an array of all relevant groups DNs after recursively scanning
380 * across parents of the groups given.
382 * @throws LdapException
384 protected function getGroupsRecursive(array $groupDNs, array $checked): array
387 foreach ($groupDNs as $groupDN) {
388 if (in_array($groupDN, $checked)) {
392 $parentGroups = $this->getParentsOfGroup($groupDN);
393 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
394 $checked[] = $groupDN;
397 $uniqueDNs = array_unique(array_merge($groupDNs, $groupsToAdd), SORT_REGULAR);
399 if (empty($groupsToAdd)) {
403 return $this->getGroupsRecursive($uniqueDNs, $checked);
407 * @throws LdapException
409 protected function getParentsOfGroup(string $groupDN): array
411 $groupsAttr = strtolower($this->config['group_attribute']);
412 $ldapConnection = $this->getConnection();
413 $this->bindSystemUser($ldapConnection);
415 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
416 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
417 $read = $this->ldap->read($ldapConnection, $groupDN, '(objectClass=*)', [$groupsAttr]);
418 $results = $this->ldap->getEntries($ldapConnection, $read);
419 if ($results['count'] === 0) {
423 return $this->extractGroupsFromSearchResponseEntry($results[0]);
427 * Extract an array of group DN values from the given LDAP search response entry
429 protected function extractGroupsFromSearchResponseEntry(array $ldapEntry): array
431 $groupsAttr = strtolower($this->config['group_attribute']);
435 if (isset($ldapEntry[$groupsAttr]['count'])) {
436 $count = (int) $ldapEntry[$groupsAttr]['count'];
439 for ($i = 0; $i < $count; $i++) {
440 $dn = $ldapEntry[$groupsAttr][$i];
441 if (!in_array($dn, $groupDNs)) {
450 * Sync the LDAP groups to the user roles for the current user.
452 * @throws LdapException
453 * @throws JsonDebugException
455 public function syncGroups(User $user, string $username): void
457 $userLdapGroups = $this->getUserGroups($username);
458 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
462 * Save and attach an avatar image, if found in the ldap details, and attach
463 * to the given user model.
465 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
467 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
472 $imageData = $ldapUserDetails['avatar'];
473 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
474 } catch (\Exception $exception) {
475 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");