1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\LdapException;
6 use BookStack\Uploads\UserAvatars;
8 use Illuminate\Support\Facades\Log;
12 * Handles any app-specific LDAP tasks.
14 class LdapService extends ExternalAuthService
18 protected $ldapConnection;
19 protected $userAvatars;
24 * LdapService constructor.
26 public function __construct(Ldap $ldap, UserAvatars $userAvatars)
29 $this->userAvatars = $userAvatars;
30 $this->config = config('services.ldap');
31 $this->enabled = config('auth.method') === 'ldap';
35 * Check if groups should be synced.
38 public function shouldSyncGroups()
40 return $this->enabled && $this->config['user_to_groups'] !== false;
44 * Search for attributes for a specific user on the ldap.
45 * @throws LdapException
47 private function getUserWithAttributes(string $userName, array $attributes): ?array
49 $ldapConnection = $this->getConnection();
50 $this->bindSystemUser($ldapConnection);
53 foreach ($attributes as $index => $attribute) {
54 if (strpos($attribute, 'BIN;') === 0) {
55 $attributes[$index] = substr($attribute, strlen('BIN;'));
60 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
61 $baseDn = $this->config['base_dn'];
63 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
64 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
65 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
66 if ($users['count'] === 0) {
74 * Get the details of a user from LDAP using the given username.
75 * User found via configurable user filter.
76 * @throws LdapException
78 public function getUserDetails(string $userName): ?array
80 $idAttr = $this->config['id_attribute'];
81 $emailAttr = $this->config['email_attribute'];
82 $displayNameAttr = $this->config['display_name_attribute'];
83 $thumbnailAttr = $this->config['thumbnail_attribute'];
85 $user = $this->getUserWithAttributes($userName, array_filter([
86 'cn', 'dn', $idAttr, $emailAttr, $displayNameAttr, $thumbnailAttr,
93 $userCn = $this->getUserResponseProperty($user, 'cn', null);
95 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
96 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
98 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
99 'avatar'=> $thumbnailAttr ? $this->getUserResponseProperty($user, $thumbnailAttr, null) : null,
102 if ($this->config['dump_user_details']) {
103 throw new JsonDebugException([
104 'details_from_ldap' => $user,
105 'details_bookstack_parsed' => $formatted,
113 * Get a property from an LDAP user response fetch.
114 * Handles properties potentially being part of an array.
115 * If the given key is prefixed with 'BIN;', that indicator will be stripped
116 * from the key and any fetched values will be converted from binary to hex.
118 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
120 $isBinary = strpos($propertyKey, 'BIN;') === 0;
121 $propertyKey = strtolower($propertyKey);
122 $value = $defaultValue;
125 $propertyKey = substr($propertyKey, strlen('BIN;'));
128 if (isset($userDetails[$propertyKey])) {
129 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
131 $value = bin2hex($value);
139 * Check if the given credentials are valid for the given user.
140 * @throws LdapException
142 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
144 if (is_null($ldapUserDetails)) {
148 $ldapConnection = $this->getConnection();
150 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
151 } catch (ErrorException $e) {
159 * Bind the system user to the LDAP connection using the given credentials
160 * otherwise anonymous access is attempted.
162 * @throws LdapException
164 protected function bindSystemUser($connection)
166 $ldapDn = $this->config['dn'];
167 $ldapPass = $this->config['pass'];
169 $isAnonymous = ($ldapDn === false || $ldapPass === false);
171 $ldapBind = $this->ldap->bind($connection);
173 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
177 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
182 * Get the connection to the LDAP server.
183 * Creates a new connection if one does not exist.
185 * @throws LdapException
187 protected function getConnection()
189 if ($this->ldapConnection !== null) {
190 return $this->ldapConnection;
193 // Check LDAP extension in installed
194 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
195 throw new LdapException(trans('errors.ldap_extension_not_installed'));
198 // Disable certificate verification.
199 // This option works globally and must be set before a connection is created.
200 if ($this->config['tls_insecure']) {
201 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
204 $serverDetails = $this->parseServerString($this->config['server']);
205 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
207 if ($ldapConnection === false) {
208 throw new LdapException(trans('errors.ldap_cannot_connect'));
211 // Set any required options
212 if ($this->config['version']) {
213 $this->ldap->setVersion($ldapConnection, $this->config['version']);
216 // Start and verify TLS if it's enabled
217 if ($this->config['start_tls']) {
218 $started = $this->ldap->startTls($ldapConnection);
220 throw new LdapException('Could not start TLS connection');
224 $this->ldapConnection = $ldapConnection;
225 return $this->ldapConnection;
229 * Parse a LDAP server string and return the host and port for a connection.
230 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
232 protected function parseServerString(string $serverString): array
234 $serverNameParts = explode(':', $serverString);
236 // If we have a protocol just return the full string since PHP will ignore a separate port.
237 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
238 return ['host' => $serverString, 'port' => 389];
241 // Otherwise, extract the port out
242 $hostName = $serverNameParts[0];
243 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
244 return ['host' => $hostName, 'port' => $ldapPort];
248 * Build a filter string by injecting common variables.
250 protected function buildFilter(string $filterString, array $attrs): string
253 foreach ($attrs as $key => $attrText) {
254 $newKey = '${' . $key . '}';
255 $newAttrs[$newKey] = $this->ldap->escape($attrText);
257 return strtr($filterString, $newAttrs);
261 * Get the groups a user is a part of on ldap.
262 * @throws LdapException
264 public function getUserGroups(string $userName): array
266 $groupsAttr = $this->config['group_attribute'];
267 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
269 if ($user === null) {
273 $userGroups = $this->groupFilter($user);
274 $userGroups = $this->getGroupsRecursive($userGroups, []);
279 * Get the parent groups of an array of groups.
280 * @throws LdapException
282 private function getGroupsRecursive(array $groupsArray, array $checked): array
285 foreach ($groupsArray as $groupName) {
286 if (in_array($groupName, $checked)) {
290 $parentGroups = $this->getGroupGroups($groupName);
291 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
292 $checked[] = $groupName;
295 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
297 if (empty($groupsToAdd)) {
301 return $this->getGroupsRecursive($groupsArray, $checked);
305 * Get the parent groups of a single group.
306 * @throws LdapException
308 private function getGroupGroups(string $groupName): array
310 $ldapConnection = $this->getConnection();
311 $this->bindSystemUser($ldapConnection);
313 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
314 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
316 $baseDn = $this->config['base_dn'];
317 $groupsAttr = strtolower($this->config['group_attribute']);
319 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
320 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
321 if ($groups['count'] === 0) {
325 return $this->groupFilter($groups[0]);
329 * Filter out LDAP CN and DN language in a ldap search return.
330 * Gets the base CN (common name) of the string.
332 protected function groupFilter(array $userGroupSearchResponse): array
334 $groupsAttr = strtolower($this->config['group_attribute']);
338 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
339 $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
342 for ($i = 0; $i < $count; $i++) {
343 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
344 if (!in_array($dnComponents[0], $ldapGroups)) {
345 $ldapGroups[] = $dnComponents[0];
353 * Sync the LDAP groups to the user roles for the current user.
354 * @throws LdapException
356 public function syncGroups(User $user, string $username)
358 $userLdapGroups = $this->getUserGroups($username);
359 $this->syncWithGroups($user, $userLdapGroups);
363 * Save and attach an avatar image, if found in the ldap details, and attach
364 * to the given user model.
366 public function saveAndAttachAvatar(User $user, array $ldapUserDetails): void
368 if (is_null(config('services.ldap.thumbnail_attribute')) || is_null($ldapUserDetails['avatar'])) {
373 $imageData = $ldapUserDetails['avatar'];
374 $this->userAvatars->assignToUserFromExistingData($user, $imageData, 'jpg');
375 } catch (\Exception $exception) {
376 Log::info("Failed to use avatar image from LDAP data for user id {$user->id}");