xref: /dokuwiki/lib/plugins/authldap/auth.php (revision d4f83172d9533c4d84f450fe22ef630816b21d75)
1f4476bd9SJan Schumann<?php
2*d4f83172SAndreas 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 user search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
206d17fc5deSAndreas Gohr        $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
207c0c77cd2SAndreas Gohr        $sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope'), $this->getConf('attributes'));
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
368ab9790caSAndreas Gohr        $phash = new PassHash();
36967723447SAxel Angel        $hash = $phash->hash_ssha($changes['pass']);
37067723447SAxel Angel
37106da270eSAxel Angel        // change the password
372ab9790caSAndreas Gohr        if (!@ldap_mod_replace($this->con, $dn, ['userpassword' => $hash])) {
373d17fc5deSAndreas Gohr            $this->debug(
374d17fc5deSAndreas Gohr                'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
375d17fc5deSAndreas Gohr                0,
376d17fc5deSAndreas Gohr                __LINE__,
377d17fc5deSAndreas Gohr                __FILE__
37864159a61SAndreas Gohr            );
37906da270eSAxel Angel            return false;
38006da270eSAxel Angel        }
38106da270eSAxel Angel
38206da270eSAxel Angel        return true;
38306da270eSAxel Angel    }
38406da270eSAxel Angel
38506da270eSAxel Angel    /**
386f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
38770e4a085SAndreas Gohr     *
38870e4a085SAndreas Gohr     * @return bool
389f4476bd9SJan Schumann     */
390d17fc5deSAndreas Gohr    public function isCaseSensitive()
391d17fc5deSAndreas Gohr    {
392f4476bd9SJan Schumann        return false;
393f4476bd9SJan Schumann    }
394f4476bd9SJan Schumann
395f4476bd9SJan Schumann    /**
396f4476bd9SJan Schumann     * Bulk retrieval of user data
397f4476bd9SJan Schumann     *
39870e4a085SAndreas Gohr     * @param int $start index of first user to be returned
39970e4a085SAndreas Gohr     * @param int $limit max number of users to be returned
40070e4a085SAndreas Gohr     * @param array $filter array of field/pattern pairs, null for no filter
401f4476bd9SJan Schumann     * @return  array of userinfo (refer getUserData for internal userinfo details)
402c0c77cd2SAndreas Gohr     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
403f4476bd9SJan Schumann     */
404ab9790caSAndreas Gohr    public function retrieveUsers($start = 0, $limit = 0, $filter = [])
405d17fc5deSAndreas Gohr    {
406ab9790caSAndreas Gohr        if (!$this->openLDAP()) return [];
407f4476bd9SJan Schumann
40870e4a085SAndreas Gohr        if (is_null($this->users)) {
409f4476bd9SJan Schumann            // Perform the search and grab all their details
41070e4a085SAndreas Gohr            if ($this->getConf('userfilter')) {
41170e4a085SAndreas Gohr                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
412f4476bd9SJan Schumann            } else {
413f4476bd9SJan Schumann                $all_filter = "(ObjectClass=*)";
414f4476bd9SJan Schumann            }
41570e4a085SAndreas Gohr            $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
416f4476bd9SJan Schumann            $entries = ldap_get_entries($this->con, $sr);
417ab9790caSAndreas Gohr            $users_array = [];
4186619ddf4SSascha Klopp            $userkey = $this->getConf('userkey');
419f4476bd9SJan Schumann            for ($i = 0; $i < $entries["count"]; $i++) {
420ab9790caSAndreas Gohr                $users_array[] = $entries[$i][$userkey][0];
421f4476bd9SJan Schumann            }
4220489c64bSMoisés Braga Ribeiro            Sort::asort($users_array);
423f4476bd9SJan Schumann            $result = $users_array;
424ab9790caSAndreas Gohr            if (!$result) return [];
425f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
426f4476bd9SJan Schumann        }
427f4476bd9SJan Schumann        $i = 0;
428f4476bd9SJan Schumann        $count = 0;
429d17fc5deSAndreas Gohr        $this->constructPattern($filter);
430ab9790caSAndreas Gohr        $result = [];
431f4476bd9SJan Schumann
432f4476bd9SJan Schumann        foreach ($this->users as $user => &$info) {
433f4476bd9SJan Schumann            if ($i++ < $start) {
434f4476bd9SJan Schumann                continue;
435f4476bd9SJan Schumann            }
436f4476bd9SJan Schumann            if ($info === false) {
437f4476bd9SJan Schumann                $info = $this->getUserData($user);
438f4476bd9SJan Schumann            }
439d17fc5deSAndreas Gohr            if ($this->filter($user, $info)) {
440f4476bd9SJan Schumann                $result[$user] = $info;
4419a2c73e8SAndreas Gohr                if (($limit > 0) && (++$count >= $limit)) break;
442f4476bd9SJan Schumann            }
443f4476bd9SJan Schumann        }
444f4476bd9SJan Schumann        return $result;
445f4476bd9SJan Schumann    }
446f4476bd9SJan Schumann
447f4476bd9SJan Schumann    /**
448f4476bd9SJan Schumann     * Make LDAP filter strings.
449f4476bd9SJan Schumann     *
450f4476bd9SJan Schumann     * Used by auth_getUserData to make the filter
451f4476bd9SJan Schumann     * strings for grouptree and groupfilter
452f4476bd9SJan Schumann     *
45370e4a085SAndreas Gohr     * @param string $filter ldap search filter with placeholders
45470e4a085SAndreas Gohr     * @param array $placeholders placeholders to fill in
455f4476bd9SJan Schumann     * @return  string
456c0c77cd2SAndreas Gohr     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
457f4476bd9SJan Schumann     */
458d17fc5deSAndreas Gohr    protected function makeFilter($filter, $placeholders)
459d17fc5deSAndreas Gohr    {
460f4476bd9SJan Schumann        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
461f4476bd9SJan Schumann        //replace each match
462f4476bd9SJan Schumann        foreach ($matches[1] as $match) {
463f4476bd9SJan Schumann            //take first element if array
464f4476bd9SJan Schumann            if (is_array($placeholders[$match])) {
465f4476bd9SJan Schumann                $value = $placeholders[$match][0];
466f4476bd9SJan Schumann            } else {
467f4476bd9SJan Schumann                $value = $placeholders[$match];
468f4476bd9SJan Schumann            }
469d17fc5deSAndreas Gohr            $value = $this->filterEscape($value);
470f4476bd9SJan Schumann            $filter = str_replace('%{' . $match . '}', $value, $filter);
471f4476bd9SJan Schumann        }
472f4476bd9SJan Schumann        return $filter;
473f4476bd9SJan Schumann    }
474f4476bd9SJan Schumann
475f4476bd9SJan Schumann    /**
47670e4a085SAndreas Gohr     * return true if $user + $info match $filter criteria, false otherwise
477f4476bd9SJan Schumann     *
47870e4a085SAndreas Gohr     * @param string $user the user's login name
47970e4a085SAndreas Gohr     * @param array $info the user's userinfo array
48070e4a085SAndreas Gohr     * @return bool
481c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
482c0c77cd2SAndreas Gohr     *
483f4476bd9SJan Schumann     */
484d17fc5deSAndreas Gohr    protected function filter($user, $info)
485d17fc5deSAndreas Gohr    {
486d17fc5deSAndreas Gohr        foreach ($this->pattern as $item => $pattern) {
487f4476bd9SJan Schumann            if ($item == 'user') {
48870e4a085SAndreas Gohr                if (!preg_match($pattern, $user)) return false;
489f4476bd9SJan Schumann            } elseif ($item == 'grps') {
49070e4a085SAndreas Gohr                if (!count(preg_grep($pattern, $info['grps']))) return false;
491ab9790caSAndreas Gohr            } elseif (!preg_match($pattern, $info[$item])) {
492ab9790caSAndreas Gohr                return false;
493f4476bd9SJan Schumann            }
494f4476bd9SJan Schumann        }
49570e4a085SAndreas Gohr        return true;
496f4476bd9SJan Schumann    }
497f4476bd9SJan Schumann
49870e4a085SAndreas Gohr    /**
49970e4a085SAndreas Gohr     * Set the filter pattern
50070e4a085SAndreas Gohr     *
50170e4a085SAndreas Gohr     * @param $filter
50270e4a085SAndreas Gohr     * @return void
503c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
504c0c77cd2SAndreas Gohr     *
50570e4a085SAndreas Gohr     */
506d17fc5deSAndreas Gohr    protected function constructPattern($filter)
507d17fc5deSAndreas Gohr    {
508ab9790caSAndreas Gohr        $this->pattern = [];
509f4476bd9SJan Schumann        foreach ($filter as $item => $pattern) {
510d17fc5deSAndreas Gohr            $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
511f4476bd9SJan Schumann        }
512f4476bd9SJan Schumann    }
513f4476bd9SJan Schumann
514f4476bd9SJan Schumann    /**
515f4476bd9SJan Schumann     * Escape a string to be used in a LDAP filter
516f4476bd9SJan Schumann     *
517f4476bd9SJan Schumann     * Ported from Perl's Net::LDAP::Util escape_filter_value
518f4476bd9SJan Schumann     *
51970e4a085SAndreas Gohr     * @param string $string
52070e4a085SAndreas Gohr     * @return string
521c0c77cd2SAndreas Gohr     * @author Andreas Gohr
522f4476bd9SJan Schumann     */
523d17fc5deSAndreas Gohr    protected function filterEscape($string)
524d17fc5deSAndreas Gohr    {
525234b5c9aSBernhard Liebl        // see https://github.com/adldap/adLDAP/issues/22
526234b5c9aSBernhard Liebl        return preg_replace_callback(
527234b5c9aSBernhard Liebl            '/([\x00-\x1F\*\(\)\\\\])/',
528ab9790caSAndreas Gohr            static fn($matches) => "\\" . implode("", unpack("H2", $matches[1])),
52970e4a085SAndreas Gohr            $string
53070e4a085SAndreas Gohr        );
531f4476bd9SJan Schumann    }
532f4476bd9SJan Schumann
533f4476bd9SJan Schumann    /**
534f4476bd9SJan Schumann     * Opens a connection to the configured LDAP server and sets the wanted
535f4476bd9SJan Schumann     * option on the connection
536f4476bd9SJan Schumann     *
537f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
538f4476bd9SJan Schumann     */
539d17fc5deSAndreas Gohr    protected function openLDAP()
540d17fc5deSAndreas Gohr    {
541f4476bd9SJan Schumann        if ($this->con) return true; // connection already established
542f4476bd9SJan Schumann
543234b5c9aSBernhard Liebl        if ($this->getConf('debug')) {
544d17fc5deSAndreas Gohr            ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
545234b5c9aSBernhard Liebl        }
546234b5c9aSBernhard Liebl
547f4476bd9SJan Schumann        $this->bound = 0;
548f4476bd9SJan Schumann
54970e4a085SAndreas Gohr        $port = $this->getConf('port');
55093a7873eSAndreas Gohr        $bound = false;
55170e4a085SAndreas Gohr        $servers = explode(',', $this->getConf('server'));
55293a7873eSAndreas Gohr        foreach ($servers as $server) {
55393a7873eSAndreas Gohr            $server = trim($server);
55493a7873eSAndreas Gohr            $this->con = @ldap_connect($server, $port);
555f4476bd9SJan Schumann            if (!$this->con) {
55693a7873eSAndreas Gohr                continue;
557f4476bd9SJan Schumann            }
558f4476bd9SJan Schumann
55993a7873eSAndreas Gohr            /*
56093a7873eSAndreas Gohr             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
56193a7873eSAndreas Gohr             * not actually connect but just initializes the connecting parameters. The actual
56293a7873eSAndreas Gohr             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
56393a7873eSAndreas Gohr             *
56493a7873eSAndreas Gohr             * So we should try to bind to server in order to check its availability.
56593a7873eSAndreas Gohr             */
56693a7873eSAndreas Gohr
567f4476bd9SJan Schumann            //set protocol version and dependend options
56870e4a085SAndreas Gohr            if ($this->getConf('version')) {
5697d34963bSAndreas Gohr                if (
5707d34963bSAndreas Gohr                    !@ldap_set_option(
571d17fc5deSAndreas Gohr                        $this->con,
572d17fc5deSAndreas Gohr                        LDAP_OPT_PROTOCOL_VERSION,
57370e4a085SAndreas Gohr                        $this->getConf('version')
57470e4a085SAndreas Gohr                    )
57570e4a085SAndreas Gohr                ) {
57670e4a085SAndreas Gohr                    msg('Setting LDAP Protocol version ' . $this->getConf('version') . ' failed', -1);
577d17fc5deSAndreas Gohr                    $this->debug('LDAP version set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
578f4476bd9SJan Schumann                } else {
579f4476bd9SJan Schumann                    //use TLS (needs version 3)
58070e4a085SAndreas Gohr                    if ($this->getConf('starttls')) {
581f4476bd9SJan Schumann                        if (!@ldap_start_tls($this->con)) {
582f4476bd9SJan Schumann                            msg('Starting TLS failed', -1);
583d17fc5deSAndreas Gohr                            $this->debug('LDAP TLS set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
584f4476bd9SJan Schumann                        }
585f4476bd9SJan Schumann                    }
586f4476bd9SJan Schumann                    // needs version 3
587d75d76b2SAndreas Gohr                    if ($this->getConf('referrals') > -1) {
5887d34963bSAndreas Gohr                        if (
5897d34963bSAndreas Gohr                            !@ldap_set_option(
590d17fc5deSAndreas Gohr                                $this->con,
591d17fc5deSAndreas Gohr                                LDAP_OPT_REFERRALS,
59270e4a085SAndreas Gohr                                $this->getConf('referrals')
59370e4a085SAndreas Gohr                            )
59470e4a085SAndreas Gohr                        ) {
595d75d76b2SAndreas Gohr                            msg('Setting LDAP referrals failed', -1);
596d17fc5deSAndreas Gohr                            $this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
597f4476bd9SJan Schumann                        }
598f4476bd9SJan Schumann                    }
599f4476bd9SJan Schumann                }
600f4476bd9SJan Schumann            }
601f4476bd9SJan Schumann
602f4476bd9SJan Schumann            //set deref mode
60370e4a085SAndreas Gohr            if ($this->getConf('deref')) {
60470e4a085SAndreas Gohr                if (!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
60570e4a085SAndreas Gohr                    msg('Setting LDAP Deref mode ' . $this->getConf('deref') . ' failed', -1);
606d17fc5deSAndreas Gohr                    $this->debug('LDAP deref set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
607f4476bd9SJan Schumann                }
608f4476bd9SJan Schumann            }
60993a7873eSAndreas Gohr            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
61093a7873eSAndreas Gohr            if (defined('LDAP_OPT_NETWORK_TIMEOUT')) {
61193a7873eSAndreas Gohr                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
61293a7873eSAndreas Gohr            }
613a426a6cdSAndreas Gohr
614a426a6cdSAndreas Gohr            if ($this->getConf('binddn') && $this->getConf('bindpw')) {
6158ef94e9eSAndreas Gohr                $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
616a426a6cdSAndreas Gohr                $this->bound = 2;
617a426a6cdSAndreas Gohr            } else {
61893a7873eSAndreas Gohr                $bound = @ldap_bind($this->con);
619a426a6cdSAndreas Gohr            }
62093a7873eSAndreas Gohr            if ($bound) {
62193a7873eSAndreas Gohr                break;
62293a7873eSAndreas Gohr            }
62393a7873eSAndreas Gohr        }
62493a7873eSAndreas Gohr
62593a7873eSAndreas Gohr        if (!$bound) {
62693a7873eSAndreas Gohr            msg("LDAP: couldn't connect to LDAP server", -1);
627d17fc5deSAndreas Gohr            $this->debug(ldap_error($this->con), 0, __LINE__, __FILE__);
62893a7873eSAndreas Gohr            return false;
62993a7873eSAndreas Gohr        }
63093a7873eSAndreas Gohr
63170e4a085SAndreas Gohr        $this->cando['getUsers'] = true;
632f4476bd9SJan Schumann        return true;
633f4476bd9SJan Schumann    }
634f4476bd9SJan Schumann
635f4476bd9SJan Schumann    /**
636f4476bd9SJan Schumann     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
637f4476bd9SJan Schumann     *
63870e4a085SAndreas Gohr     * @param resource $link_identifier
63970e4a085SAndreas Gohr     * @param string $base_dn
64070e4a085SAndreas Gohr     * @param string $filter
64170e4a085SAndreas Gohr     * @param string $scope can be 'base', 'one' or 'sub'
642e0c26282SGerrit Uitslag     * @param null|array $attributes
64370e4a085SAndreas Gohr     * @param int $attrsonly
64470e4a085SAndreas Gohr     * @param int $sizelimit
64570e4a085SAndreas Gohr     * @return resource
646c0c77cd2SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
647f4476bd9SJan Schumann     */
648d17fc5deSAndreas Gohr    protected function ldapSearch(
649d17fc5deSAndreas Gohr        $link_identifier,
650d17fc5deSAndreas Gohr        $base_dn,
651d17fc5deSAndreas Gohr        $filter,
652d17fc5deSAndreas Gohr        $scope = 'sub',
653d17fc5deSAndreas Gohr        $attributes = null,
654d17fc5deSAndreas Gohr        $attrsonly = 0,
655d17fc5deSAndreas Gohr        $sizelimit = 0
656d868eb89SAndreas Gohr    ) {
657ab9790caSAndreas Gohr        if (is_null($attributes)) $attributes = [];
658f4476bd9SJan Schumann
659f4476bd9SJan Schumann        if ($scope == 'base') {
66070e4a085SAndreas Gohr            return @ldap_read(
661d17fc5deSAndreas Gohr                $link_identifier,
662d17fc5deSAndreas Gohr                $base_dn,
663d17fc5deSAndreas Gohr                $filter,
664d17fc5deSAndreas Gohr                $attributes,
665d17fc5deSAndreas Gohr                $attrsonly,
666d17fc5deSAndreas Gohr                $sizelimit
66770e4a085SAndreas Gohr            );
668f4476bd9SJan Schumann        } elseif ($scope == 'one') {
66970e4a085SAndreas Gohr            return @ldap_list(
670d17fc5deSAndreas Gohr                $link_identifier,
671d17fc5deSAndreas Gohr                $base_dn,
672d17fc5deSAndreas Gohr                $filter,
673d17fc5deSAndreas Gohr                $attributes,
674d17fc5deSAndreas Gohr                $attrsonly,
675d17fc5deSAndreas Gohr                $sizelimit
67670e4a085SAndreas Gohr            );
677f4476bd9SJan Schumann        } else {
67870e4a085SAndreas Gohr            return @ldap_search(
679d17fc5deSAndreas Gohr                $link_identifier,
680d17fc5deSAndreas Gohr                $base_dn,
681d17fc5deSAndreas Gohr                $filter,
682d17fc5deSAndreas Gohr                $attributes,
683d17fc5deSAndreas Gohr                $attrsonly,
684d17fc5deSAndreas Gohr                $sizelimit
68570e4a085SAndreas Gohr            );
686f4476bd9SJan Schumann        }
687f4476bd9SJan Schumann    }
68870e4a085SAndreas Gohr
68970e4a085SAndreas Gohr    /**
69070e4a085SAndreas Gohr     * Wrapper around msg() but outputs only when debug is enabled
69170e4a085SAndreas Gohr     *
69270e4a085SAndreas Gohr     * @param string $message
69370e4a085SAndreas Gohr     * @param int $err
69470e4a085SAndreas Gohr     * @param int $line
69570e4a085SAndreas Gohr     * @param string $file
69670e4a085SAndreas Gohr     * @return void
69770e4a085SAndreas Gohr     */
698d17fc5deSAndreas Gohr    protected function debug($message, $err, $line, $file)
699d17fc5deSAndreas Gohr    {
70070e4a085SAndreas Gohr        if (!$this->getConf('debug')) return;
70170e4a085SAndreas Gohr        msg($message, $err, $line, $file);
70270e4a085SAndreas Gohr    }
703f4476bd9SJan Schumann}
704