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.
16 class LdapService extends ExternalAuthService
19 protected $ldapConnection;
20 protected $userAvatars;
25 * LdapService constructor.
27 public function __construct(Ldap $ldap, UserAvatars $userAvatars)
30 $this->userAvatars = $userAvatars;
31 $this->config = config('services.ldap');
32 $this->enabled = config('auth.method') === 'ldap';
36 * Check if groups should be synced.
40 public function shouldSyncGroups()
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);
288 $userGroups = $this->getGroupsRecursive($userGroups, []);
294 * Get the parent groups of an array of groups.
296 * @throws LdapException
298 private function getGroupsRecursive(array $groupsArray, array $checked): array
301 foreach ($groupsArray as $groupName) {
302 if (in_array($groupName, $checked)) {
306 $parentGroups = $this->getGroupGroups($groupName);
307 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
308 $checked[] = $groupName;
311 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
313 if (empty($groupsToAdd)) {
317 return $this->getGroupsRecursive($groupsArray, $checked);
321 * Get the parent groups of a single group.
323 * @throws LdapException
325 private function getGroupGroups(string $groupName): array
327 $ldapConnection = $this->getConnection();
328 $this->bindSystemUser($ldapConnection);
330 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
331 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
333 $baseDn = $this->config['base_dn'];
334 $groupsAttr = strtolower($this->config['group_attribute']);
336 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
337 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
338 if ($groups['count'] === 0) {
342 return $this->groupFilter($groups[0]);
346 * Filter out LDAP CN and DN language in a ldap search return.
347 * Gets the base CN (common name) of the string.
349 protected function groupFilter(array $userGroupSearchResponse): array
351 $groupsAttr = strtolower($this->config['group_attribute']);
355 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
356 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
359 for ($i = 0; $i < $count; $i++) {
360 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
361 if (!in_array($dnComponents[0], $ldapGroups)) {
362 $ldapGroups[] = $dnComponents[0];
370 * Sync the LDAP groups to the user roles for the current user.
372 * @throws LdapException
374 public function syncGroups(User $user, string $username)
376 $userLdapGroups = $this->getUserGroups($username);
377 $this->syncWithGroups($user, $userLdapGroups);
381 * Save and attach an avatar image, if found in the ldap details, and attach
382 * to the given user model.
384 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
386 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
391 $imageData = $ldapUserDetails['avatar'];
392 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
393 } catch (\Exception $exception) {
394 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");