1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\Access;
4 use BookStack\Auth\Role;
5 use BookStack\Auth\User;
6 use BookStack\Auth\UserRepo;
7 use BookStack\Exceptions\LdapException;
8 use Illuminate\Contracts\Auth\Authenticatable;
9 use Illuminate\Database\Eloquent\Builder;
13 * Handles any app-specific LDAP tasks.
14 * @package BookStack\Services
20 protected $ldapConnection;
26 * LdapService constructor.
28 * @param \BookStack\Auth\UserRepo $userRepo
30 public function __construct(Access\Ldap $ldap, UserRepo $userRepo)
33 $this->config = config('services.ldap');
34 $this->userRepo = $userRepo;
35 $this->enabled = config('auth.method') === 'ldap';
39 * Check if groups should be synced.
42 public function shouldSyncGroups()
44 return $this->enabled && $this->config['user_to_groups'] !== false;
48 * Search for attributes for a specific user on the ldap
49 * @param string $userName
50 * @param array $attributes
52 * @throws LdapException
54 private function getUserWithAttributes($userName, $attributes)
56 $ldapConnection = $this->getConnection();
57 $this->bindSystemUser($ldapConnection);
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.
78 * @throws LdapException
80 public function getUserDetails($userName)
82 $emailAttr = $this->config['email_attribute'];
83 $displayNameAttr = $this->config['display_name_attribute'];
85 $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr, $displayNameAttr]);
91 $userCn = $this->getUserResponseProperty($user, 'cn', null);
93 'uid' => $this->getUserResponseProperty($user, 'uid', $user['dn']),
94 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
96 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
101 * Get a property from an LDAP user response fetch.
102 * Handles properties potentially being part of an array.
103 * @param array $userDetails
104 * @param string $propertyKey
105 * @param $defaultValue
108 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
110 if (isset($userDetails[$propertyKey])) {
111 return (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
114 return $defaultValue;
118 * @param Authenticatable $user
119 * @param string $username
120 * @param string $password
122 * @throws LdapException
124 public function validateUserCredentials(Authenticatable $user, $username, $password)
126 $ldapUser = $this->getUserDetails($username);
127 if ($ldapUser === null) {
131 if ($ldapUser['uid'] !== $user->external_auth_id) {
135 $ldapConnection = $this->getConnection();
137 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
138 } catch (\ErrorException $e) {
146 * Bind the system user to the LDAP connection using the given credentials
147 * otherwise anonymous access is attempted.
149 * @throws LdapException
151 protected function bindSystemUser($connection)
153 $ldapDn = $this->config['dn'];
154 $ldapPass = $this->config['pass'];
156 $isAnonymous = ($ldapDn === false || $ldapPass === false);
158 $ldapBind = $this->ldap->bind($connection);
160 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
164 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
169 * Get the connection to the LDAP server.
170 * Creates a new connection if one does not exist.
172 * @throws LdapException
174 protected function getConnection()
176 if ($this->ldapConnection !== null) {
177 return $this->ldapConnection;
180 // Check LDAP extension in installed
181 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
182 throw new LdapException(trans('errors.ldap_extension_not_installed'));
185 // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
186 // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
187 if ($this->config['tls_insecure']) {
188 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
191 $serverDetails = $this->parseServerString($this->config['server']);
192 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
194 if ($ldapConnection === false) {
195 throw new LdapException(trans('errors.ldap_cannot_connect'));
198 // Set any required options
199 if ($this->config['version']) {
200 $this->ldap->setVersion($ldapConnection, $this->config['version']);
203 $this->ldapConnection = $ldapConnection;
204 return $this->ldapConnection;
208 * Parse a LDAP server string and return the host and port for
209 * a connection. Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'
210 * @param $serverString
213 protected function parseServerString($serverString)
215 $serverNameParts = explode(':', $serverString);
217 // If we have a protocol just return the full string since PHP will ignore a separate port.
218 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
219 return ['host' => $serverString, 'port' => 389];
222 // Otherwise, extract the port out
223 $hostName = $serverNameParts[0];
224 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
225 return ['host' => $hostName, 'port' => $ldapPort];
229 * Build a filter string by injecting common variables.
230 * @param string $filterString
231 * @param array $attrs
234 protected function buildFilter($filterString, array $attrs)
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 * @param string $userName
248 * @throws LdapException
250 public function getUserGroups($userName)
252 $groupsAttr = $this->config['group_attribute'];
253 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
255 if ($user === null) {
259 $userGroups = $this->groupFilter($user);
260 $userGroups = $this->getGroupsRecursive($userGroups, []);
265 * Get the parent groups of an array of groups
266 * @param array $groupsArray
267 * @param array $checked
269 * @throws LdapException
271 private function getGroupsRecursive($groupsArray, $checked)
274 foreach ($groupsArray as $groupName) {
275 if (in_array($groupName, $checked)) {
279 $groupsToAdd = $this->getGroupGroups($groupName);
280 $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
281 $checked[] = $groupName;
283 $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
285 if (!empty($groups_to_add)) {
286 return $this->getGroupsRecursive($groupsArray, $checked);
293 * Get the parent groups of a single group
294 * @param string $groupName
296 * @throws LdapException
298 private function getGroupGroups($groupName)
300 $ldapConnection = $this->getConnection();
301 $this->bindSystemUser($ldapConnection);
303 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
304 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
306 $baseDn = $this->config['base_dn'];
307 $groupsAttr = strtolower($this->config['group_attribute']);
309 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
310 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
311 if ($groups['count'] === 0) {
315 $groupGroups = $this->groupFilter($groups[0]);
320 * Filter out LDAP CN and DN language in a ldap search return
321 * Gets the base CN (common name) of the string
322 * @param array $userGroupSearchResponse
325 protected function groupFilter(array $userGroupSearchResponse)
327 $groupsAttr = strtolower($this->config['group_attribute']);
331 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
332 $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
335 for ($i = 0; $i < $count; $i++) {
336 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
337 if (!in_array($dnComponents[0], $ldapGroups)) {
338 $ldapGroups[] = $dnComponents[0];
346 * Sync the LDAP groups to the user roles for the current user
347 * @param \BookStack\Auth\User $user
348 * @param string $username
349 * @throws LdapException
351 public function syncGroups(User $user, string $username)
353 $userLdapGroups = $this->getUserGroups($username);
355 // Get the ids for the roles from the names
356 $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
359 if ($this->config['remove_from_groups']) {
360 $user->roles()->sync($ldapGroupsAsRoles);
361 $this->userRepo->attachDefaultRole($user);
363 $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
368 * Match an array of group names from LDAP to BookStack system roles.
369 * Formats LDAP group names to be lower-case and hyphenated.
370 * @param array $groupNames
371 * @return \Illuminate\Support\Collection
373 protected function matchLdapGroupsToSystemsRoles(array $groupNames)
375 foreach ($groupNames as $i => $groupName) {
376 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
379 $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
380 $query->whereIn('name', $groupNames);
381 foreach ($groupNames as $groupName) {
382 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
386 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
387 return $this->roleMatchesGroupNames($role, $groupNames);
390 return $matchedRoles->pluck('id');
394 * Check a role against an array of group names to see if it matches.
395 * Checked against role 'external_auth_id' if set otherwise the name of the role.
396 * @param \BookStack\Auth\Role $role
397 * @param array $groupNames
400 protected function roleMatchesGroupNames(Role $role, array $groupNames)
402 if ($role->external_auth_id) {
403 $externalAuthIds = explode(',', strtolower($role->external_auth_id));
404 foreach ($externalAuthIds as $externalAuthId) {
405 if (in_array(trim($externalAuthId), $groupNames)) {
412 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
413 return in_array($roleName, $groupNames);