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]);
92 'uid' => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
93 'name' => (isset($user[$displayNameAttr])) ? (is_array($user[$displayNameAttr]) ? $user[$displayNameAttr][0] : $user[$displayNameAttr]) : $user['cn'][0],
95 'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
100 * @param Authenticatable $user
101 * @param string $username
102 * @param string $password
104 * @throws LdapException
106 public function validateUserCredentials(Authenticatable $user, $username, $password)
108 $ldapUser = $this->getUserDetails($username);
109 if ($ldapUser === null) {
113 if ($ldapUser['uid'] !== $user->external_auth_id) {
117 $ldapConnection = $this->getConnection();
119 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
120 } catch (\ErrorException $e) {
128 * Bind the system user to the LDAP connection using the given credentials
129 * otherwise anonymous access is attempted.
131 * @throws LdapException
133 protected function bindSystemUser($connection)
135 $ldapDn = $this->config['dn'];
136 $ldapPass = $this->config['pass'];
138 $isAnonymous = ($ldapDn === false || $ldapPass === false);
140 $ldapBind = $this->ldap->bind($connection);
142 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
146 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
151 * Get the connection to the LDAP server.
152 * Creates a new connection if one does not exist.
154 * @throws LdapException
156 protected function getConnection()
158 if ($this->ldapConnection !== null) {
159 return $this->ldapConnection;
162 // Check LDAP extension in installed
163 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
164 throw new LdapException(trans('errors.ldap_extension_not_installed'));
167 // Get port from server string and protocol if specified.
168 $ldapServer = explode(':', $this->config['server']);
169 $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
171 array_unshift($ldapServer, '');
173 $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
174 $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
177 * Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
178 * the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not
181 if ($this->config['tls_insecure']) {
182 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
185 $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
187 if ($ldapConnection === false) {
188 throw new LdapException(trans('errors.ldap_cannot_connect'));
191 // Set any required options
192 if ($this->config['version']) {
193 $this->ldap->setVersion($ldapConnection, $this->config['version']);
196 $this->ldapConnection = $ldapConnection;
197 return $this->ldapConnection;
201 * Build a filter string by injecting common variables.
202 * @param string $filterString
203 * @param array $attrs
206 protected function buildFilter($filterString, array $attrs)
209 foreach ($attrs as $key => $attrText) {
210 $newKey = '${' . $key . '}';
211 $newAttrs[$newKey] = $this->ldap->escape($attrText);
213 return strtr($filterString, $newAttrs);
217 * Get the groups a user is a part of on ldap
218 * @param string $userName
220 * @throws LdapException
222 public function getUserGroups($userName)
224 $groupsAttr = $this->config['group_attribute'];
225 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
227 if ($user === null) {
231 $userGroups = $this->groupFilter($user);
232 $userGroups = $this->getGroupsRecursive($userGroups, []);
237 * Get the parent groups of an array of groups
238 * @param array $groupsArray
239 * @param array $checked
241 * @throws LdapException
243 private function getGroupsRecursive($groupsArray, $checked)
246 foreach ($groupsArray as $groupName) {
247 if (in_array($groupName, $checked)) {
251 $groupsToAdd = $this->getGroupGroups($groupName);
252 $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
253 $checked[] = $groupName;
255 $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
257 if (!empty($groups_to_add)) {
258 return $this->getGroupsRecursive($groupsArray, $checked);
265 * Get the parent groups of a single group
266 * @param string $groupName
268 * @throws LdapException
270 private function getGroupGroups($groupName)
272 $ldapConnection = $this->getConnection();
273 $this->bindSystemUser($ldapConnection);
275 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
276 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
278 $baseDn = $this->config['base_dn'];
279 $groupsAttr = strtolower($this->config['group_attribute']);
281 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
282 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
283 if ($groups['count'] === 0) {
287 $groupGroups = $this->groupFilter($groups[0]);
292 * Filter out LDAP CN and DN language in a ldap search return
293 * Gets the base CN (common name) of the string
294 * @param array $userGroupSearchResponse
297 protected function groupFilter(array $userGroupSearchResponse)
299 $groupsAttr = strtolower($this->config['group_attribute']);
303 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
304 $count = (int) $userGroupSearchResponse[$groupsAttr]['count'];
307 for ($i=0; $i<$count; $i++) {
308 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
309 if (!in_array($dnComponents[0], $ldapGroups)) {
310 $ldapGroups[] = $dnComponents[0];
318 * Sync the LDAP groups to the user roles for the current user
319 * @param \BookStack\Auth\User $user
320 * @param string $username
321 * @throws LdapException
323 public function syncGroups(User $user, string $username)
325 $userLdapGroups = $this->getUserGroups($username);
327 // Get the ids for the roles from the names
328 $ldapGroupsAsRoles = $this->matchLdapGroupsToSystemsRoles($userLdapGroups);
331 if ($this->config['remove_from_groups']) {
332 $user->roles()->sync($ldapGroupsAsRoles);
333 $this->userRepo->attachDefaultRole($user);
335 $user->roles()->syncWithoutDetaching($ldapGroupsAsRoles);
340 * Match an array of group names from LDAP to BookStack system roles.
341 * Formats LDAP group names to be lower-case and hyphenated.
342 * @param array $groupNames
343 * @return \Illuminate\Support\Collection
345 protected function matchLdapGroupsToSystemsRoles(array $groupNames)
347 foreach ($groupNames as $i => $groupName) {
348 $groupNames[$i] = str_replace(' ', '-', trim(strtolower($groupName)));
351 $roles = Role::query()->where(function (Builder $query) use ($groupNames) {
352 $query->whereIn('name', $groupNames);
353 foreach ($groupNames as $groupName) {
354 $query->orWhere('external_auth_id', 'LIKE', '%' . $groupName . '%');
358 $matchedRoles = $roles->filter(function (Role $role) use ($groupNames) {
359 return $this->roleMatchesGroupNames($role, $groupNames);
362 return $matchedRoles->pluck('id');
366 * Check a role against an array of group names to see if it matches.
367 * Checked against role 'external_auth_id' if set otherwise the name of the role.
368 * @param \BookStack\Auth\Role $role
369 * @param array $groupNames
372 protected function roleMatchesGroupNames(Role $role, array $groupNames)
374 if ($role->external_auth_id) {
375 $externalAuthIds = explode(',', strtolower($role->external_auth_id));
376 foreach ($externalAuthIds as $externalAuthId) {
377 if (in_array(trim($externalAuthId), $groupNames)) {
384 $roleName = str_replace(' ', '-', trim(strtolower($role->display_name)));
385 return in_array($roleName, $groupNames);