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->parseServerString($this->config['server']);
220 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
222 if ($ldapConnection === false) {
223 throw new LdapException(trans('errors.ldap_cannot_connect'));
226 // Set any required options
227 if ($this->config['version']) {
228 $this->ldap->setVersion($ldapConnection, $this->config['version']);
231 // Start and verify TLS if it's enabled
232 if ($this->config['start_tls']) {
233 $started = $this->ldap->startTls($ldapConnection);
235 throw new LdapException('Could not start TLS connection');
239 $this->ldapConnection = $ldapConnection;
241 return $this->ldapConnection;
245 * Parse a LDAP server string and return the host and port for a connection.
246 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
248 protected function parseServerString(string $serverString): array
250 $serverNameParts = explode(':', $serverString);
252 // If we have a protocol just return the full string since PHP will ignore a separate port.
253 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
254 return ['host' => $serverString, 'port' => 389];
257 // Otherwise, extract the port out
258 $hostName = $serverNameParts[0];
259 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
261 return ['host' => $hostName, 'port' => $ldapPort];
265 * Build a filter string by injecting common variables.
267 protected function buildFilter(string $filterString, array $attrs): string
270 foreach ($attrs as $key => $attrText) {
271 $newKey = '${' . $key . '}';
272 $newAttrs[$newKey] = $this->ldap->escape($attrText);
275 return strtr($filterString, $newAttrs);
279 * Get the groups a user is a part of on ldap.
281 * @throws LdapException
282 * @throws JsonDebugException
284 public function getUserGroups(string $userName): array
286 $groupsAttr = $this->config['group_attribute'];
287 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
289 if ($user === null) {
293 $userGroups = $this->groupFilter($user);
294 $allGroups = $this->getGroupsRecursive($userGroups, []);
296 if ($this->config['dump_user_groups']) {
297 throw new JsonDebugException([
298 'details_from_ldap' => $user,
299 'parsed_direct_user_groups' => $userGroups,
300 'parsed_recursive_user_groups' => $allGroups,
308 * Get the parent groups of an array of groups.
310 * @throws LdapException
312 private function getGroupsRecursive(array $groupsArray, array $checked): array
315 foreach ($groupsArray as $groupName) {
316 if (in_array($groupName, $checked)) {
320 $parentGroups = $this->getGroupGroups($groupName);
321 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
322 $checked[] = $groupName;
325 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
327 if (empty($groupsToAdd)) {
331 return $this->getGroupsRecursive($groupsArray, $checked);
335 * Get the parent groups of a single group.
337 * @throws LdapException
339 private function getGroupGroups(string $groupName): array
341 $ldapConnection = $this->getConnection();
342 $this->bindSystemUser($ldapConnection);
344 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
345 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
347 $baseDn = $this->config['base_dn'];
348 $groupsAttr = strtolower($this->config['group_attribute']);
350 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
351 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
352 if ($groups['count'] === 0) {
356 return $this->groupFilter($groups[0]);
360 * Filter out LDAP CN and DN language in a ldap search return.
361 * Gets the base CN (common name) of the string.
363 protected function groupFilter(array $userGroupSearchResponse): array
365 $groupsAttr = strtolower($this->config['group_attribute']);
369 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
370 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
373 for ($i = 0; $i < $count; $i++) {
374 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
375 if (!in_array($dnComponents[0], $ldapGroups)) {
376 $ldapGroups[] = $dnComponents[0];
384 * Sync the LDAP groups to the user roles for the current user.
386 * @throws LdapException
387 * @throws JsonDebugException
389 public function syncGroups(User $user, string $username)
391 $userLdapGroups = $this->getUserGroups($username);
392 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
396 * Save and attach an avatar image, if found in the ldap details, and attach
397 * to the given user model.
399 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
401 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
406 $imageData = $ldapUserDetails['avatar'];
407 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
408 } catch (\Exception $exception) {
409 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");