1 <?php namespace BookStack\Services;
3 use BookStack\Exceptions\LdapException;
4 use Illuminate\Contracts\Auth\Authenticatable;
8 * Handles any app-specific LDAP tasks.
9 * @package BookStack\Services
15 protected $ldapConnection;
19 * LdapService constructor.
22 public function __construct(Ldap $ldap)
25 $this->config = config('services.ldap');
29 * Search for attributes for a specific user on the ldap
30 * @param string $userName
31 * @param array $attributes
33 * @throws LdapException
35 private function getUserWithAttributes($userName, $attributes)
37 $ldapConnection = $this->getConnection();
38 $this->bindSystemUser($ldapConnection);
41 $userFilter = $this->buildFilter($this->config['user_filter'], ['user' => $userName]);
42 $baseDn = $this->config['base_dn'];
44 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
45 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
46 $users = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, $userFilter, $attributes);
47 if ($users['count'] === 0) {
55 * Get the details of a user from LDAP using the given username.
56 * User found via configurable user filter.
59 * @throws LdapException
61 public function getUserDetails($userName)
63 $emailAttr = $this->config['email_attribute'];
64 $user = $this->getUserWithAttributes($userName, ['cn', 'uid', 'dn', $emailAttr]);
71 'uid' => (isset($user['uid'])) ? $user['uid'][0] : $user['dn'],
72 'name' => $user['cn'][0],
74 'email' => (isset($user[$emailAttr])) ? (is_array($user[$emailAttr]) ? $user[$emailAttr][0] : $user[$emailAttr]) : null
79 * @param Authenticatable $user
80 * @param string $username
81 * @param string $password
83 * @throws LdapException
85 public function validateUserCredentials(Authenticatable $user, $username, $password)
87 $ldapUser = $this->getUserDetails($username);
88 if ($ldapUser === null) {
91 if ($ldapUser['uid'] !== $user->external_auth_id) {
95 $ldapConnection = $this->getConnection();
97 $ldapBind = $this->ldap->bind($ldapConnection, $ldapUser['dn'], $password);
98 } catch (\ErrorException $e) {
106 * Bind the system user to the LDAP connection using the given credentials
107 * otherwise anonymous access is attempted.
109 * @throws LdapException
111 protected function bindSystemUser($connection)
113 $ldapDn = $this->config['dn'];
114 $ldapPass = $this->config['pass'];
116 $isAnonymous = ($ldapDn === false || $ldapPass === false);
118 $ldapBind = $this->ldap->bind($connection);
120 $ldapBind = $this->ldap->bind($connection, $ldapDn, $ldapPass);
124 throw new LdapException(($isAnonymous ? trans('errors.ldap_fail_anonymous') : trans('errors.ldap_fail_authed')));
129 * Get the connection to the LDAP server.
130 * Creates a new connection if one does not exist.
132 * @throws LdapException
134 protected function getConnection()
136 if ($this->ldapConnection !== null) {
137 return $this->ldapConnection;
140 // Check LDAP extension in installed
141 if (!function_exists('ldap_connect') && config('app.env') !== 'testing') {
142 throw new LdapException(trans('errors.ldap_extension_not_installed'));
145 // Get port from server string and protocol if specified.
146 $ldapServer = explode(':', $this->config['server']);
147 $hasProtocol = preg_match('/^ldaps{0,1}\:\/\//', $this->config['server']) === 1;
149 array_unshift($ldapServer, '');
151 $hostName = $ldapServer[0] . ($hasProtocol?':':'') . $ldapServer[1];
152 $defaultPort = $ldapServer[0] === 'ldaps' ? 636 : 389;
153 $ldapConnection = $this->ldap->connect($hostName, count($ldapServer) > 2 ? intval($ldapServer[2]) : $defaultPort);
155 if ($ldapConnection === false) {
156 throw new LdapException(trans('errors.ldap_cannot_connect'));
159 // Set any required options
160 if ($this->config['version']) {
161 $this->ldap->setVersion($ldapConnection, $this->config['version']);
164 $this->ldapConnection = $ldapConnection;
165 return $this->ldapConnection;
169 * Build a filter string by injecting common variables.
170 * @param string $filterString
171 * @param array $attrs
174 protected function buildFilter($filterString, array $attrs)
177 foreach ($attrs as $key => $attrText) {
178 $newKey = '${' . $key . '}';
179 $newAttrs[$newKey] = $attrText;
181 return strtr($filterString, $newAttrs);
185 * Get the groups a user is a part of on ldap
186 * @param string $userName
189 public function getUserGroups($userName)
191 $groupsAttr = $this->config['group_attribute'];
192 $user = $this->getUserWithAttributes($userName, [$groupsAttr]);
194 if ($user === null) {
198 $userGroups = $this->groupFilter($user);
199 $userGroups = $this->getGroupsRecursive($userGroups, []);
204 * Get the parent groups of an array of groups
205 * @param array $groupsArray
206 * @param array $checked
209 private function getGroupsRecursive($groupsArray, $checked)
212 foreach ($groupsArray as $groupName) {
213 if (in_array($groupName, $checked)) {
217 $groupsToAdd = $this->getGroupGroups($groupName);
218 $groups_to_add = array_merge($groups_to_add, $groupsToAdd);
219 $checked[] = $groupName;
221 $groupsArray = array_unique(array_merge($groupsArray, $groups_to_add), SORT_REGULAR);
223 if (!empty($groups_to_add)) {
224 return $this->getGroupsRecursive($groupsArray, $checked);
231 * Get the parent groups of a single group
232 * @param string $groupName
235 private function getGroupGroups($groupName)
237 $ldapConnection = $this->getConnection();
238 $this->bindSystemUser($ldapConnection);
240 $followReferrals = $this->config['follow_referrals'] ? 1 : 0;
241 $this->ldap->setOption($ldapConnection, LDAP_OPT_REFERRALS, $followReferrals);
243 $baseDn = $this->config['base_dn'];
244 $groupsAttr = strtolower($this->config['group_attribute']);
246 $groups = $this->ldap->searchAndGetEntries($ldapConnection, $baseDn, 'CN='.$groupName, [$groupsAttr]);
247 if ($groups['count'] === 0) {
251 $groupGroups = $this->groupFilter($groups[0]);
256 * Filter out LDAP CN and DN language in a ldap search return
257 * Gets the base CN (common name) of the string
258 * @param string $ldapSearchReturn
261 protected function groupFilter($ldapSearchReturn)
263 $groupsAttr = strtolower($this->config['group_attribute']);
266 if (isset($ldapSearchReturn[$groupsAttr]['count'])) {
267 $count = (int) $ldapSearchReturn[$groupsAttr]['count'];
269 for ($i=0; $i<$count; $i++) {
270 $dnComponents = ldap_explode_dn($ldapSearchReturn[$groupsAttr][$i], 1);
271 if (!in_array($dnComponents[0], $ldapGroups)) {
272 $ldapGroups[] = $dnComponents[0];