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 // Get port from server string and protocol if specified.
186 $ldapServer = explode(':', $this->config['server']);
187 $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
189 array_unshift($ldapServer, '');
191 $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
192 $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
195 * Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
196 * the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not
199 if ($this->config['tls_insecure']) {
200 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
203 $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
205 if ($ldapConnection === false) {
206 throw new LdapException(trans('errors.ldap_cannot_connect'));
209 // Set any required options
210 if ($this->config['version']) {
211 $this->ldap->setVersion($ldapConnection, $this->config['version']);
214 $this->ldapConnection = $ldapConnection;
215 return $this->ldapConnection;
219 * Build a filter string by injecting common variables.
220 * @param string $filterString
221 * @param array $attrs
224 protected function buildFilter($filterString, array $attrs)
227 foreach ($attrs as $key => $attrText) {
228 $newKey = '${' . $key . '}';
229 $newAttrs[$newKey] = $this->ldap->escape($attrText);
231 return strtr($filterString, $newAttrs);
235 * Get the groups a user is a part of on ldap
236 * @param string $userName
238 * @throws LdapException
240 public function getUserGroups($userName)
242 $groupsAttr = $this->config['group_attribute'];
243 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
245 if ($user === null) {
249 $userGroups = $this->groupFilter($user);
250 $userGroups = $this->getGroupsRecursive($userGroups, []);
255 * Get the parent groups of an array of groups
256 * @param array $groupsArray
257 * @param array $checked
259 * @throws LdapException
261 private function getGroupsRecursive($groupsArray, $checked)
264 foreach ($groupsArray as $groupName) {
265 if (in_array($groupName, $checked)) {
269 $groupsToAdd = $this->getGroupGroups($groupName);
270 $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
271 $checked[] = $groupName;
273 $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
275 if (!empty($groups_to_add)) {
276 return $this->getGroupsRecursive($groupsArray, $checked);
283 * Get the parent groups of a single group
284 * @param string $groupName
286 * @throws LdapException
288 private function getGroupGroups($groupName)
290 $ldapConnection = $this->getConnection();
291 $this->bindSystemUser($ldapConnection);
293 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
294 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
296 $baseDn = $this->config['base_dn'];
297 $groupsAttr = strtolower($this->config['group_attribute']);
299 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
300 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
301 if ($groups['count'] === 0) {
305 $groupGroups = $this->groupFilter($groups[0]);
310 * Filter out LDAP CN and DN language in a ldap search return
311 * Gets the base CN (common name) of the string
312 * @param array $userGroupSearchResponse
315 protected function groupFilter(array $userGroupSearchResponse)
317 $groupsAttr = strtolower($this->config['group_attribute']);
321 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
322 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
325 for ($i=0; $i<$count; $i++) {
326 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
327 if (!in_array($dnComponents[0], $ldapGroups)) {
328 $ldapGroups[] = $dnComponents[0];
336 * Sync the LDAP groups to the user roles for the current user
337 * @param \BookStack\Auth\User $user
338 * @param string $username
339 * @throws LdapException
341 public function syncGroups(User $user, string $username)
343 $userLdapGroups = $this->getUserGroups($username);
345 // Get the ids for the roles from the names
346 $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
349 if ($this->config['remove_from_groups']) {
350 $user->roles()->sync($ldapGroupsAsRoles);
351 $this->userRepo->attachDefaultRole($user);
353 $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
358 * Match an array of group names from LDAP to BookStack system roles.
359 * Formats LDAP group names to be lower-case and hyphenated.
360 * @param array $groupNames
361 * @return \Illuminate\Support\Collection
363 protected function matchLdapGroupsToSystemsRoles(array $groupNames)
365 foreach ($groupNames as $i => $groupName) {
366 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
369 $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
370 $query->whereIn('name', $groupNames);
371 foreach ($groupNames as $groupName) {
372 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
376 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
377 return $this->roleMatchesGroupNames($role, $groupNames);
380 return $matchedRoles->pluck('id');
384 * Check a role against an array of group names to see if it matches.
385 * Checked against role 'external_auth_id' if set otherwise the name of the role.
386 * @param \BookStack\Auth\Role $role
387 * @param array $groupNames
390 protected function roleMatchesGroupNames(Role $role, array $groupNames)
392 if ($role->external_auth_id) {
393 $externalAuthIds = explode(',', strtolower($role->external_auth_id));
394 foreach ($externalAuthIds as $externalAuthId) {
395 if (in_array(trim($externalAuthId), $groupNames)) {
402 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
403 return in_array($roleName, $groupNames);