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;
20 protected $ldapConnection;
21 protected $userAvatars;
26 * LdapService constructor.
28 public function __construct(Ldap $ldap, UserAvatars $userAvatars, GroupSyncService $groupSyncService)
31 $this->userAvatars = $userAvatars;
32 $this->groupSyncService = $groupSyncService;
33 $this->config = config('services.ldap');
34 $this->enabled = config('auth.method') === 'ldap';
38 * Check if groups should be synced.
40 public function shouldSyncGroups(): bool
42 return $this->enabled && $this->config['user_to_groups'] !== false;
46 * Search for attributes for a specific user on the ldap.
48 * @throws LdapException
50 private function getUserWithAttributes(string $userName, array $attributes): ?array
52 $ldapConnection = $this->getConnection();
53 $this->bindSystemUser($ldapConnection);
56 foreach ($attributes as $index => $attribute) {
57 if (strpos($attribute, 'BIN;') === 0) {
58 $attributes[$index] = substr($attribute, strlen('BIN;'));
63 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
64 $baseDn = $this->config['base_dn'];
66 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
67 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
68 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
69 if ($users['count'] === 0) {
77 * Get the details of a user from LDAP using the given username.
78 * User found via configurable user filter.
80 * @throws LdapException
82 public function getUserDetails(string $userName): ?array
84 $idAttr = $this->config['id_attribute'];
85 $emailAttr = $this->config['email_attribute'];
86 $displayNameAttr = $this->config['display_name_attribute'];
87 $thumbnailAttr = $this->config['thumbnail_attribute'];
89 $user = $this->getUserWithAttributes($userName, array_filter([
90 'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
97 $userCn = $this->getUserResponseProperty($user, 'cn', null);
99 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
100 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
102 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
103 'avatar'=> $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
106 if ($this->config['dump_user_details']) {
107 throw new JsonDebugException([
108 'details_from_ldap' => $user,
109 'details_bookstack_parsed' => $formatted,
117 * Get a property from an LDAP user response fetch.
118 * Handles properties potentially being part of an array.
119 * If the given key is prefixed with 'BIN;', that indicator will be stripped
120 * from the key and any fetched values will be converted from binary to hex.
122 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
124 $isBinary = strpos($propertyKey, 'BIN;') === 0;
125 $propertyKey = strtolower($propertyKey);
126 $value = $defaultValue;
129 $propertyKey = substr($propertyKey, strlen('BIN;'));
132 if (isset($userDetails[$propertyKey])) {
133 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
135 $value = bin2hex($value);
143 * Check if the given credentials are valid for the given user.
145 * @throws LdapException
147 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
149 if (is_null($ldapUserDetails)) {
153 $ldapConnection = $this->getConnection();
156 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
157 } catch (ErrorException $e) {
165 * Bind the system user to the LDAP connection using the given credentials
166 * otherwise anonymous access is attempted.
170 * @throws LdapException
172 protected function bindSystemUser($connection)
174 $ldapDn = $this->config['dn'];
175 $ldapPass = $this->config['pass'];
177 $isAnonymous = ($ldapDn === false || $ldapPass === false);
179 $ldapBind = $this->ldap->bind($connection);
181 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
185 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
190 * Get the connection to the LDAP server.
191 * Creates a new connection if one does not exist.
193 * @throws LdapException
197 protected function getConnection()
199 if ($this->ldapConnection !== null) {
200 return $this->ldapConnection;
203 // Check LDAP extension in installed
204 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
205 throw new LdapException(trans('errors.ldap_extension_not_installed'));
208 // Disable certificate verification.
209 // This option works globally and must be set before a connection is created.
210 if ($this->config['tls_insecure']) {
211 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
214 $serverDetails = $this->parseServerString($this->config['server']);
215 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
217 if ($ldapConnection === false) {
218 throw new LdapException(trans('errors.ldap_cannot_connect'));
221 // Set any required options
222 if ($this->config['version']) {
223 $this->ldap->setVersion($ldapConnection, $this->config['version']);
226 // Start and verify TLS if it's enabled
227 if ($this->config['start_tls']) {
228 $started = $this->ldap->startTls($ldapConnection);
230 throw new LdapException('Could not start TLS connection');
234 $this->ldapConnection = $ldapConnection;
236 return $this->ldapConnection;
240 * Parse a LDAP server string and return the host and port for a connection.
241 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
243 protected function parseServerString(string $serverString): array
245 $serverNameParts = explode(':', $serverString);
247 // If we have a protocol just return the full string since PHP will ignore a separate port.
248 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
249 return ['host' => $serverString, 'port' => 389];
252 // Otherwise, extract the port out
253 $hostName = $serverNameParts[0];
254 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
256 return ['host' => $hostName, 'port' => $ldapPort];
260 * Build a filter string by injecting common variables.
262 protected function buildFilter(string $filterString, array $attrs): string
265 foreach ($attrs as $key => $attrText) {
266 $newKey = '${' . $key . '}';
267 $newAttrs[$newKey] = $this->ldap->escape($attrText);
270 return strtr($filterString, $newAttrs);
274 * Get the groups a user is a part of on ldap.
276 * @throws LdapException
278 public function getUserGroups(string $userName): array
280 $groupsAttr = $this->config['group_attribute'];
281 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
283 if ($user === null) {
287 $userGroups = $this->groupFilter($user);
289 return $this->getGroupsRecursive($userGroups, []);
293 * Get the parent groups of an array of groups.
295 * @throws LdapException
297 private function getGroupsRecursive(array $groupsArray, array $checked): array
300 foreach ($groupsArray as $groupName) {
301 if (in_array($groupName, $checked)) {
305 $parentGroups = $this->getGroupGroups($groupName);
306 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
307 $checked[] = $groupName;
310 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
312 if (empty($groupsToAdd)) {
316 return $this->getGroupsRecursive($groupsArray, $checked);
320 * Get the parent groups of a single group.
322 * @throws LdapException
324 private function getGroupGroups(string $groupName): array
326 $ldapConnection = $this->getConnection();
327 $this->bindSystemUser($ldapConnection);
329 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
330 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
332 $baseDn = $this->config['base_dn'];
333 $groupsAttr = strtolower($this->config['group_attribute']);
335 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
336 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
337 if ($groups['count'] === 0) {
341 return $this->groupFilter($groups[0]);
345 * Filter out LDAP CN and DN language in a ldap search return.
346 * Gets the base CN (common name) of the string.
348 protected function groupFilter(array $userGroupSearchResponse): array
350 $groupsAttr = strtolower($this->config['group_attribute']);
354 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
355 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
358 for ($i = 0; $i < $count; $i++) {
359 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
360 if (!in_array($dnComponents[0], $ldapGroups)) {
361 $ldapGroups[] = $dnComponents[0];
369 * Sync the LDAP groups to the user roles for the current user.
371 * @throws LdapException
373 public function syncGroups(User $user, string $username)
375 $userLdapGroups = $this->getUserGroups($username);
376 $this->groupSyncService->syncUserWithFoundGroups($user, $userLdapGroups, $this->config['remove_from_groups']);
380 * Save and attach an avatar image, if found in the ldap details, and attach
381 * to the given user model.
383 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
385 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
390 $imageData = $ldapUserDetails['avatar'];
391 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
392 } catch (\Exception $exception) {
393 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");