1 <?php namespace BookStack\Auth\Access;
3 use BookStack\Auth\User;
4 use BookStack\Auth\UserRepo;
5 use BookStack\Exceptions\LdapException;
7 use Illuminate\Contracts\Auth\Authenticatable;
11 * Handles any app-specific LDAP tasks.
13 class LdapService extends ExternalAuthService
17 protected $ldapConnection;
23 * LdapService constructor.
25 public function __construct(Ldap $ldap, UserRepo $userRepo)
28 $this->config = config('services.ldap');
29 $this->userRepo = $userRepo;
30 $this->enabled = config('auth.method') === 'ldap';
34 * Check if groups should be synced.
37 public function shouldSyncGroups()
39 return $this->enabled && $this->config['user_to_groups'] !== false;
43 * Search for attributes for a specific user on the ldap.
44 * @throws LdapException
46 private function getUserWithAttributes(string $userName, array $attributes): ?array
48 $ldapConnection = $this->getConnection();
49 $this->bindSystemUser($ldapConnection);
52 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
53 $baseDn = $this->config['base_dn'];
55 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
56 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
57 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
58 if ($users['count'] === 0) {
66 * Get the details of a user from LDAP using the given username.
67 * User found via configurable user filter.
68 * @throws LdapException
70 public function getUserDetails(string $userName): ?array
72 $idAttr = $this->config['id_attribute'];
73 $emailAttr = $this->config['email_attribute'];
74 $displayNameAttr = $this->config['display_name_attribute'];
76 $user = $this->getUserWithAttributes($userName, ['cn', 'dn', $idAttr, $emailAttr, $displayNameAttr]);
82 $userCn = $this->getUserResponseProperty($user, 'cn', null);
84 'uid' => $this->getUserResponseProperty($user, $idAttr, $user['dn']),
85 'name' => $this->getUserResponseProperty($user, $displayNameAttr, $userCn),
87 'email' => $this->getUserResponseProperty($user, $emailAttr, null),
92 * Get a property from an LDAP user response fetch.
93 * Handles properties potentially being part of an array.
95 protected function getUserResponseProperty(array $userDetails, string $propertyKey, $defaultValue)
97 $propertyKey = strtolower($propertyKey);
98 if (isset($userDetails[$propertyKey])) {
99 return (is_array($userDetails[$propertyKey]) ? $userDetails[$propertyKey][0] : $userDetails[$propertyKey]);
102 return $defaultValue;
106 * Check if the given credentials are valid for the given user.
107 * @throws LdapException
109 public function validateUserCredentials(array $ldapUserDetails, string $username, string $password): bool
111 if ($ldapUserDetails === null) {
115 $ldapConnection = $this->getConnection();
117 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUserDetails['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 // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
166 // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
167 if ($this->config['tls_insecure']) {
168 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
171 $serverDetails = $this->parseServerString($this->config['server']);
172 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
174 if ($ldapConnection === false) {
175 throw new LdapException(trans('errors.ldap_cannot_connect'));
178 // Set any required options
179 if ($this->config['version']) {
180 $this->ldap->setVersion($ldapConnection, $this->config['version']);
183 $this->ldapConnection = $ldapConnection;
184 return $this->ldapConnection;
188 * Parse a LDAP server string and return the host and port for a connection.
189 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
191 protected function parseServerString(string $serverString): array
193 $serverNameParts = explode(':', $serverString);
195 // If we have a protocol just return the full string since PHP will ignore a separate port.
196 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
197 return ['host' => $serverString, 'port' => 389];
200 // Otherwise, extract the port out
201 $hostName = $serverNameParts[0];
202 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
203 return ['host' => $hostName, 'port' => $ldapPort];
207 * Build a filter string by injecting common variables.
209 protected function buildFilter(string $filterString, array $attrs): string
212 foreach ($attrs as $key => $attrText) {
213 $newKey = '${' . $key . '}';
214 $newAttrs[$newKey] = $this->ldap->escape($attrText);
216 return strtr($filterString, $newAttrs);
220 * Get the groups a user is a part of on ldap.
221 * @throws LdapException
223 public function getUserGroups(string $userName): array
225 $groupsAttr = $this->config['group_attribute'];
226 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
228 if ($user === null) {
232 $userGroups = $this->groupFilter($user);
233 $userGroups = $this->getGroupsRecursive($userGroups, []);
238 * Get the parent groups of an array of groups.
239 * @throws LdapException
241 private function getGroupsRecursive(array $groupsArray, array $checked): array
244 foreach ($groupsArray as $groupName) {
245 if (in_array($groupName, $checked)) {
249 $parentGroups = $this->getGroupGroups($groupName);
250 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
251 $checked[] = $groupName;
254 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
256 if (empty($groupsToAdd)) {
260 return $this->getGroupsRecursive($groupsArray, $checked);
264 * Get the parent groups of a single group.
265 * @throws LdapException
267 private function getGroupGroups(string $groupName): array
269 $ldapConnection = $this->getConnection();
270 $this->bindSystemUser($ldapConnection);
272 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
273 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
275 $baseDn = $this->config['base_dn'];
276 $groupsAttr = strtolower($this->config['group_attribute']);
278 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
279 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
280 if ($groups['count'] === 0) {
284 return $this->groupFilter($groups[0]);
288 * Filter out LDAP CN and DN language in a ldap search return.
289 * Gets the base CN (common name) of the string.
291 protected function groupFilter(array $userGroupSearchResponse): array
293 $groupsAttr = strtolower($this->config['group_attribute']);
297 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
298 $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
301 for ($i = 0; $i < $count; $i++) {
302 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
303 if (!in_array($dnComponents[0], $ldapGroups)) {
304 $ldapGroups[] = $dnComponents[0];
312 * Sync the LDAP groups to the user roles for the current user.
313 * @throws LdapException
315 public function syncGroups(User $user, string $username)
317 $userLdapGroups = $this->getUserGroups($username);
318 $this->syncWithGroups($user, $userLdapGroups);