xref: /plugin/pureldap/classes/ADClient.php (revision 204fba68543421287b88b2a48c04b5dea32b5394)
1<?php
2
3namespace dokuwiki\plugin\pureldap\classes;
4
5use dokuwiki\Utf8\PhpString;
6use FreeDSx\Ldap\Entry\Attribute;
7use FreeDSx\Ldap\Entry\Entries;
8use FreeDSx\Ldap\Entry\Entry;
9use FreeDSx\Ldap\Exception\OperationException;
10use FreeDSx\Ldap\Exception\ProtocolException;
11use FreeDSx\Ldap\Operations;
12use FreeDSx\Ldap\Search\Filters;
13
14class ADClient extends Client
15{
16
17    /** @inheritDoc */
18    public function getUser($username, $fetchgroups = true)
19    {
20        if (!$this->autoAuth()) return null;
21        $username = $this->simpleUser($username);
22
23        $filter = Filters::and(
24            Filters::equal('objectClass', 'user'),
25            Filters::equal('sAMAccountName', $this->simpleUser($username))
26        );
27        $this->debug('Searching ' . $filter->toString(), __FILE__, __LINE__);
28
29        try {
30            /** @var Entries $entries */
31            $attributes = $this->userAttributes();
32            $entries = $this->ldap->search(Operations::search($filter, ...$attributes));
33        } catch (OperationException $e) {
34            $this->fatal($e);
35            return null;
36        }
37        if ($entries->count() !== 1) return null;
38        $entry = $entries->first();
39        return $this->entry2User($entry);
40    }
41
42    /** @inheritDoc */
43    public function getGroups($match = null, $filtermethod = self::FILTER_EQUAL)
44    {
45        if (!$this->autoAuth()) return [];
46
47        $filter = Filters::and(
48            Filters::equal('objectClass', 'group')
49        );
50        if ($match !== null) {
51            // FIXME this is a workaround that removes regex anchors as passed by the groupuser plugin
52            // a proper fix requires splitbrain/dokuwiki#3028 to be properly fixed
53            $match = ltrim($match, '^');
54            $match = rtrim($match, '$');
55
56            $filter->add(Filters::$filtermethod('cn', $match));
57        }
58
59        $this->debug('Searching ' . $filter->toString(), __FILE__, __LINE__);
60        $search = Operations::search($filter, 'cn');
61        $paging = $this->ldap->paging($search);
62
63        $groups = [];
64        while ($paging->hasEntries()) {
65            try {
66                $entries = $paging->getEntries();
67            } catch (ProtocolException $e) {
68                $this->fatal($e);
69                return $groups; // we return what we got so far
70            }
71
72            foreach ($entries as $entry) {
73                /** @var Entry $entry */
74                $groups[$entry->getDn()->toString()] = $this->cleanGroup($this->attr2str($entry->get('cn')));
75            }
76        }
77
78        asort($groups);
79        return $groups;
80    }
81
82    /**
83     * Fetch users matching the given filters
84     *
85     * @param array $match
86     * @param string $filtermethod The method to use for filtering
87     * @return array
88     */
89    public function getFilteredUsers($match, $filtermethod = self::FILTER_EQUAL)
90    {
91        if (!$this->autoAuth()) return [];
92
93        $filter = Filters::and(Filters::equal('objectClass', 'user'));
94        if (isset($match['user'])) {
95            $filter->add(Filters::$filtermethod('sAMAccountName', $this->simpleUser($match['user'])));
96        }
97        if (isset($match['name'])) {
98            $filter->add(Filters::$filtermethod('displayName', $match['name']));
99        }
100        if (isset($match['mail'])) {
101            $filter->add(Filters::$filtermethod('mail', $match['mail']));
102        }
103        if (isset($match['grps'])) {
104            // memberOf can not be checked with a substring match, so we need to get the right groups first
105            $groups = $this->getGroups($match['grps'], $filtermethod);
106            $or = Filters::or();
107            foreach ($groups as $dn => $group) {
108                // domain users membership is in primary group
109                if ($group === 'domain users') {
110                    $or->add(Filters::equal('primaryGroupID', 513));
111                    continue;
112                }
113
114                $or->add(Filters::equal('memberOf', $dn));
115            }
116            $filter->add($or);
117        }
118        $this->debug('Searching ' . $filter->toString(), __FILE__, __LINE__);
119        $attributes = $this->userAttributes();
120        $search = Operations::search($filter, ...$attributes);
121        $paging = $this->ldap->paging($search);
122
123        $users = [];
124        while ($paging->hasEntries()) {
125            try {
126                $entries = $paging->getEntries();
127            } catch (ProtocolException $e) {
128                $this->fatal($e);
129                break; // we abort and return what we have so far
130            }
131
132            foreach ($entries as $entry) {
133                $userinfo = $this->entry2User($entry);
134                $users[$userinfo['user']] = $this->entry2User($entry);
135            }
136        }
137
138        ksort($users);
139        return $users;
140    }
141
142    /** @inheritDoc */
143    public function cleanUser($user)
144    {
145        return $this->simpleUser($user);
146    }
147
148    /** @inheritDoc */
149    public function cleanGroup($group)
150    {
151        return PhpString::strtolower($group);
152    }
153
154    /** @inheritDoc */
155    public function prepareBindUser($user)
156    {
157        $user = $this->qualifiedUser($user); // add account suffix
158        return $user;
159    }
160
161    /**
162     * @inheritDoc
163     * userPrincipalName in the form <user>@<suffix>
164     */
165    protected function qualifiedUser($user)
166    {
167        $user = $this->simpleUser($user); // strip any existing qualifiers
168        if (!$this->config['suffix']) {
169            $this->error('No account suffix set. Logins may fail.', __FILE__, __LINE__);
170        }
171
172        return $user . '@' . $this->config['suffix'];
173    }
174
175    /**
176     * @inheritDoc
177     * Removes the account suffix from the given user. Should match the SAMAccountName
178     */
179    protected function simpleUser($user)
180    {
181        $user = PhpString::strtolower($user);
182        $user = preg_replace('/@.*$/', '', $user);
183        $user = preg_replace('/^.*\\\\/', '', $user);
184        return $user;
185    }
186
187    /**
188     * Transform an LDAP entry to a user info array
189     *
190     * @param Entry $entry
191     * @return array
192     */
193    protected function entry2User(Entry $entry)
194    {
195        $user = [
196            'user' => $this->simpleUser($this->attr2str($entry->get('sAMAccountName'))),
197            'name' => $this->attr2str($entry->get('DisplayName')) ?: $this->attr2str($entry->get('Name')),
198            'mail' => $this->attr2str($entry->get('mail')),
199            'dn' => $entry->getDn()->toString(),
200            'grps' => $this->getUserGroups($entry), // we always return groups because its currently inexpensive
201        ];
202
203        // get additional attributes
204        foreach ($this->config['attributes'] as $attr) {
205            $user[$attr] = $this->attr2str($entry->get($attr));
206        }
207
208        return $user;
209    }
210
211    /**
212     * Get the list of groups the given user is member of
213     *
214     * This method currently does no LDAP queries and thus is inexpensive.
215     *
216     * @param Entry $userentry
217     * @return array
218     * @todo implement nested group memberships FIXME already correct?
219     */
220    protected function getUserGroups(Entry $userentry)
221    {
222        $groups = [$this->config['defaultgroup']]; // always add default
223
224        // we simply take the first CN= part of the group DN and return it as the group name
225        // this should be correct for ActiveDirectory and saves us additional LDAP queries
226        if ($userentry->has('memberOf')) {
227            foreach ($userentry->get('memberOf')->getValues() as $dn) {
228                list($cn) = explode(',', $dn, 2);
229                $groups[] = $this->cleanGroup(substr($cn, 3));
230            }
231        }
232
233        // resolving the primary group in AD is complicated but basically never needed
234        // http://support.microsoft.com/?kbid=321360
235        $gid = $userentry->get('primaryGroupID')->firstValue();
236        if ($gid == 513) {
237            $groups[] = $this->cleanGroup('domain users');
238        }
239
240        sort($groups);
241        return $groups;
242    }
243
244    /** @inheritDoc */
245    protected function userAttributes()
246    {
247        $attr = parent::userAttributes();
248        $attr[] = new Attribute('sAMAccountName');
249        $attr[] = new Attribute('Name');
250        $attr[] = new Attribute('primaryGroupID');
251        $attr[] = new Attribute('memberOf');
252
253        return $attr;
254    }
255
256}
257