1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Exceptions\JsonDebugException;
5 use BookStack\Exceptions\LdapException;
10 * Handles any app-specific LDAP tasks.
12 class LdapService extends ExternalAuthService
16 protected $ldapConnection;
21 * LdapService constructor.
23 public function __construct(Ldap $ldap)
26 $this->config = config('services.ldap');
27 $this->enabled = config('auth.method') === 'ldap';
31 * Check if groups should be synced.
34 public function shouldSyncGroups()
36 return $this->enabled && $this->config['user_to_groups'] !== false;
40 * Search for attributes for a specific user on the ldap.
41 * @throws LdapException
43 private function getUserWithAttributes(string $userName, array $attributes): ?array
45 $ldapConnection = $this->getConnection();
46 $this->bindSystemUser($ldapConnection);
49 foreach ($attributes as $index => $attribute) {
50 if (strpos($attribute, 'BIN;') === 0) {
51 $attributes[$index] = substr($attribute, strlen('BIN;'));
56 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
57 $baseDn = $this->config['base_dn'];
59 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
60 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
61 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
62 if ($users['count'] === 0) {
70 * Get the details of a user from LDAP using the given username.
71 * User found via configurable user filter.
72 * @throws LdapException
74 public function getUserDetails(string $userName): ?array
76 $idAttr = $this->config['id_attribute'];
77 $emailAttr = $this->config['email_attribute'];
78 $displayNameAttr = $this->config['display_name_attribute'];
80 $user = $this->getUserWithAttributes($userName, ['cn', 'dn', $idAttr, $emailAttr, $displayNameAttr]);
86 $userCn = $this->getUserResponseProperty($user, 'cn', null);
88 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
89 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
91 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
94 if ($this->config['dump_user_details']) {
95 throw new JsonDebugException([
96 'details_from_ldap' => $user,
97 'details_bookstack_parsed' => $formatted,
105 * Get a property from an LDAP user response fetch.
106 * Handles properties potentially being part of an array.
107 * If the given key is prefixed with 'BIN;', that indicator will be stripped
108 * from the key and any fetched values will be converted from binary to hex.
110 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
112 $isBinary = strpos($propertyKey, 'BIN;') === 0;
113 $propertyKey = strtolower($propertyKey);
114 $value = $defaultValue;
117 $propertyKey = substr($propertyKey, strlen('BIN;'));
120 if (isset($userDetails[$propertyKey])) {
121 $value = (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
123 $value = bin2hex($value);
131 * Check if the given credentials are valid for the given user.
132 * @throws LdapException
134 public function validateUserCredentials(?array $ldapUserDetails, string $password): bool
136 if (is_null($ldapUserDetails)) {
140 $ldapConnection = $this->getConnection();
142 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['dn'], $password);
143 } catch (ErrorException $e) {
151 * Bind the system user to the LDAP connection using the given credentials
152 * otherwise anonymous access is attempted.
154 * @throws LdapException
156 protected function bindSystemUser($connection)
158 $ldapDn = $this->config['dn'];
159 $ldapPass = $this->config['pass'];
161 $isAnonymous = ($ldapDn === false || $ldapPass === false);
163 $ldapBind = $this->ldap->bind($connection);
165 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
169 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
174 * Get the connection to the LDAP server.
175 * Creates a new connection if one does not exist.
177 * @throws LdapException
179 protected function getConnection()
181 if ($this->ldapConnection !== null) {
182 return $this->ldapConnection;
185 // Check LDAP extension in installed
186 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
187 throw new LdapException(trans('errors.ldap_extension_not_installed'));
190 // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
191 // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
192 if ($this->config['tls_insecure']) {
193 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
196 $serverDetails = $this->parseServerString($this->config['server']);
197 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
199 if ($ldapConnection === false) {
200 throw new LdapException(trans('errors.ldap_cannot_connect'));
203 // Set any required options
204 if ($this->config['version']) {
205 $this->ldap->setVersion($ldapConnection, $this->config['version']);
208 $this->ldapConnection = $ldapConnection;
209 return $this->ldapConnection;
213 * Parse a LDAP server string and return the host and port for a connection.
214 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
216 protected function parseServerString(string $serverString): array
218 $serverNameParts = explode(':', $serverString);
220 // If we have a protocol just return the full string since PHP will ignore a separate port.
221 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
222 return ['host' => $serverString, 'port' => 389];
225 // Otherwise, extract the port out
226 $hostName = $serverNameParts[0];
227 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
228 return ['host' => $hostName, 'port' => $ldapPort];
232 * Build a filter string by injecting common variables.
234 protected function buildFilter(string $filterString, array $attrs): string
237 foreach ($attrs as $key => $attrText) {
238 $newKey = '${' . $key . '}';
239 $newAttrs[$newKey] = $this->ldap->escape($attrText);
241 return strtr($filterString, $newAttrs);
245 * Get the groups a user is a part of on ldap.
246 * @throws LdapException
248 public function getUserGroups(string $userName): array
250 $groupsAttr = $this->config['group_attribute'];
251 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
253 if ($user === null) {
257 $userGroups = $this->groupFilter($user);
258 $userGroups = $this->getGroupsRecursive($userGroups, []);
263 * Get the parent groups of an array of groups.
264 * @throws LdapException
266 private function getGroupsRecursive(array $groupsArray, array $checked): array
269 foreach ($groupsArray as $groupName) {
270 if (in_array($groupName, $checked)) {
274 $parentGroups = $this->getGroupGroups($groupName);
275 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
276 $checked[] = $groupName;
279 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
281 if (empty($groupsToAdd)) {
285 return $this->getGroupsRecursive($groupsArray, $checked);
289 * Get the parent groups of a single group.
290 * @throws LdapException
292 private function getGroupGroups(string $groupName): array
294 $ldapConnection = $this->getConnection();
295 $this->bindSystemUser($ldapConnection);
297 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
298 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
300 $baseDn = $this->config['base_dn'];
301 $groupsAttr = strtolower($this->config['group_attribute']);
303 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
304 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
305 if ($groups['count'] === 0) {
309 return $this->groupFilter($groups[0]);
313 * Filter out LDAP CN and DN language in a ldap search return.
314 * Gets the base CN (common name) of the string.
316 protected function groupFilter(array $userGroupSearchResponse): array
318 $groupsAttr = strtolower($this->config['group_attribute']);
322 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
323 $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
326 for ($i = 0; $i < $count; $i++) {
327 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
328 if (!in_array($dnComponents[0], $ldapGroups)) {
329 $ldapGroups[] = $dnComponents[0];
337 * Sync the LDAP groups to the user roles for the current user.
338 * @throws LdapException
340 public function syncGroups(User $user, string $username)
342 $userLdapGroups = $this->getUserGroups($username);
343 $this->syncWithGroups($user, $userLdapGroups);