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(Authenticatable $user, string $username, string $password): bool
111 $ldapUser = $this->getUserDetails($username);
112 if ($ldapUser === null) {
116 if ($ldapUser['uid'] !== $user->external_auth_id) {
120 $ldapConnection = $this->getConnection();
122 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
123 } catch (ErrorException $e) {
131 * Bind the system user to the LDAP connection using the given credentials
132 * otherwise anonymous access is attempted.
134 * @throws LdapException
136 protected function bindSystemUser($connection)
138 $ldapDn = $this->config['dn'];
139 $ldapPass = $this->config['pass'];
141 $isAnonymous = ($ldapDn === false || $ldapPass === false);
143 $ldapBind = $this->ldap->bind($connection);
145 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
149 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
154 * Get the connection to the LDAP server.
155 * Creates a new connection if one does not exist.
157 * @throws LdapException
159 protected function getConnection()
161 if ($this->ldapConnection !== null) {
162 return $this->ldapConnection;
165 // Check LDAP extension in installed
166 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
167 throw new LdapException(trans('errors.ldap_extension_not_installed'));
170 // Check if TLS_INSECURE is set. The handle is set to NULL due to the nature of
171 // the LDAP_OPT_X_TLS_REQUIRE_CERT option. It can only be set globally and not per handle.
172 if ($this->config['tls_insecure']) {
173 $this->ldap->setOption(null, LDAP_OPT_X_TLS_REQUIRE_CERT, LDAP_OPT_X_TLS_NEVER);
176 $serverDetails = $this->parseServerString($this->config['server']);
177 $ldapConnection = $this->ldap->connect($serverDetails['host'], $serverDetails['port']);
179 if ($ldapConnection === false) {
180 throw new LdapException(trans('errors.ldap_cannot_connect'));
183 // Set any required options
184 if ($this->config['version']) {
185 $this->ldap->setVersion($ldapConnection, $this->config['version']);
188 $this->ldapConnection = $ldapConnection;
189 return $this->ldapConnection;
193 * Parse a LDAP server string and return the host and port for a connection.
194 * Is flexible to formats such as 'ldap.example.com:8069' or 'ldaps://ldap.example.com'.
196 protected function parseServerString(string $serverString): array
198 $serverNameParts = explode(':', $serverString);
200 // If we have a protocol just return the full string since PHP will ignore a separate port.
201 if ($serverNameParts[0] === 'ldaps' || $serverNameParts[0] === 'ldap') {
202 return ['host' => $serverString, 'port' => 389];
205 // Otherwise, extract the port out
206 $hostName = $serverNameParts[0];
207 $ldapPort = (count($serverNameParts) > 1) ? intval($serverNameParts[1]) : 389;
208 return ['host' => $hostName, 'port' => $ldapPort];
212 * Build a filter string by injecting common variables.
214 protected function buildFilter(string $filterString, array $attrs): string
217 foreach ($attrs as $key => $attrText) {
218 $newKey = '${' . $key . '}';
219 $newAttrs[$newKey] = $this->ldap->escape($attrText);
221 return strtr($filterString, $newAttrs);
225 * Get the groups a user is a part of on ldap.
226 * @throws LdapException
228 public function getUserGroups(string $userName): array
230 $groupsAttr = $this->config['group_attribute'];
231 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
233 if ($user === null) {
237 $userGroups = $this->groupFilter($user);
238 $userGroups = $this->getGroupsRecursive($userGroups, []);
243 * Get the parent groups of an array of groups.
244 * @throws LdapException
246 private function getGroupsRecursive(array $groupsArray, array $checked): array
249 foreach ($groupsArray as $groupName) {
250 if (in_array($groupName, $checked)) {
254 $parentGroups = $this->getGroupGroups($groupName);
255 $groupsToAdd = array_merge($groupsToAdd, $parentGroups);
256 $checked[] = $groupName;
259 $groupsArray = array_unique(array_merge($groupsArray, $groupsToAdd), SORT_REGULAR);
261 if (empty($groupsToAdd)) {
265 return $this->getGroupsRecursive($groupsArray, $checked);
269 * Get the parent groups of a single group.
270 * @throws LdapException
272 private function getGroupGroups(string $groupName): array
274 $ldapConnection = $this->getConnection();
275 $this->bindSystemUser($ldapConnection);
277 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
278 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
280 $baseDn = $this->config['base_dn'];
281 $groupsAttr = strtolower($this->config['group_attribute']);
283 $groupFilter = 'CN=' . $this->ldap->escape($groupName);
284 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $groupFilter, [$groupsAttr]);
285 if ($groups['count'] === 0) {
289 return $this->groupFilter($groups[0]);
293 * Filter out LDAP CN and DN language in a ldap search return.
294 * Gets the base CN (common name) of the string.
296 protected function groupFilter(array $userGroupSearchResponse): array
298 $groupsAttr = strtolower($this->config['group_attribute']);
302 if (isset($userGroupSearchResponse[$groupsAttr]['count'])) {
303 $count = (int)$userGroupSearchResponse[$groupsAttr]['count'];
306 for ($i = 0; $i < $count; $i++) {
307 $dnComponents = $this->ldap->explodeDn($userGroupSearchResponse[$groupsAttr][$i], 1);
308 if (!in_array($dnComponents[0], $ldapGroups)) {
309 $ldapGroups[] = $dnComponents[0];
317 * Sync the LDAP groups to the user roles for the current user.
318 * @throws LdapException
320 public function syncGroups(User $user, string $username)
322 $userLdapGroups = $this->getUserGroups($username);
323 $this->syncWithGroups($user, $userLdapGroups);