3 namespace BookStack\Auth\Access;
5 use BookStack\Auth\User;
6 use BookStack\Exceptions\JsonDebugException;
7 use BookStack\Exceptions\LdapException;
8 use BookStack\Uploads\UserAvatars;
10 use Illuminate\Support\Facades\Log;
14 * Handles any app-specific LDAP tasks.
19 protected GroupSyncService $groupSyncService;
20 protected UserAvatars $userAvatars;
25 protected $ldapConnection;
27 protected array $config;
28 protected bool $enabled;
31 * LdapService constructor.
33 public function __construct(Ldap $ldap, UserAvatars $userAvatars, GroupSyncService $groupSyncService)
36 $this->userAvatars = $userAvatars;
37 $this->groupSyncService = $groupSyncService;
38 $this->config = config('services.ldap');
39 $this->enabled = config('auth.method') === 'ldap';
43 * Check if groups should be synced.
45 public function shouldSyncGroups(): bool
47 return $this->enabled && $this->config['user_to_groups'] !== false;
51 * Search for attributes for a specific user on the ldap.
53 * @throws LdapException
55 private function getUserWithAttributes(string $userName, array $attributes): ?array
57 $ldapConnection = $this->getConnection();
58 $this->bindSystemUser($ldapConnection);
61 foreach ($attributes as $index => $attribute) {
62 if (strpos($attribute, 'BIN;') === 0) {
63 $attributes[$index] = substr($attribute, strlen('BIN;'));
68 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
69 $baseDn = $this->config['base_dn'];
71 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
72 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
73 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
74 if ($users['count'] === 0) {
82 * Get the details of a user from LDAP using the given username.
83 * User found via configurable user filter.
85 * @throws LdapException
87 public function getUserDetails(string $userName): ?array
89 $idAttr = $this->config['id_attribute'];
90 $emailAttr = $this->config['email_attribute'];
91 $displayNameAttr = $this->config['display_name_attribute'];
92 $thumbnailAttr = $this->config['thumbnail_attribute'];
94 $user = $this->getUserWithAttributes($userName, array_filter([
95 'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
102 $userCn = $this->getUserResponseProperty($user, 'cn', null);
104 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
105 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
107 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
108 'avatar' => $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
111 if ($this->config['dump_user_details']) {
112 throw new JsonDebugException([
113 'details_from_ldap' => $user,
114 'details_bookstack_parsed' => $formatted,
122 * Get a property from an LDAP user response fetch.
123 * Handles properties potentially being part of an array.
124 * If the given key is prefixed with 'BIN;', that indicator will be stripped
125 * from the key and any fetched values will be converted from binary to hex.
127 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
129 $isBinary = strpos($propertyKey, 'BIN;') === 0;
130 $propertyKey = strtolower($propertyKey);
131 $value = $defaultValue;
134 $propertyKey = substr($propertyKey, strlen('BIN;'));
137 if (isset($userDetails[$propertyKey])) {
138 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
140 $value = bin2hex($value);
148 * Check if the given credentials are valid for the given user.
150 * @throws LdapException
152 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
154 if (is_null($ldapUserDetails)) {
158 $ldapConnection = $this->getConnection();
161 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
162 } catch (ErrorException $e) {
170 * Bind the system user to the LDAP connection using the given credentials
171 * otherwise anonymous access is attempted.
173 * @param resource $connection
175 * @throws LdapException
177 protected function bindSystemUser($connection)
179 $ldapDn = $this->config['dn'];
180 $ldapPass = $this->config['pass'];
182 $isAnonymous = ($ldapDn === false || $ldapPass === false);
184 $ldapBind = $this->ldap->bind($connection);
186 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
190 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
195 * Get the connection to the LDAP server.
196 * Creates a new connection if one does not exist.
198 * @throws LdapException
202 protected function getConnection()
204 if ($this->ldapConnection !== null) {
205 return $this->ldapConnection;
208 // Check LDAP extension in installed
209 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
210 throw new LdapException(trans('errors.ldap_extension_not_installed'));
213 // Disable certificate verification.
214 // This option works globally and must be set before a connection is created.
215 if ($this->config['tls_insecure']) {
216 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
219 $serverDetails = $this->parseEnvironmentServer($this->config['server']);
220 $this->ldapConnection = $this->prepareServerConnection($serverDetails);
222 return $this->ldapConnection;
226 * Processes an array of received servers and returns the first working connection.
228 * @param array $serverDetails
230 * @throws LdapException
232 protected function prepareServerConnection(array $serverDetails)
234 $lastException = null;
235 foreach ($serverDetails as $server) {
237 $ldapConnection = $this->ldap->connect($server['host'], $server['port']);
239 if (!$ldapConnection) {
240 throw new LdapException(trans('errors.ldap_cannot_connect'));
243 // Set any required options
244 if ($this->config['version']) {
245 $this->ldap->setVersion($ldapConnection, $this->config['version']);
248 // Start and verify TLS if it's enabled
249 if ($this->config['start_tls']) {
251 $tlsStarted = $this->ldap->startTls($ldapConnection);
252 } catch (ErrorException $exception) {
257 throw new LdapException('Could not start TLS connection');
261 return $ldapConnection;
262 } catch (LdapException $exception) {
263 $lastException = $exception;
267 throw $lastException;
271 * Parse environment variable with LDAP server and returns an array of recognized servers.
272 * If you need to use multiple addresses, separate them with a semicolon.
273 * Ex: 'ldap.example.com:8069;ldaps://ldap.example.com'
275 protected function parseEnvironmentServer(string $environmentServer): array
277 $explodedEnvironmentServer = explode(';', $environmentServer);
278 $result_servers = [];
280 foreach ($explodedEnvironmentServer as $serverString) {
281 $result_servers[] = $this->parseServerString($serverString);
284 return $result_servers;
288 * Parse a LDAP server string and return the host and port for a connection.
289 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
291 protected function parseServerString(string $serverString): array
293 $serverNameParts = explode(':', $serverString);
295 // If we have a protocol just return the full string since PHP will ignore a separate port.
296 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
297 return ['host' => $serverString, 'port' => 389];
300 // Otherwise, extract the port out
301 $hostName = $serverNameParts[0];
302 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
304 return ['host' => $hostName, 'port' => $ldapPort];
308 * Build a filter string by injecting common variables.
310 protected function buildFilter(string $filterString, array $attrs): string
313 foreach ($attrs as $key => $attrText) {
314 $newKey = '${' . $key . '}';
315 $newAttrs[$newKey] = $this->ldap->escape($attrText);
318 return strtr($filterString, $newAttrs);
322 * Get the groups a user is a part of on ldap.
324 * @throws LdapException
325 * @throws JsonDebugException
327 public function getUserGroups(string $userName): array
329 $groupsAttr = $this->config['group_attribute'];
330 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
332 if ($user === null) {
336 $userGroups = $this->groupFilter($user);
337 $allGroups = $this->getGroupsRecursive($userGroups, []);
339 if ($this->config['dump_user_groups']) {
340 throw new JsonDebugException([
341 'details_from_ldap' => $user,
342 'parsed_direct_user_groups' => $userGroups,
343 'parsed_recursive_user_groups' => $allGroups,
351 * Get the parent groups of an array of groups.
353 * @throws LdapException
355 private function getGroupsRecursive(array $groupsArray, array $checked): array
358 foreach ($groupsArray as $groupName) {
359 if (in_array($groupName, $checked)) {
363 $parentGroups = $this->getGroupGroups($groupName);
364 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
365 $checked[] = $groupName;
368 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
370 if (empty($groupsToAdd)) {
374 return $this->getGroupsRecursive($groupsArray, $checked);
378 * Get the parent groups of a single group.
380 * @throws LdapException
382 private function getGroupGroups(string $groupName): array
384 $ldapConnection = $this->getConnection();
385 $this->bindSystemUser($ldapConnection);
387 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
388 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
390 $baseDn = $this->config['base_dn'];
391 $groupsAttr = strtolower($this->config['group_attribute']);
393 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
394 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
395 if ($groups['count'] === 0) {
399 return $this->groupFilter($groups[0]);
403 * Filter out LDAP CN and DN language in a ldap search return.
404 * Gets the base CN (common name) of the string.
406 protected function groupFilter(array $userGroupSearchResponse): array
408 $groupsAttr = strtolower($this->config['group_attribute']);
412 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
413 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
416 for ($i = 0; $i < $count; $i++) {
417 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
418 if (!in_array($dnComponents[0], $ldapGroups)) {
419 $ldapGroups[] = $dnComponents[0];
427 * Sync the LDAP groups to the user roles for the current user.
429 * @throws LdapException
430 * @throws JsonDebugException
432 public function syncGroups(User $user, string $username)
434 $userLdapGroups = $this->getUserGroups($username);
435 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
439 * Save and attach an avatar image, if found in the ldap details, and attach
440 * to the given user model.
442 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
444 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
449 $imageData = $ldapUserDetails['avatar'];
450 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
451 } catch (\Exception $exception) {
452 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");