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 * Get the details of a user from LDAP using the given username.
76 * User found via configurable user filter.
78 * @throws LdapException|JsonDebugException
80 public function getUserDetails(string $userName): ?array
82 $idAttr = $this->config['id_attribute'];
83 $emailAttr = $this->config['email_attribute'];
84 $displayNameAttr = $this->config['display_name_attribute'];
85 $thumbnailAttr = $this->config['thumbnail_attribute'];
87 $user = $this->getUserWithAttributes($userName, array_filter([
88 'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
95 $userCn = $this->getUserResponseProperty($user, 'cn', null);
97 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
98 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
100 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
101 'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
104 if ($this->config['dump_user_details']) {
105 throw new JsonDebugException([
106 'details_from_ldap' => $user,
107 'details_bookstack_parsed' => $formatted,
115 * Get a property from an LDAP user response fetch.
116 * Handles properties potentially being part of an array.
117 * If the given key is prefixed with 'BIN;', that indicator will be stripped
118 * from the key and any fetched values will be converted from binary to hex.
120 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
122 $isBinary = str_starts_with($propertyKey, 'BIN;');
123 $propertyKey = strtolower($propertyKey);
124 $value = $defaultValue;
127 $propertyKey = substr($propertyKey, strlen('BIN;'));
130 if (isset($userDetails[$propertyKey])) {
131 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
133 $value = bin2hex($value);
141 * Check if the given credentials are valid for the given user.
143 * @throws LdapException
145 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
147 if (is_null($ldapUserDetails)) {
151 $ldapConnection = $this->getConnection();
154 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
155 } catch (ErrorException $e) {
163 * Bind the system user to the LDAP connection using the given credentials
164 * otherwise anonymous access is attempted.
166 * @param resource|\LDAP\Connection $connection
168 * @throws LdapException
170 protected function bindSystemUser($connection): void
172 $ldapDn = $this->config['dn'];
173 $ldapPass = $this->config['pass'];
175 $isAnonymous = ($ldapDn === false || $ldapPass === false);
177 $ldapBind = $this->ldap->bind($connection);
179 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
183 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
188 * Get the connection to the LDAP server.
189 * Creates a new connection if one does not exist.
191 * @throws LdapException
193 * @return resource|\LDAP\Connection
195 protected function getConnection()
197 if ($this->ldapConnection !== null) {
198 return $this->ldapConnection;
201 // Check LDAP extension in installed
202 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
203 throw new LdapException(trans('errors.ldap_extension_not_installed'));
206 // Disable certificate verification.
207 // This option works globally and must be set before a connection is created.
208 if ($this->config['tls_insecure']) {
209 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
212 // Configure any user-provided CA cert files for LDAP.
213 // This option works globally and must be set before a connection is created.
214 if ($this->config['tls_ca_cert']) {
215 $this->configureTlsCaCerts($this->config['tls_ca_cert']);
218 $ldapHost = $this->parseServerString($this->config['server']);
219 $ldapConnection = $this->ldap->connect($ldapHost);
221 if ($ldapConnection === false) {
222 throw new LdapException(trans('errors.ldap_cannot_connect'));
225 // Set any required options
226 if ($this->config['version']) {
227 $this->ldap->setVersion($ldapConnection, $this->config['version']);
230 // Start and verify TLS if it's enabled
231 if ($this->config['start_tls']) {
233 $started = $this->ldap->startTls($ldapConnection);
234 } catch (\Exception $exception) {
235 $error = $exception->getMessage() . ' :: ' . ldap_error($ldapConnection);
236 ldap_get_option($ldapConnection, LDAP_OPT_DIAGNOSTIC_MESSAGE, $detail);
237 Log::info("LDAP STARTTLS failure: {$error} {$detail}");
238 throw new LdapException('Could not start TLS connection. Further details in the application log.');
241 throw new LdapException('Could not start TLS connection');
245 $this->ldapConnection = $ldapConnection;
247 return $this->ldapConnection;
251 * Configure TLS CA certs globally for ldap use.
252 * This will detect if the given path is a directory or file, and set the relevant
253 * LDAP TLS options appropriately otherwise throw an exception if no file/folder found.
255 * Note: When using a folder, certificates are expected to be correctly named by hash
256 * which can be done via the c_rehash utility.
258 * @throws LdapException
260 protected function configureTlsCaCerts(string $caCertPath): void
262 $errMessage = "Provided path [{$caCertPath}] for LDAP TLS CA certs could not be resolved to an existing location";
263 $path = realpath($caCertPath);
264 if ($path === false) {
265 throw new LdapException($errMessage);
269 $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTDIR, $path);
270 } else if (is_file($path)) {
271 $this->ldap->setOption(null, LDAP_OPT_X_TLS_CACERTFILE, $path);
273 throw new LdapException($errMessage);
278 * Parse an LDAP server string and return the host suitable for a connection.
279 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
281 protected function parseServerString(string $serverString): string
283 if (str_starts_with($serverString, 'ldaps://') || str_starts_with($serverString, 'ldap://')) {
284 return $serverString;
287 return "ldap://{$serverString}";
291 * Build a filter string by injecting common variables.
292 * Both "${var}" and "{var}" style placeholders are supported.
293 * Dollar based are old format but supported for compatibility.
295 protected function buildFilter(string $filterString, array $attrs): string
298 foreach ($attrs as $key => $attrText) {
299 $escapedText = $this->ldap->escape($attrText);
300 $oldVarKey = '${' . $key . '}';
301 $newVarKey = '{' . $key . '}';
302 $newAttrs[$oldVarKey] = $escapedText;
303 $newAttrs[$newVarKey] = $escapedText;
306 return strtr($filterString, $newAttrs);
310 * Get the groups a user is a part of on ldap.
312 * @throws LdapException
313 * @throws JsonDebugException
315 public function getUserGroups(string $userName): array
317 $groupsAttr = $this->config['group_attribute'];
318 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
320 if ($user === null) {
324 $userGroups = $this->groupFilter($user);
325 $allGroups = $this->getGroupsRecursive($userGroups, []);
327 if ($this->config['dump_user_groups']) {
328 throw new JsonDebugException([
329 'details_from_ldap' => $user,
330 'parsed_direct_user_groups' => $userGroups,
331 'parsed_recursive_user_groups' => $allGroups,
339 * Get the parent groups of an array of groups.
341 * @throws LdapException
343 private function getGroupsRecursive(array $groupsArray, array $checked): array
346 foreach ($groupsArray as $groupName) {
347 if (in_array($groupName, $checked)) {
351 $parentGroups = $this->getGroupGroups($groupName);
352 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
353 $checked[] = $groupName;
356 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
358 if (empty($groupsToAdd)) {
362 return $this->getGroupsRecursive($groupsArray, $checked);
366 * Get the parent groups of a single group.
368 * @throws LdapException
370 private function getGroupGroups(string $groupName): array
372 $ldapConnection = $this->getConnection();
373 $this->bindSystemUser($ldapConnection);
375 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
376 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
378 $baseDn = $this->config['base_dn'];
379 $groupsAttr = strtolower($this->config['group_attribute']);
381 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
382 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
383 if ($groups['count'] === 0) {
387 return $this->groupFilter($groups[0]);
391 * Filter out LDAP CN and DN language in a ldap search return.
392 * Gets the base CN (common name) of the string.
394 protected function groupFilter(array $userGroupSearchResponse): array
396 $groupsAttr = strtolower($this->config['group_attribute']);
400 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
401 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
404 for ($i = 0; $i < $count; $i++) {
405 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
406 if (!in_array($dnComponents[0], $ldapGroups)) {
407 $ldapGroups[] = $dnComponents[0];
415 * Sync the LDAP groups to the user roles for the current user.
417 * @throws LdapException
418 * @throws JsonDebugException
420 public function syncGroups(User $user, string $username): void
422 $userLdapGroups = $this->getUserGroups($username);
423 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
427 * Save and attach an avatar image, if found in the ldap details, and attach
428 * to the given user model.
430 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
432 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
437 $imageData = $ldapUserDetails['avatar'];
438 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
439 } catch (\Exception $exception) {
440 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");