xref: /dokuwiki/lib/plugins/authldap/auth.php (revision 6405e5fd396e2c2834736b0eaaf530f67dd4c034)
1f4476bd9SJan Schumann<?php
2d4f83172SAndreas Gohr
38553d24dSAndreas Gohruse dokuwiki\Extension\AuthPlugin;
4ab9790caSAndreas Gohruse dokuwiki\PassHash;
50489c64bSMoisés Braga Ribeirouse dokuwiki\Utf8\Sort;
6d17fc5deSAndreas Gohr
7f4476bd9SJan Schumann/**
8f4476bd9SJan Schumann * LDAP authentication backend
9f4476bd9SJan Schumann *
10f4476bd9SJan Schumann * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
11f4476bd9SJan Schumann * @author    Andreas Gohr <andi@splitbrain.org>
12f4476bd9SJan Schumann * @author    Chris Smith <chris@jalakaic.co.uk>
13f4476bd9SJan Schumann * @author    Jan Schumann <js@schumann-it.com>
14f4476bd9SJan Schumann */
158553d24dSAndreas Gohrclass auth_plugin_authldap extends AuthPlugin
16d17fc5deSAndreas Gohr{
1770e4a085SAndreas Gohr    /* @var resource $con holds the LDAP connection */
18ab9790caSAndreas Gohr    protected $con;
1970e4a085SAndreas Gohr
2070e4a085SAndreas Gohr    /* @var int $bound What type of connection does already exist? */
2170e4a085SAndreas Gohr    protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
2270e4a085SAndreas Gohr
2370e4a085SAndreas Gohr    /* @var array $users User data cache */
24ab9790caSAndreas Gohr    protected $users;
2570e4a085SAndreas Gohr
26d17fc5deSAndreas Gohr    /* @var array $pattern User filter pattern */
27ab9790caSAndreas Gohr    protected $pattern;
28f4476bd9SJan Schumann
29f4476bd9SJan Schumann    /**
30f4476bd9SJan Schumann     * Constructor
31f4476bd9SJan Schumann     */
32d17fc5deSAndreas Gohr    public function __construct()
33d17fc5deSAndreas Gohr    {
34454d868bSAndreas Gohr        parent::__construct();
35454d868bSAndreas Gohr
36f4476bd9SJan Schumann        // ldap extension is needed
37f4476bd9SJan Schumann        if (!function_exists('ldap_connect')) {
38d17fc5deSAndreas Gohr            $this->debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
39f4476bd9SJan Schumann            $this->success = false;
40f4476bd9SJan Schumann            return;
41f4476bd9SJan Schumann        }
42f4476bd9SJan Schumann
4306da270eSAxel Angel        // Add the capabilities to change the password
446619ddf4SSascha Klopp        $this->cando['modPass'] = $this->getConf('modPass');
45f4476bd9SJan Schumann    }
46f4476bd9SJan Schumann
47f4476bd9SJan Schumann    /**
48f4476bd9SJan Schumann     * Check user+password
49f4476bd9SJan Schumann     *
50f4476bd9SJan Schumann     * Checks if the given user exists and the given
51f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
52f4476bd9SJan Schumann     * to the LDAP server
53f4476bd9SJan Schumann     *
5470e4a085SAndreas Gohr     * @param string $user
5570e4a085SAndreas Gohr     * @param string $pass
56f4476bd9SJan Schumann     * @return  bool
57c0c77cd2SAndreas Gohr     * @author  Andreas Gohr <andi@splitbrain.org>
58f4476bd9SJan Schumann     */
59d17fc5deSAndreas Gohr    public function checkPass($user, $pass)
60d17fc5deSAndreas Gohr    {
61f4476bd9SJan Schumann        // reject empty password
62f4476bd9SJan Schumann        if (empty($pass)) return false;
63d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return false;
64f4476bd9SJan Schumann
65f4476bd9SJan Schumann        // indirect user bind
6670e4a085SAndreas Gohr        if ($this->getConf('binddn') && $this->getConf('bindpw')) {
67f4476bd9SJan Schumann            // use superuser credentials
688ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
69d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
70f4476bd9SJan Schumann                return false;
71f4476bd9SJan Schumann            }
72f4476bd9SJan Schumann            $this->bound = 2;
737d34963bSAndreas Gohr        } elseif (
747d34963bSAndreas Gohr            $this->getConf('binddn') &&
7570e4a085SAndreas Gohr            $this->getConf('usertree') &&
7670e4a085SAndreas Gohr            $this->getConf('userfilter')
7770e4a085SAndreas Gohr        ) {
78f4476bd9SJan Schumann            // special bind string
79d17fc5deSAndreas Gohr            $dn = $this->makeFilter(
8070e4a085SAndreas Gohr                $this->getConf('binddn'),
81ab9790caSAndreas Gohr                ['user' => $user, 'server' => $this->getConf('server')]
8270e4a085SAndreas Gohr            );
8370e4a085SAndreas Gohr        } elseif (strpos($this->getConf('usertree'), '%{user}')) {
84f4476bd9SJan Schumann            // direct user bind
85d17fc5deSAndreas Gohr            $dn = $this->makeFilter(
8670e4a085SAndreas Gohr                $this->getConf('usertree'),
87ab9790caSAndreas Gohr                ['user' => $user, 'server' => $this->getConf('server')]
8870e4a085SAndreas Gohr            );
89ab9790caSAndreas Gohr        } elseif (!@ldap_bind($this->con)) {
90f4476bd9SJan Schumann            // Anonymous bind
91f4476bd9SJan Schumann            msg("LDAP: can not bind anonymously", -1);
92d17fc5deSAndreas Gohr            $this->debug('LDAP anonymous bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
93f4476bd9SJan Schumann            return false;
94f4476bd9SJan Schumann        }
95f4476bd9SJan Schumann
96f4476bd9SJan Schumann        // Try to bind to with the dn if we have one.
97f4476bd9SJan Schumann        if (!empty($dn)) {
98f4476bd9SJan Schumann            // User/Password bind
99f4476bd9SJan Schumann            if (!@ldap_bind($this->con, $dn, $pass)) {
100d17fc5deSAndreas Gohr                $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
101d17fc5deSAndreas Gohr                $this->debug('LDAP user dn bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
102f4476bd9SJan Schumann                return false;
103f4476bd9SJan Schumann            }
104f4476bd9SJan Schumann            $this->bound = 1;
105f4476bd9SJan Schumann            return true;
106f4476bd9SJan Schumann        } else {
107f4476bd9SJan Schumann            // See if we can find the user
108d17fc5deSAndreas Gohr            $info = $this->fetchUserData($user, true);
109f4476bd9SJan Schumann            if (empty($info['dn'])) {
110f4476bd9SJan Schumann                return false;
111f4476bd9SJan Schumann            } else {
112f4476bd9SJan Schumann                $dn = $info['dn'];
113f4476bd9SJan Schumann            }
114f4476bd9SJan Schumann
115f4476bd9SJan Schumann            // Try to bind with the dn provided
116f4476bd9SJan Schumann            if (!@ldap_bind($this->con, $dn, $pass)) {
117d17fc5deSAndreas Gohr                $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
118d17fc5deSAndreas Gohr                $this->debug('LDAP user bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
119f4476bd9SJan Schumann                return false;
120f4476bd9SJan Schumann            }
121f4476bd9SJan Schumann            $this->bound = 1;
122f4476bd9SJan Schumann            return true;
123f4476bd9SJan Schumann        }
124f4476bd9SJan Schumann    }
125f4476bd9SJan Schumann
126f4476bd9SJan Schumann    /**
127f4476bd9SJan Schumann     * Return user info
128f4476bd9SJan Schumann     *
129f4476bd9SJan Schumann     * Returns info about the given user needs to contain
130f4476bd9SJan Schumann     * at least these fields:
131f4476bd9SJan Schumann     *
132f4476bd9SJan Schumann     * name string  full name of the user
133f4476bd9SJan Schumann     * mail string  email addres of the user
134f4476bd9SJan Schumann     * grps array   list of groups the user is in
135f4476bd9SJan Schumann     *
136f4476bd9SJan Schumann     * This LDAP specific function returns the following
137f4476bd9SJan Schumann     * addional fields:
138f4476bd9SJan Schumann     *
139f4476bd9SJan Schumann     * dn     string  distinguished name (DN)
140f4476bd9SJan Schumann     * uid    string  Posix User ID
141f4476bd9SJan Schumann     * inbind bool    for internal use - avoid loop in binding
142f4476bd9SJan Schumann     *
143c0c77cd2SAndreas Gohr     * @param string $user
144c0c77cd2SAndreas Gohr     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
145c0c77cd2SAndreas Gohr     * @return  array containing user data or false
146f4476bd9SJan Schumann     * @author  <evaldas.auryla@pheur.org>
147f4476bd9SJan Schumann     * @author  Stephane Chazelas <stephane.chazelas@emerson.com>
1483e23f03eSSteScho     * @author  Steffen Schoch <schoch@dsb.net>
14970e4a085SAndreas Gohr     *
150c0c77cd2SAndreas Gohr     * @author  Andreas Gohr <andi@splitbrain.org>
151c0c77cd2SAndreas Gohr     * @author  Trouble
152c0c77cd2SAndreas Gohr     * @author  Dan Allen <dan.j.allen@gmail.com>
153d397e6daSChristopher Smith     */
154d17fc5deSAndreas Gohr    public function getUserData($user, $requireGroups = true)
155d17fc5deSAndreas Gohr    {
156d17fc5deSAndreas Gohr        return $this->fetchUserData($user);
157d397e6daSChristopher Smith    }
158d397e6daSChristopher Smith
159d397e6daSChristopher Smith    /**
160d397e6daSChristopher Smith     * @param string $user
16170e4a085SAndreas Gohr     * @param bool $inbind authldap specific, true if in bind phase
162f4476bd9SJan Schumann     * @return  array containing user data or false
163f4476bd9SJan Schumann     */
164d17fc5deSAndreas Gohr    protected function fetchUserData($user, $inbind = false)
165d17fc5deSAndreas Gohr    {
166f4476bd9SJan Schumann        global $conf;
167ab9790caSAndreas Gohr        if (!$this->openLDAP()) return [];
168f4476bd9SJan Schumann
169f4476bd9SJan Schumann        // force superuser bind if wanted and not bound as superuser yet
17070e4a085SAndreas Gohr        if ($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
171f4476bd9SJan Schumann            // use superuser credentials
1728ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
173d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
174ab9790caSAndreas Gohr                return [];
175f4476bd9SJan Schumann            }
176f4476bd9SJan Schumann            $this->bound = 2;
177f4476bd9SJan Schumann        } elseif ($this->bound == 0 && !$inbind) {
178f4476bd9SJan Schumann            // in some cases getUserData is called outside the authentication workflow
179f4476bd9SJan Schumann            // eg. for sending email notification on subscribed pages. This data might not
180f4476bd9SJan Schumann            // be accessible anonymously, so we try to rebind the current user here
181ab9790caSAndreas Gohr            [$loginuser, $loginsticky, $loginpass] = auth_getCookie();
182f4476bd9SJan Schumann            if ($loginuser && $loginpass) {
183b4304655SMichael Hamann                $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
184f4476bd9SJan Schumann                $this->checkPass($loginuser, $loginpass);
185f4476bd9SJan Schumann            }
186f4476bd9SJan Schumann        }
187f4476bd9SJan Schumann
188ab9790caSAndreas Gohr        $info = [];
189f4476bd9SJan Schumann        $info['user'] = $user;
190d17fc5deSAndreas Gohr        $this->debug('LDAP user to find: ' . hsc($info['user']), 0, __LINE__, __FILE__);
19140017f0bSItamar Shoham
19270e4a085SAndreas Gohr        $info['server'] = $this->getConf('server');
193d17fc5deSAndreas Gohr        $this->debug('LDAP Server: ' . hsc($info['server']), 0, __LINE__, __FILE__);
194f4476bd9SJan Schumann
195f4476bd9SJan Schumann        //get info for given user
196d17fc5deSAndreas Gohr        $base = $this->makeFilter($this->getConf('usertree'), $info);
19770e4a085SAndreas Gohr        if ($this->getConf('userfilter')) {
198d17fc5deSAndreas Gohr            $filter = $this->makeFilter($this->getConf('userfilter'), $info);
199f4476bd9SJan Schumann        } else {
200f4476bd9SJan Schumann            $filter = "(ObjectClass=*)";
201f4476bd9SJan Schumann        }
202f4476bd9SJan Schumann
203d17fc5deSAndreas Gohr        $this->debug('LDAP Filter: ' . hsc($filter), 0, __LINE__, __FILE__);
20440017f0bSItamar Shoham
205d17fc5deSAndreas Gohr        $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
206c0c77cd2SAndreas Gohr        $sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope'), $this->getConf('attributes'));
207821c061aSAndreas Gohr        $this->debug('LDAP user search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
20883616da3Shydrian        if ($sr === false) {
20983616da3Shydrian            $this->debug('User ldap_search failed. Check configuration.', 0, __LINE__, __FILE__);
2101c6fde61SBen Tyger            return false;
21183616da3Shydrian        }
21240017f0bSItamar Shoham
21340017f0bSItamar Shoham        $result = @ldap_get_entries($this->con, $sr);
21440017f0bSItamar Shoham
21540017f0bSItamar Shoham        // if result is not an array
21640017f0bSItamar Shoham        if (!is_array($result)) {
21740017f0bSItamar Shoham            // no objects found
218d17fc5deSAndreas Gohr            $this->debug('LDAP search returned non-array result: ' . hsc(print($result)), -1, __LINE__, __FILE__);
219ab9790caSAndreas Gohr            return [];
22040017f0bSItamar Shoham        }
221f4476bd9SJan Schumann
222f4476bd9SJan Schumann        // Don't accept more or less than one response
22340017f0bSItamar Shoham        if ($result['count'] != 1) {
224d17fc5deSAndreas Gohr            $this->debug(
22564159a61SAndreas Gohr                'LDAP search returned ' . hsc($result['count']) . ' results while it should return 1!',
226d17fc5deSAndreas Gohr                -1,
227d17fc5deSAndreas Gohr                __LINE__,
228d17fc5deSAndreas Gohr                __FILE__
22964159a61SAndreas Gohr            );
23040017f0bSItamar Shoham            //for($i = 0; $i < $result["count"]; $i++) {
23164159a61SAndreas Gohr            //$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__);
23240017f0bSItamar Shoham            //}
233ab9790caSAndreas Gohr            return [];
234f4476bd9SJan Schumann        }
235f4476bd9SJan Schumann
236d17fc5deSAndreas Gohr        $this->debug('LDAP search found single result !', 0, __LINE__, __FILE__);
23740017f0bSItamar Shoham
238f4476bd9SJan Schumann        $user_result = $result[0];
239f4476bd9SJan Schumann        ldap_free_result($sr);
240f4476bd9SJan Schumann
241f4476bd9SJan Schumann        // general user info
242f4476bd9SJan Schumann        $info['dn'] = $user_result['dn'];
24382be9eabSGirish Ramakrishnan        $info['gid'] = $user_result['gidnumber'][0] ?? null;
244f4476bd9SJan Schumann        $info['mail'] = $user_result['mail'][0];
245f4476bd9SJan Schumann        $info['name'] = $user_result['cn'][0];
246ab9790caSAndreas Gohr        $info['grps'] = [];
247f4476bd9SJan Schumann
248f4476bd9SJan Schumann        // overwrite if other attribs are specified.
24970e4a085SAndreas Gohr        if (is_array($this->getConf('mapping'))) {
25070e4a085SAndreas Gohr            foreach ($this->getConf('mapping') as $localkey => $key) {
251f4476bd9SJan Schumann                if (is_array($key)) {
252f4476bd9SJan Schumann                    // use regexp to clean up user_result
2538f1011e8SPhy                    // $key = array($key=>$regexp), only handles the first key-value
2548f1011e8SPhy                    $regexp = current($key);
2558f1011e8SPhy                    $key = key($key);
2564f11d93dSGerrit Uitslag                    if ($user_result[$key]) foreach ($user_result[$key] as $grpkey => $grp) {
2574f11d93dSGerrit Uitslag                        if ($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
258f4476bd9SJan Schumann                            if ($localkey == 'grps') {
259f4476bd9SJan Schumann                                $info[$localkey][] = $match[1];
260f4476bd9SJan Schumann                            } else {
261f4476bd9SJan Schumann                                $info[$localkey] = $match[1];
262f4476bd9SJan Schumann                            }
263f4476bd9SJan Schumann                        }
264f4476bd9SJan Schumann                    }
265f4476bd9SJan Schumann                } else {
266f4476bd9SJan Schumann                    $info[$localkey] = $user_result[$key][0];
267f4476bd9SJan Schumann                }
268f4476bd9SJan Schumann            }
269f4476bd9SJan Schumann        }
270f4476bd9SJan Schumann        $user_result = array_merge($info, $user_result);
271f4476bd9SJan Schumann
272f4476bd9SJan Schumann        //get groups for given user if grouptree is given
27370e4a085SAndreas Gohr        if ($this->getConf('grouptree') || $this->getConf('groupfilter')) {
274d17fc5deSAndreas Gohr            $base = $this->makeFilter($this->getConf('grouptree'), $user_result);
275d17fc5deSAndreas Gohr            $filter = $this->makeFilter($this->getConf('groupfilter'), $user_result);
276d17fc5deSAndreas Gohr            $sr = $this->ldapSearch(
27764159a61SAndreas Gohr                $this->con,
27864159a61SAndreas Gohr                $base,
27964159a61SAndreas Gohr                $filter,
28064159a61SAndreas Gohr                $this->getConf('groupscope'),
281ab9790caSAndreas Gohr                [$this->getConf('groupkey')]
282d17fc5deSAndreas Gohr            );
283d17fc5deSAndreas Gohr            $this->debug('LDAP group search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
284d17fc5deSAndreas Gohr            $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
28570e4a085SAndreas Gohr
286f4476bd9SJan Schumann            if (!$sr) {
287f4476bd9SJan Schumann                msg("LDAP: Reading group memberships failed", -1);
288ab9790caSAndreas Gohr                return [];
289f4476bd9SJan Schumann            }
290f4476bd9SJan Schumann            $result = ldap_get_entries($this->con, $sr);
291f4476bd9SJan Schumann            ldap_free_result($sr);
292f4476bd9SJan Schumann
293f4476bd9SJan Schumann            if (is_array($result)) foreach ($result as $grp) {
2949f72d639SAndreas Gohr                if (!empty($grp[$this->getConf('groupkey')])) {
2959f72d639SAndreas Gohr                    $group = $grp[$this->getConf('groupkey')];
2969f72d639SAndreas Gohr                    if (is_array($group)) {
2979f72d639SAndreas Gohr                        $group = $group[0];
2989f72d639SAndreas Gohr                    } else {
299d17fc5deSAndreas Gohr                        $this->debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
3009f72d639SAndreas Gohr                    }
3019f72d639SAndreas Gohr                    if ($group === '') continue;
3029f72d639SAndreas Gohr
303d17fc5deSAndreas Gohr                    $this->debug('LDAP usergroup: ' . hsc($group), 0, __LINE__, __FILE__);
3049f72d639SAndreas Gohr                    $info['grps'][] = $group;
305f4476bd9SJan Schumann                }
306f4476bd9SJan Schumann            }
307f4476bd9SJan Schumann        }
308f4476bd9SJan Schumann
309f4476bd9SJan Schumann        // always add the default group to the list of groups
310ab9790caSAndreas Gohr        if (!$info['grps'] || !in_array($conf['defaultgroup'], $info['grps'])) {
311f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
312f4476bd9SJan Schumann        }
313f4476bd9SJan Schumann        return $info;
314f4476bd9SJan Schumann    }
315f4476bd9SJan Schumann
316f4476bd9SJan Schumann    /**
31706da270eSAxel Angel     * Definition of the function modifyUser in order to modify the password
318b83b4364SGerrit Uitslag     *
319b83b4364SGerrit Uitslag     * @param string $user nick of the user to be changed
320b83b4364SGerrit Uitslag     * @param array $changes array of field/value pairs to be changed (password will be clear text)
321b83b4364SGerrit Uitslag     * @return  bool   true on success, false on error
32206da270eSAxel Angel     */
323d17fc5deSAndreas Gohr    public function modifyUser($user, $changes)
324d17fc5deSAndreas Gohr    {
32506da270eSAxel Angel
32606da270eSAxel Angel        // open the connection to the ldap
327d17fc5deSAndreas Gohr        if (!$this->openLDAP()) {
328d17fc5deSAndreas Gohr            $this->debug('LDAP cannot connect: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
32906da270eSAxel Angel            return false;
33006da270eSAxel Angel        }
33106da270eSAxel Angel
33206da270eSAxel Angel        // find the information about the user, in particular the "dn"
33306da270eSAxel Angel        $info = $this->getUserData($user, true);
33406da270eSAxel Angel        if (empty($info['dn'])) {
335d17fc5deSAndreas Gohr            $this->debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__);
33606da270eSAxel Angel            return false;
3378f2ea93bSAxel Angel        }
33806da270eSAxel Angel        $dn = $info['dn'];
33906da270eSAxel Angel
34006da270eSAxel Angel        // find the old password of the user
341ab9790caSAndreas Gohr        [$loginuser, $loginsticky, $loginpass] = auth_getCookie();
342719c6730SAxel Angel        if ($loginuser !== null) { // the user is currently logged in
34318496fe0SAndreas Gohr            $secret = auth_cookiesalt(!$loginsticky, true);
34406da270eSAxel Angel            $pass = auth_decrypt($loginpass, $secret);
34506da270eSAxel Angel
34606da270eSAxel Angel            // bind with the ldap
34706da270eSAxel Angel            if (!@ldap_bind($this->con, $dn, $pass)) {
348d17fc5deSAndreas Gohr                $this->debug(
349d17fc5deSAndreas Gohr                    'LDAP user bind failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
350d17fc5deSAndreas Gohr                    0,
351d17fc5deSAndreas Gohr                    __LINE__,
352d17fc5deSAndreas Gohr                    __FILE__
35364159a61SAndreas Gohr                );
35406da270eSAxel Angel                return false;
35506da270eSAxel Angel            }
356719c6730SAxel Angel        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
357719c6730SAxel Angel            // we are changing the password on behalf of the user (eg: forgotten password)
358719c6730SAxel Angel            // bind with the superuser ldap
3598ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
360d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
361719c6730SAxel Angel                return false;
362719c6730SAxel Angel            }
363d17fc5deSAndreas Gohr        } else {
364719c6730SAxel Angel            return false; // no otherway
365719c6730SAxel Angel        }
36606da270eSAxel Angel
36767723447SAxel Angel        // Generate the salted hashed password for LDAP
368*6405e5fdSspike        if ($this->getConf('modPassPlain')) {
369*6405e5fdSspike            $hash = $changes['pass'];
370*6405e5fdSspike        } else {
371ab9790caSAndreas Gohr            $phash = new PassHash();
37267723447SAxel Angel            $hash = $phash->hash_ssha($changes['pass']);
373*6405e5fdSspike        }
37467723447SAxel Angel
37506da270eSAxel Angel        // change the password
376ab9790caSAndreas Gohr        if (!@ldap_mod_replace($this->con, $dn, ['userpassword' => $hash])) {
377d17fc5deSAndreas Gohr            $this->debug(
378d17fc5deSAndreas Gohr                'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
379d17fc5deSAndreas Gohr                0,
380d17fc5deSAndreas Gohr                __LINE__,
381d17fc5deSAndreas Gohr                __FILE__
38264159a61SAndreas Gohr            );
38306da270eSAxel Angel            return false;
38406da270eSAxel Angel        }
38506da270eSAxel Angel
38606da270eSAxel Angel        return true;
38706da270eSAxel Angel    }
38806da270eSAxel Angel
38906da270eSAxel Angel    /**
390f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
39170e4a085SAndreas Gohr     *
39270e4a085SAndreas Gohr     * @return bool
393f4476bd9SJan Schumann     */
394d17fc5deSAndreas Gohr    public function isCaseSensitive()
395d17fc5deSAndreas Gohr    {
396f4476bd9SJan Schumann        return false;
397f4476bd9SJan Schumann    }
398f4476bd9SJan Schumann
399f4476bd9SJan Schumann    /**
400f4476bd9SJan Schumann     * Bulk retrieval of user data
401f4476bd9SJan Schumann     *
40270e4a085SAndreas Gohr     * @param int $start index of first user to be returned
40370e4a085SAndreas Gohr     * @param int $limit max number of users to be returned
40470e4a085SAndreas Gohr     * @param array $filter array of field/pattern pairs, null for no filter
405f4476bd9SJan Schumann     * @return  array of userinfo (refer getUserData for internal userinfo details)
406c0c77cd2SAndreas Gohr     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
407f4476bd9SJan Schumann     */
408ab9790caSAndreas Gohr    public function retrieveUsers($start = 0, $limit = 0, $filter = [])
409d17fc5deSAndreas Gohr    {
410ab9790caSAndreas Gohr        if (!$this->openLDAP()) return [];
411f4476bd9SJan Schumann
41270e4a085SAndreas Gohr        if (is_null($this->users)) {
413f4476bd9SJan Schumann            // Perform the search and grab all their details
41470e4a085SAndreas Gohr            if ($this->getConf('userfilter')) {
41570e4a085SAndreas Gohr                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
416f4476bd9SJan Schumann            } else {
417f4476bd9SJan Schumann                $all_filter = "(ObjectClass=*)";
418f4476bd9SJan Schumann            }
41970e4a085SAndreas Gohr            $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
420f4476bd9SJan Schumann            $entries = ldap_get_entries($this->con, $sr);
421ab9790caSAndreas Gohr            $users_array = [];
4226619ddf4SSascha Klopp            $userkey = $this->getConf('userkey');
423f4476bd9SJan Schumann            for ($i = 0; $i < $entries["count"]; $i++) {
424ab9790caSAndreas Gohr                $users_array[] = $entries[$i][$userkey][0];
425f4476bd9SJan Schumann            }
4260489c64bSMoisés Braga Ribeiro            Sort::asort($users_array);
427f4476bd9SJan Schumann            $result = $users_array;
428ab9790caSAndreas Gohr            if (!$result) return [];
429f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
430f4476bd9SJan Schumann        }
431f4476bd9SJan Schumann        $i = 0;
432f4476bd9SJan Schumann        $count = 0;
433d17fc5deSAndreas Gohr        $this->constructPattern($filter);
434ab9790caSAndreas Gohr        $result = [];
435f4476bd9SJan Schumann
436f4476bd9SJan Schumann        foreach ($this->users as $user => &$info) {
437f4476bd9SJan Schumann            if ($i++ < $start) {
438f4476bd9SJan Schumann                continue;
439f4476bd9SJan Schumann            }
440f4476bd9SJan Schumann            if ($info === false) {
441f4476bd9SJan Schumann                $info = $this->getUserData($user);
442f4476bd9SJan Schumann            }
443d17fc5deSAndreas Gohr            if ($this->filter($user, $info)) {
444f4476bd9SJan Schumann                $result[$user] = $info;
4459a2c73e8SAndreas Gohr                if (($limit > 0) && (++$count >= $limit)) break;
446f4476bd9SJan Schumann            }
447f4476bd9SJan Schumann        }
448f4476bd9SJan Schumann        return $result;
449f4476bd9SJan Schumann    }
450f4476bd9SJan Schumann
451f4476bd9SJan Schumann    /**
452f4476bd9SJan Schumann     * Make LDAP filter strings.
453f4476bd9SJan Schumann     *
454f4476bd9SJan Schumann     * Used by auth_getUserData to make the filter
455f4476bd9SJan Schumann     * strings for grouptree and groupfilter
456f4476bd9SJan Schumann     *
45770e4a085SAndreas Gohr     * @param string $filter ldap search filter with placeholders
45870e4a085SAndreas Gohr     * @param array $placeholders placeholders to fill in
459f4476bd9SJan Schumann     * @return  string
460c0c77cd2SAndreas Gohr     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
461f4476bd9SJan Schumann     */
462d17fc5deSAndreas Gohr    protected function makeFilter($filter, $placeholders)
463d17fc5deSAndreas Gohr    {
464f4476bd9SJan Schumann        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
465f4476bd9SJan Schumann        //replace each match
466f4476bd9SJan Schumann        foreach ($matches[1] as $match) {
467f4476bd9SJan Schumann            //take first element if array
468f4476bd9SJan Schumann            if (is_array($placeholders[$match])) {
469f4476bd9SJan Schumann                $value = $placeholders[$match][0];
470f4476bd9SJan Schumann            } else {
471f4476bd9SJan Schumann                $value = $placeholders[$match];
472f4476bd9SJan Schumann            }
473d17fc5deSAndreas Gohr            $value = $this->filterEscape($value);
474f4476bd9SJan Schumann            $filter = str_replace('%{' . $match . '}', $value, $filter);
475f4476bd9SJan Schumann        }
476f4476bd9SJan Schumann        return $filter;
477f4476bd9SJan Schumann    }
478f4476bd9SJan Schumann
479f4476bd9SJan Schumann    /**
48070e4a085SAndreas Gohr     * return true if $user + $info match $filter criteria, false otherwise
481f4476bd9SJan Schumann     *
48270e4a085SAndreas Gohr     * @param string $user the user's login name
48370e4a085SAndreas Gohr     * @param array $info the user's userinfo array
48470e4a085SAndreas Gohr     * @return bool
485c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
486c0c77cd2SAndreas Gohr     *
487f4476bd9SJan Schumann     */
488d17fc5deSAndreas Gohr    protected function filter($user, $info)
489d17fc5deSAndreas Gohr    {
490d17fc5deSAndreas Gohr        foreach ($this->pattern as $item => $pattern) {
491f4476bd9SJan Schumann            if ($item == 'user') {
49270e4a085SAndreas Gohr                if (!preg_match($pattern, $user)) return false;
493f4476bd9SJan Schumann            } elseif ($item == 'grps') {
49470e4a085SAndreas Gohr                if (!count(preg_grep($pattern, $info['grps']))) return false;
495ab9790caSAndreas Gohr            } elseif (!preg_match($pattern, $info[$item])) {
496ab9790caSAndreas Gohr                return false;
497f4476bd9SJan Schumann            }
498f4476bd9SJan Schumann        }
49970e4a085SAndreas Gohr        return true;
500f4476bd9SJan Schumann    }
501f4476bd9SJan Schumann
50270e4a085SAndreas Gohr    /**
50370e4a085SAndreas Gohr     * Set the filter pattern
50470e4a085SAndreas Gohr     *
50570e4a085SAndreas Gohr     * @param $filter
50670e4a085SAndreas Gohr     * @return void
507c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
508c0c77cd2SAndreas Gohr     *
50970e4a085SAndreas Gohr     */
510d17fc5deSAndreas Gohr    protected function constructPattern($filter)
511d17fc5deSAndreas Gohr    {
512ab9790caSAndreas Gohr        $this->pattern = [];
513f4476bd9SJan Schumann        foreach ($filter as $item => $pattern) {
514d17fc5deSAndreas Gohr            $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
515f4476bd9SJan Schumann        }
516f4476bd9SJan Schumann    }
517f4476bd9SJan Schumann
518f4476bd9SJan Schumann    /**
519f4476bd9SJan Schumann     * Escape a string to be used in a LDAP filter
520f4476bd9SJan Schumann     *
521f4476bd9SJan Schumann     * Ported from Perl's Net::LDAP::Util escape_filter_value
522f4476bd9SJan Schumann     *
52370e4a085SAndreas Gohr     * @param string $string
52470e4a085SAndreas Gohr     * @return string
525c0c77cd2SAndreas Gohr     * @author Andreas Gohr
526f4476bd9SJan Schumann     */
527d17fc5deSAndreas Gohr    protected function filterEscape($string)
528d17fc5deSAndreas Gohr    {
529234b5c9aSBernhard Liebl        // see https://github.com/adldap/adLDAP/issues/22
530234b5c9aSBernhard Liebl        return preg_replace_callback(
531234b5c9aSBernhard Liebl            '/([\x00-\x1F\*\(\)\\\\])/',
532ab9790caSAndreas Gohr            static fn($matches) => "\\" . implode("", unpack("H2", $matches[1])),
53370e4a085SAndreas Gohr            $string
53470e4a085SAndreas Gohr        );
535f4476bd9SJan Schumann    }
536f4476bd9SJan Schumann
537f4476bd9SJan Schumann    /**
538f4476bd9SJan Schumann     * Opens a connection to the configured LDAP server and sets the wanted
539f4476bd9SJan Schumann     * option on the connection
540f4476bd9SJan Schumann     *
541f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
542f4476bd9SJan Schumann     */
543d17fc5deSAndreas Gohr    protected function openLDAP()
544d17fc5deSAndreas Gohr    {
545f4476bd9SJan Schumann        if ($this->con) return true; // connection already established
546f4476bd9SJan Schumann
547234b5c9aSBernhard Liebl        if ($this->getConf('debug')) {
548d17fc5deSAndreas Gohr            ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
549234b5c9aSBernhard Liebl        }
550234b5c9aSBernhard Liebl
551f4476bd9SJan Schumann        $this->bound = 0;
552f4476bd9SJan Schumann
55370e4a085SAndreas Gohr        $port = $this->getConf('port');
55493a7873eSAndreas Gohr        $bound = false;
55570e4a085SAndreas Gohr        $servers = explode(',', $this->getConf('server'));
55693a7873eSAndreas Gohr        foreach ($servers as $server) {
55793a7873eSAndreas Gohr            $server = trim($server);
558cff9a541SNathan Neulinger            if (str_starts_with($server, 'ldap://') || str_starts_with($server, 'ldaps://')) {
559cff9a541SNathan Neulinger                $this->con = @ldap_connect($server);
560cff9a541SNathan Neulinger            } else {
56193a7873eSAndreas Gohr                $this->con = @ldap_connect($server, $port);
562cff9a541SNathan Neulinger            }
563f4476bd9SJan Schumann            if (!$this->con) {
56493a7873eSAndreas Gohr                continue;
565f4476bd9SJan Schumann            }
566f4476bd9SJan Schumann
56793a7873eSAndreas Gohr            /*
56893a7873eSAndreas Gohr             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
56993a7873eSAndreas Gohr             * not actually connect but just initializes the connecting parameters. The actual
57093a7873eSAndreas Gohr             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
57193a7873eSAndreas Gohr             *
57293a7873eSAndreas Gohr             * So we should try to bind to server in order to check its availability.
57393a7873eSAndreas Gohr             */
57493a7873eSAndreas Gohr
575f4476bd9SJan Schumann            //set protocol version and dependend options
57670e4a085SAndreas Gohr            if ($this->getConf('version')) {
5777d34963bSAndreas Gohr                if (
5787d34963bSAndreas Gohr                    !@ldap_set_option(
579d17fc5deSAndreas Gohr                        $this->con,
580d17fc5deSAndreas Gohr                        LDAP_OPT_PROTOCOL_VERSION,
58170e4a085SAndreas Gohr                        $this->getConf('version')
58270e4a085SAndreas Gohr                    )
58370e4a085SAndreas Gohr                ) {
58470e4a085SAndreas Gohr                    msg('Setting LDAP Protocol version ' . $this->getConf('version') . ' failed', -1);
585d17fc5deSAndreas Gohr                    $this->debug('LDAP version set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
586f4476bd9SJan Schumann                } else {
587f4476bd9SJan Schumann                    //use TLS (needs version 3)
58870e4a085SAndreas Gohr                    if ($this->getConf('starttls')) {
589f4476bd9SJan Schumann                        if (!@ldap_start_tls($this->con)) {
590f4476bd9SJan Schumann                            msg('Starting TLS failed', -1);
591d17fc5deSAndreas Gohr                            $this->debug('LDAP TLS set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
592f4476bd9SJan Schumann                        }
593f4476bd9SJan Schumann                    }
594f4476bd9SJan Schumann                    // needs version 3
595d75d76b2SAndreas Gohr                    if ($this->getConf('referrals') > -1) {
5967d34963bSAndreas Gohr                        if (
5977d34963bSAndreas Gohr                            !@ldap_set_option(
598d17fc5deSAndreas Gohr                                $this->con,
599d17fc5deSAndreas Gohr                                LDAP_OPT_REFERRALS,
60070e4a085SAndreas Gohr                                $this->getConf('referrals')
60170e4a085SAndreas Gohr                            )
60270e4a085SAndreas Gohr                        ) {
603d75d76b2SAndreas Gohr                            msg('Setting LDAP referrals failed', -1);
604d17fc5deSAndreas Gohr                            $this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
605f4476bd9SJan Schumann                        }
606f4476bd9SJan Schumann                    }
607f4476bd9SJan Schumann                }
608f4476bd9SJan Schumann            }
609f4476bd9SJan Schumann
610f4476bd9SJan Schumann            //set deref mode
61170e4a085SAndreas Gohr            if ($this->getConf('deref')) {
61270e4a085SAndreas Gohr                if (!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
61370e4a085SAndreas Gohr                    msg('Setting LDAP Deref mode ' . $this->getConf('deref') . ' failed', -1);
614d17fc5deSAndreas Gohr                    $this->debug('LDAP deref set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
615f4476bd9SJan Schumann                }
616f4476bd9SJan Schumann            }
61793a7873eSAndreas Gohr            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
61893a7873eSAndreas Gohr            if (defined('LDAP_OPT_NETWORK_TIMEOUT')) {
61993a7873eSAndreas Gohr                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
62093a7873eSAndreas Gohr            }
621a426a6cdSAndreas Gohr
622a426a6cdSAndreas Gohr            if ($this->getConf('binddn') && $this->getConf('bindpw')) {
6238ef94e9eSAndreas Gohr                $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
624a426a6cdSAndreas Gohr                $this->bound = 2;
625a426a6cdSAndreas Gohr            } else {
62693a7873eSAndreas Gohr                $bound = @ldap_bind($this->con);
627a426a6cdSAndreas Gohr            }
62893a7873eSAndreas Gohr            if ($bound) {
62993a7873eSAndreas Gohr                break;
63093a7873eSAndreas Gohr            }
63193a7873eSAndreas Gohr        }
63293a7873eSAndreas Gohr
63393a7873eSAndreas Gohr        if (!$bound) {
63493a7873eSAndreas Gohr            msg("LDAP: couldn't connect to LDAP server", -1);
635d17fc5deSAndreas Gohr            $this->debug(ldap_error($this->con), 0, __LINE__, __FILE__);
63693a7873eSAndreas Gohr            return false;
63793a7873eSAndreas Gohr        }
63893a7873eSAndreas Gohr
63970e4a085SAndreas Gohr        $this->cando['getUsers'] = true;
640f4476bd9SJan Schumann        return true;
641f4476bd9SJan Schumann    }
642f4476bd9SJan Schumann
643f4476bd9SJan Schumann    /**
644f4476bd9SJan Schumann     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
645f4476bd9SJan Schumann     *
64670e4a085SAndreas Gohr     * @param resource $link_identifier
64770e4a085SAndreas Gohr     * @param string $base_dn
64870e4a085SAndreas Gohr     * @param string $filter
64970e4a085SAndreas Gohr     * @param string $scope can be 'base', 'one' or 'sub'
650e0c26282SGerrit Uitslag     * @param null|array $attributes
65170e4a085SAndreas Gohr     * @param int $attrsonly
65270e4a085SAndreas Gohr     * @param int $sizelimit
65370e4a085SAndreas Gohr     * @return resource
654c0c77cd2SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
655f4476bd9SJan Schumann     */
656d17fc5deSAndreas Gohr    protected function ldapSearch(
657d17fc5deSAndreas Gohr        $link_identifier,
658d17fc5deSAndreas Gohr        $base_dn,
659d17fc5deSAndreas Gohr        $filter,
660d17fc5deSAndreas Gohr        $scope = 'sub',
661d17fc5deSAndreas Gohr        $attributes = null,
662d17fc5deSAndreas Gohr        $attrsonly = 0,
663d17fc5deSAndreas Gohr        $sizelimit = 0
664d868eb89SAndreas Gohr    ) {
665ab9790caSAndreas Gohr        if (is_null($attributes)) $attributes = [];
666f4476bd9SJan Schumann
667f4476bd9SJan Schumann        if ($scope == 'base') {
66870e4a085SAndreas Gohr            return @ldap_read(
669d17fc5deSAndreas Gohr                $link_identifier,
670d17fc5deSAndreas Gohr                $base_dn,
671d17fc5deSAndreas Gohr                $filter,
672d17fc5deSAndreas Gohr                $attributes,
673d17fc5deSAndreas Gohr                $attrsonly,
674d17fc5deSAndreas Gohr                $sizelimit
67570e4a085SAndreas Gohr            );
676f4476bd9SJan Schumann        } elseif ($scope == 'one') {
67770e4a085SAndreas Gohr            return @ldap_list(
678d17fc5deSAndreas Gohr                $link_identifier,
679d17fc5deSAndreas Gohr                $base_dn,
680d17fc5deSAndreas Gohr                $filter,
681d17fc5deSAndreas Gohr                $attributes,
682d17fc5deSAndreas Gohr                $attrsonly,
683d17fc5deSAndreas Gohr                $sizelimit
68470e4a085SAndreas Gohr            );
685f4476bd9SJan Schumann        } else {
68670e4a085SAndreas Gohr            return @ldap_search(
687d17fc5deSAndreas Gohr                $link_identifier,
688d17fc5deSAndreas Gohr                $base_dn,
689d17fc5deSAndreas Gohr                $filter,
690d17fc5deSAndreas Gohr                $attributes,
691d17fc5deSAndreas Gohr                $attrsonly,
692d17fc5deSAndreas Gohr                $sizelimit
69370e4a085SAndreas Gohr            );
694f4476bd9SJan Schumann        }
695f4476bd9SJan Schumann    }
69670e4a085SAndreas Gohr
69770e4a085SAndreas Gohr    /**
69870e4a085SAndreas Gohr     * Wrapper around msg() but outputs only when debug is enabled
69970e4a085SAndreas Gohr     *
70070e4a085SAndreas Gohr     * @param string $message
70170e4a085SAndreas Gohr     * @param int $err
70270e4a085SAndreas Gohr     * @param int $line
70370e4a085SAndreas Gohr     * @param string $file
70470e4a085SAndreas Gohr     * @return void
70570e4a085SAndreas Gohr     */
706d17fc5deSAndreas Gohr    protected function debug($message, $err, $line, $file)
707d17fc5deSAndreas Gohr    {
70870e4a085SAndreas Gohr        if (!$this->getConf('debug')) return;
70970e4a085SAndreas Gohr        msg($message, $err, $line, $file);
71070e4a085SAndreas Gohr    }
711f4476bd9SJan Schumann}
712