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 $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr]);
90 'uid' => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
91 'name' => $user['cn'][0],
93 'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
98 * @param Authenticatable $user
99 * @param string $username
100 * @param string $password
102 * @throws LdapException
104 public function validateUserCredentials(Authenticatable $user, $username, $password)
106 $ldapUser = $this->getUserDetails($username);
107 if ($ldapUser === null) {
111 if ($ldapUser['uid'] !== $user->external_auth_id) {
115 $ldapConnection = $this->getConnection();
117 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
118 } catch (\ErrorException $e) {
126 * Bind the system user to the LDAP connection using the given credentials
127 * otherwise anonymous access is attempted.
129 * @throws LdapException
131 protected function bindSystemUser($connection)
133 $ldapDn = $this->config['dn'];
134 $ldapPass = $this->config['pass'];
136 $isAnonymous = ($ldapDn === false || $ldapPass === false);
138 $ldapBind = $this->ldap->bind($connection);
140 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
144 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
149 * Get the connection to the LDAP server.
150 * Creates a new connection if one does not exist.
152 * @throws LdapException
154 protected function getConnection()
156 if ($this->ldapConnection !== null) {
157 return $this->ldapConnection;
160 // Check LDAP extension in installed
161 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
162 throw new LdapException(trans('errors.ldap_extension_not_installed'));
165 // Get port from server string and protocol if specified.
166 $ldapServer = explode(':', $this->config['server']);
167 $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
169 array_unshift($ldapServer, '');
171 $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
172 $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
173 $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
175 if ($ldapConnection === false) {
176 throw new LdapException(trans('errors.ldap_cannot_connect'));
179 // Set any required options
180 if ($this->config['version']) {
181 $this->ldap->setVersion($ldapConnection, $this->config['version']);
184 $this->ldapConnection = $ldapConnection;
185 return $this->ldapConnection;
189 * Build a filter string by injecting common variables.
190 * @param string $filterString
191 * @param array $attrs
194 protected function buildFilter($filterString, array $attrs)
197 foreach ($attrs as $key => $attrText) {
198 $newKey = '${' . $key . '}';
199 $newAttrs[$newKey] = $this->ldap->escape($attrText);
201 return strtr($filterString, $newAttrs);
205 * Get the groups a user is a part of on ldap
206 * @param string $userName
208 * @throws LdapException
210 public function getUserGroups($userName)
212 $groupsAttr = $this->config['group_attribute'];
213 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
215 if ($user === null) {
219 $userGroups = $this->groupFilter($user);
220 $userGroups = $this->getGroupsRecursive($userGroups, []);
225 * Get the parent groups of an array of groups
226 * @param array $groupsArray
227 * @param array $checked
229 * @throws LdapException
231 private function getGroupsRecursive($groupsArray, $checked)
234 foreach ($groupsArray as $groupName) {
235 if (in_array($groupName, $checked)) {
239 $groupsToAdd = $this->getGroupGroups($groupName);
240 $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
241 $checked[] = $groupName;
243 $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
245 if (!empty($groups_to_add)) {
246 return $this->getGroupsRecursive($groupsArray, $checked);
253 * Get the parent groups of a single group
254 * @param string $groupName
256 * @throws LdapException
258 private function getGroupGroups($groupName)
260 $ldapConnection = $this->getConnection();
261 $this->bindSystemUser($ldapConnection);
263 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
264 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
266 $baseDn = $this->config['base_dn'];
267 $groupsAttr = strtolower($this->config['group_attribute']);
269 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
270 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
271 if ($groups['count'] === 0) {
275 $groupGroups = $this->groupFilter($groups[0]);
280 * Filter out LDAP CN and DN language in a ldap search return
281 * Gets the base CN (common name) of the string
282 * @param array $userGroupSearchResponse
285 protected function groupFilter(array $userGroupSearchResponse)
287 $groupsAttr = strtolower($this->config['group_attribute']);
291 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
292 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
295 for ($i=0; $i<$count; $i++) {
296 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
297 if (!in_array($dnComponents[0], $ldapGroups)) {
298 $ldapGroups[] = $dnComponents[0];
306 * Sync the LDAP groups to the user roles for the current user
307 * @param \BookStack\Auth\User $user
308 * @param string $username
309 * @throws LdapException
311 public function syncGroups(User $user, string $username)
313 $userLdapGroups = $this->getUserGroups($username);
315 // Get the ids for the roles from the names
316 $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
319 if ($this->config['remove_from_groups']) {
320 $user->roles()->sync($ldapGroupsAsRoles);
321 $this->userRepo->attachDefaultRole($user);
323 $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
328 * Match an array of group names from LDAP to BookStack system roles.
329 * Formats LDAP group names to be lower-case and hyphenated.
330 * @param array $groupNames
331 * @return \Illuminate\Support\Collection
333 protected function matchLdapGroupsToSystemsRoles(array $groupNames)
335 foreach ($groupNames as $i => $groupName) {
336 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
339 $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
340 $query->whereIn('name', $groupNames);
341 foreach ($groupNames as $groupName) {
342 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
346 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
347 return $this->roleMatchesGroupNames($role, $groupNames);
350 return $matchedRoles->pluck('id');
354 * Check a role against an array of group names to see if it matches.
355 * Checked against role 'external_auth_id' if set otherwise the name of the role.
356 * @param \BookStack\Auth\Role $role
357 * @param array $groupNames
360 protected function roleMatchesGroupNames(Role $role, array $groupNames)
362 if ($role->external_auth_id) {
363 $externalAuthIds = explode(',', strtolower($role->external_auth_id));
364 foreach ($externalAuthIds as $externalAuthId) {
365 if (in_array(trim($externalAuthId), $groupNames)) {
372 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
373 return in_array($roleName, $groupNames);