xref: /plugin/pureldap/classes/ADClient.php (revision c2500b4410d7943a5b4952a0bb25d20d1a95cb79)
11078ec26SAndreas Gohr<?php
21078ec26SAndreas Gohr
31078ec26SAndreas Gohrnamespace dokuwiki\plugin\pureldap\classes;
41078ec26SAndreas Gohr
580ac552fSAndreas Gohruse dokuwiki\Utf8\PhpString;
69c590892SAndreas Gohruse FreeDSx\Ldap\Entry\Attribute;
71078ec26SAndreas Gohruse FreeDSx\Ldap\Entry\Entries;
81078ec26SAndreas Gohruse FreeDSx\Ldap\Entry\Entry;
91078ec26SAndreas Gohruse FreeDSx\Ldap\Exception\OperationException;
105a3b9122SAndreas Gohruse FreeDSx\Ldap\Exception\ProtocolException;
111078ec26SAndreas Gohruse FreeDSx\Ldap\Operations;
121078ec26SAndreas Gohruse FreeDSx\Ldap\Search\Filters;
131078ec26SAndreas Gohr
141078ec26SAndreas Gohrclass ADClient extends Client
151078ec26SAndreas Gohr{
161078ec26SAndreas Gohr
171078ec26SAndreas Gohr    /** @inheritDoc */
181078ec26SAndreas Gohr    public function getUser($username, $fetchgroups = true)
191078ec26SAndreas Gohr    {
201078ec26SAndreas Gohr        if (!$this->autoAuth()) return null;
21a1128cc0SAndreas Gohr        $username = $this->simpleUser($username);
221078ec26SAndreas Gohr
231078ec26SAndreas Gohr        $filter = Filters::and(
241078ec26SAndreas Gohr            Filters::equal('objectClass', 'user'),
25a1128cc0SAndreas Gohr            Filters::equal('sAMAccountName', $this->simpleUser($username))
261078ec26SAndreas Gohr        );
27b21740b4SAndreas Gohr        $this->debug('Searching ' . $filter->toString(), __FILE__, __LINE__);
281078ec26SAndreas Gohr
291078ec26SAndreas Gohr        try {
301078ec26SAndreas Gohr            /** @var Entries $entries */
319c590892SAndreas Gohr            $attributes = $this->userAttributes();
329c590892SAndreas Gohr            $entries = $this->ldap->search(Operations::search($filter, ...$attributes));
331078ec26SAndreas Gohr        } catch (OperationException $e) {
34b21740b4SAndreas Gohr            $this->fatal($e);
351078ec26SAndreas Gohr            return null;
361078ec26SAndreas Gohr        }
371078ec26SAndreas Gohr        if ($entries->count() !== 1) return null;
381078ec26SAndreas Gohr        $entry = $entries->first();
39b21740b4SAndreas Gohr        return $this->entry2User($entry);
40b21740b4SAndreas Gohr    }
411078ec26SAndreas Gohr
42b21740b4SAndreas Gohr    /** @inheritDoc */
43204fba68SAndreas Gohr    public function getGroups($match = null, $filtermethod = self::FILTER_EQUAL)
44b21740b4SAndreas Gohr    {
45b21740b4SAndreas Gohr        if (!$this->autoAuth()) return [];
46b21740b4SAndreas Gohr
47b21740b4SAndreas Gohr        $filter = Filters::and(
48b21740b4SAndreas Gohr            Filters::equal('objectClass', 'group')
49b21740b4SAndreas Gohr        );
50b21740b4SAndreas Gohr        if ($match !== null) {
51fce018daSAndreas Gohr            // FIXME this is a workaround that removes regex anchors as passed by the groupuser plugin
52fce018daSAndreas Gohr            // a proper fix requires splitbrain/dokuwiki#3028 to be properly fixed
53fce018daSAndreas Gohr            $match = ltrim($match, '^');
54fce018daSAndreas Gohr            $match = rtrim($match, '$');
55fce018daSAndreas Gohr
56b21740b4SAndreas Gohr            $filter->add(Filters::$filtermethod('cn', $match));
57b21740b4SAndreas Gohr        }
58b21740b4SAndreas Gohr
59b21740b4SAndreas Gohr        $this->debug('Searching ' . $filter->toString(), __FILE__, __LINE__);
60b21740b4SAndreas Gohr        $search = Operations::search($filter, 'cn');
61b21740b4SAndreas Gohr        $paging = $this->ldap->paging($search);
62b21740b4SAndreas Gohr
63b21740b4SAndreas Gohr        $groups = [];
64b21740b4SAndreas Gohr        while ($paging->hasEntries()) {
65b21740b4SAndreas Gohr            try {
66b21740b4SAndreas Gohr                $entries = $paging->getEntries();
67b21740b4SAndreas Gohr            } catch (ProtocolException $e) {
68b21740b4SAndreas Gohr                $this->fatal($e);
69b21740b4SAndreas Gohr                return $groups; // we return what we got so far
70b21740b4SAndreas Gohr            }
71b21740b4SAndreas Gohr
72b21740b4SAndreas Gohr            foreach ($entries as $entry) {
73b21740b4SAndreas Gohr                /** @var Entry $entry */
74204fba68SAndreas Gohr                $groups[$entry->getDn()->toString()] = $this->cleanGroup($this->attr2str($entry->get('cn')));
75b21740b4SAndreas Gohr            }
76b21740b4SAndreas Gohr        }
77b21740b4SAndreas Gohr
781b0eb9b3SAndreas Gohr        asort($groups);
79b21740b4SAndreas Gohr        return $groups;
80b21740b4SAndreas Gohr    }
81b21740b4SAndreas Gohr
82b21740b4SAndreas Gohr    /**
83b21740b4SAndreas Gohr     * Fetch users matching the given filters
84b21740b4SAndreas Gohr     *
85b21740b4SAndreas Gohr     * @param array $match
86b21740b4SAndreas Gohr     * @param string $filtermethod The method to use for filtering
87b21740b4SAndreas Gohr     * @return array
88b21740b4SAndreas Gohr     */
89204fba68SAndreas Gohr    public function getFilteredUsers($match, $filtermethod = self::FILTER_EQUAL)
90b21740b4SAndreas Gohr    {
91b21740b4SAndreas Gohr        if (!$this->autoAuth()) return [];
92b21740b4SAndreas Gohr
93b21740b4SAndreas Gohr        $filter = Filters::and(Filters::equal('objectClass', 'user'));
94b21740b4SAndreas Gohr        if (isset($match['user'])) {
95a1128cc0SAndreas Gohr            $filter->add(Filters::$filtermethod('sAMAccountName', $this->simpleUser($match['user'])));
96b21740b4SAndreas Gohr        }
97b21740b4SAndreas Gohr        if (isset($match['name'])) {
98b21740b4SAndreas Gohr            $filter->add(Filters::$filtermethod('displayName', $match['name']));
99b21740b4SAndreas Gohr        }
100b21740b4SAndreas Gohr        if (isset($match['mail'])) {
101b21740b4SAndreas Gohr            $filter->add(Filters::$filtermethod('mail', $match['mail']));
102b21740b4SAndreas Gohr        }
103b21740b4SAndreas Gohr        if (isset($match['grps'])) {
104b21740b4SAndreas Gohr            // memberOf can not be checked with a substring match, so we need to get the right groups first
105b21740b4SAndreas Gohr            $groups = $this->getGroups($match['grps'], $filtermethod);
106b21740b4SAndreas Gohr            $or = Filters::or();
107b21740b4SAndreas Gohr            foreach ($groups as $dn => $group) {
108204fba68SAndreas Gohr                // domain users membership is in primary group
109*c2500b44SAndreas Gohr                if ($group === $this->config['primarygroup']) {
110204fba68SAndreas Gohr                    $or->add(Filters::equal('primaryGroupID', 513));
111204fba68SAndreas Gohr                    continue;
112204fba68SAndreas Gohr                }
113204fba68SAndreas Gohr
114b21740b4SAndreas Gohr                $or->add(Filters::equal('memberOf', $dn));
115b21740b4SAndreas Gohr            }
116b21740b4SAndreas Gohr            $filter->add($or);
117b21740b4SAndreas Gohr        }
118b21740b4SAndreas Gohr        $this->debug('Searching ' . $filter->toString(), __FILE__, __LINE__);
1199c590892SAndreas Gohr        $attributes = $this->userAttributes();
1209c590892SAndreas Gohr        $search = Operations::search($filter, ...$attributes);
121b21740b4SAndreas Gohr        $paging = $this->ldap->paging($search);
122b21740b4SAndreas Gohr
123b21740b4SAndreas Gohr        $users = [];
124b21740b4SAndreas Gohr        while ($paging->hasEntries()) {
125b21740b4SAndreas Gohr            try {
126b21740b4SAndreas Gohr                $entries = $paging->getEntries();
127b21740b4SAndreas Gohr            } catch (ProtocolException $e) {
128b21740b4SAndreas Gohr                $this->fatal($e);
12980ac552fSAndreas Gohr                break; // we abort and return what we have so far
130b21740b4SAndreas Gohr            }
131b21740b4SAndreas Gohr
132b21740b4SAndreas Gohr            foreach ($entries as $entry) {
13380ac552fSAndreas Gohr                $userinfo = $this->entry2User($entry);
13480ac552fSAndreas Gohr                $users[$userinfo['user']] = $this->entry2User($entry);
135b21740b4SAndreas Gohr            }
136b21740b4SAndreas Gohr        }
137b21740b4SAndreas Gohr
1381b0eb9b3SAndreas Gohr        ksort($users);
139b21740b4SAndreas Gohr        return $users;
140b21740b4SAndreas Gohr    }
141b21740b4SAndreas Gohr
142a1128cc0SAndreas Gohr    /** @inheritDoc */
143a1128cc0SAndreas Gohr    public function cleanUser($user)
14480ac552fSAndreas Gohr    {
145a1128cc0SAndreas Gohr        return $this->simpleUser($user);
14680ac552fSAndreas Gohr    }
14780ac552fSAndreas Gohr
148a1128cc0SAndreas Gohr    /** @inheritDoc */
149a1128cc0SAndreas Gohr    public function cleanGroup($group)
150a1128cc0SAndreas Gohr    {
151a1128cc0SAndreas Gohr        return PhpString::strtolower($group);
152a1128cc0SAndreas Gohr    }
153a1128cc0SAndreas Gohr
154a1128cc0SAndreas Gohr    /** @inheritDoc */
155a1128cc0SAndreas Gohr    public function prepareBindUser($user)
156a1128cc0SAndreas Gohr    {
157a1128cc0SAndreas Gohr        $user = $this->qualifiedUser($user); // add account suffix
158a1128cc0SAndreas Gohr        return $user;
15980ac552fSAndreas Gohr    }
16080ac552fSAndreas Gohr
16180ac552fSAndreas Gohr    /**
16280ac552fSAndreas Gohr     * @inheritDoc
163a1128cc0SAndreas Gohr     * userPrincipalName in the form <user>@<suffix>
16480ac552fSAndreas Gohr     */
165a1128cc0SAndreas Gohr    protected function qualifiedUser($user)
166a1128cc0SAndreas Gohr    {
167a1128cc0SAndreas Gohr        $user = $this->simpleUser($user); // strip any existing qualifiers
168a1128cc0SAndreas Gohr        if (!$this->config['suffix']) {
169a1128cc0SAndreas Gohr            $this->error('No account suffix set. Logins may fail.', __FILE__, __LINE__);
170a1128cc0SAndreas Gohr        }
171a1128cc0SAndreas Gohr
172a1128cc0SAndreas Gohr        return $user . '@' . $this->config['suffix'];
173a1128cc0SAndreas Gohr    }
174a1128cc0SAndreas Gohr
175a1128cc0SAndreas Gohr    /**
176a1128cc0SAndreas Gohr     * @inheritDoc
177a1128cc0SAndreas Gohr     * Removes the account suffix from the given user. Should match the SAMAccountName
178a1128cc0SAndreas Gohr     */
179a1128cc0SAndreas Gohr    protected function simpleUser($user)
18080ac552fSAndreas Gohr    {
18180ac552fSAndreas Gohr        $user = PhpString::strtolower($user);
182a1128cc0SAndreas Gohr        $user = preg_replace('/@.*$/', '', $user);
183a1128cc0SAndreas Gohr        $user = preg_replace('/^.*\\\\/', '', $user);
18480ac552fSAndreas Gohr        return $user;
18580ac552fSAndreas Gohr    }
18680ac552fSAndreas Gohr
18780ac552fSAndreas Gohr    /**
188b21740b4SAndreas Gohr     * Transform an LDAP entry to a user info array
189b21740b4SAndreas Gohr     *
190b21740b4SAndreas Gohr     * @param Entry $entry
191b21740b4SAndreas Gohr     * @return array
192b21740b4SAndreas Gohr     */
193b21740b4SAndreas Gohr    protected function entry2User(Entry $entry)
194b21740b4SAndreas Gohr    {
195b914569fSAndreas Gohr        $user = [
196a1128cc0SAndreas Gohr            'user' => $this->simpleUser($this->attr2str($entry->get('sAMAccountName'))),
1971078ec26SAndreas Gohr            'name' => $this->attr2str($entry->get('DisplayName')) ?: $this->attr2str($entry->get('Name')),
1981078ec26SAndreas Gohr            'mail' => $this->attr2str($entry->get('mail')),
1991078ec26SAndreas Gohr            'dn' => $entry->getDn()->toString(),
2001078ec26SAndreas Gohr            'grps' => $this->getUserGroups($entry), // we always return groups because its currently inexpensive
2011078ec26SAndreas Gohr        ];
202b914569fSAndreas Gohr
203b914569fSAndreas Gohr        // get additional attributes
204b914569fSAndreas Gohr        foreach ($this->config['attributes'] as $attr) {
205b914569fSAndreas Gohr            $user[$attr] = $this->attr2str($entry->get($attr));
206b914569fSAndreas Gohr        }
207b914569fSAndreas Gohr
208b914569fSAndreas Gohr        return $user;
2091078ec26SAndreas Gohr    }
2101078ec26SAndreas Gohr
2111078ec26SAndreas Gohr    /**
2121078ec26SAndreas Gohr     * Get the list of groups the given user is member of
2131078ec26SAndreas Gohr     *
2141078ec26SAndreas Gohr     * This method currently does no LDAP queries and thus is inexpensive.
2151078ec26SAndreas Gohr     *
2161078ec26SAndreas Gohr     * @param Entry $userentry
2171078ec26SAndreas Gohr     * @return array
2186d90d5c8SAndreas Gohr     * @todo implement nested group memberships FIXME already correct?
2191078ec26SAndreas Gohr     */
2201078ec26SAndreas Gohr    protected function getUserGroups(Entry $userentry)
2211078ec26SAndreas Gohr    {
2221078ec26SAndreas Gohr        $groups = [$this->config['defaultgroup']]; // always add default
2231078ec26SAndreas Gohr
2241078ec26SAndreas Gohr        // we simply take the first CN= part of the group DN and return it as the group name
2251078ec26SAndreas Gohr        // this should be correct for ActiveDirectory and saves us additional LDAP queries
2261078ec26SAndreas Gohr        if ($userentry->has('memberOf')) {
227b21740b4SAndreas Gohr            foreach ($userentry->get('memberOf')->getValues() as $dn) {
228b21740b4SAndreas Gohr                list($cn) = explode(',', $dn, 2);
229a1128cc0SAndreas Gohr                $groups[] = $this->cleanGroup(substr($cn, 3));
2301078ec26SAndreas Gohr            }
2311078ec26SAndreas Gohr        }
2321078ec26SAndreas Gohr
2331078ec26SAndreas Gohr        // resolving the primary group in AD is complicated but basically never needed
2341078ec26SAndreas Gohr        // http://support.microsoft.com/?kbid=321360
2351078ec26SAndreas Gohr        $gid = $userentry->get('primaryGroupID')->firstValue();
2361078ec26SAndreas Gohr        if ($gid == 513) {
237a1128cc0SAndreas Gohr            $groups[] = $this->cleanGroup('domain users');
2381078ec26SAndreas Gohr        }
2391078ec26SAndreas Gohr
2401b0eb9b3SAndreas Gohr        sort($groups);
2411078ec26SAndreas Gohr        return $groups;
2421078ec26SAndreas Gohr    }
2439c590892SAndreas Gohr
2449c590892SAndreas Gohr    /** @inheritDoc */
2459c590892SAndreas Gohr    protected function userAttributes()
2469c590892SAndreas Gohr    {
2479c590892SAndreas Gohr        $attr = parent::userAttributes();
248a1128cc0SAndreas Gohr        $attr[] = new Attribute('sAMAccountName');
2499c590892SAndreas Gohr        $attr[] = new Attribute('Name');
2509c590892SAndreas Gohr        $attr[] = new Attribute('primaryGroupID');
2519c590892SAndreas Gohr        $attr[] = new Attribute('memberOf');
2529c590892SAndreas Gohr
2539c590892SAndreas Gohr        return $attr;
2549c590892SAndreas Gohr    }
2551078ec26SAndreas Gohr}
256