xref: /dokuwiki/lib/plugins/authldap/auth.php (revision c0c77cd20b23921c9e893bb70b99f38be153875a)
1f4476bd9SJan Schumann<?php
2d17fc5deSAndreas Gohr
3f4476bd9SJan Schumann/**
4f4476bd9SJan Schumann * LDAP authentication backend
5f4476bd9SJan Schumann *
6f4476bd9SJan Schumann * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
7f4476bd9SJan Schumann * @author    Andreas Gohr <andi@splitbrain.org>
8f4476bd9SJan Schumann * @author    Chris Smith <chris@jalakaic.co.uk>
9f4476bd9SJan Schumann * @author    Jan Schumann <js@schumann-it.com>
10f4476bd9SJan Schumann */
11d17fc5deSAndreas Gohrclass auth_plugin_authldap extends DokuWiki_Auth_Plugin
12d17fc5deSAndreas Gohr{
1370e4a085SAndreas Gohr    /* @var resource $con holds the LDAP connection */
1470e4a085SAndreas Gohr    protected $con = null;
1570e4a085SAndreas Gohr
1670e4a085SAndreas Gohr    /* @var int $bound What type of connection does already exist? */
1770e4a085SAndreas Gohr    protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
1870e4a085SAndreas Gohr
1970e4a085SAndreas Gohr    /* @var array $users User data cache */
2070e4a085SAndreas Gohr    protected $users = null;
2170e4a085SAndreas Gohr
22d17fc5deSAndreas Gohr    /* @var array $pattern User filter pattern */
23d17fc5deSAndreas Gohr    protected $pattern = null;
24f4476bd9SJan Schumann
25f4476bd9SJan Schumann    /**
26f4476bd9SJan Schumann     * Constructor
27f4476bd9SJan Schumann     */
28d17fc5deSAndreas Gohr    public function __construct()
29d17fc5deSAndreas Gohr    {
30454d868bSAndreas Gohr        parent::__construct();
31454d868bSAndreas Gohr
32f4476bd9SJan Schumann        // ldap extension is needed
33f4476bd9SJan Schumann        if (!function_exists('ldap_connect')) {
34d17fc5deSAndreas Gohr            $this->debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
35f4476bd9SJan Schumann            $this->success = false;
36f4476bd9SJan Schumann            return;
37f4476bd9SJan Schumann        }
38f4476bd9SJan Schumann
3906da270eSAxel Angel        // Add the capabilities to change the password
406619ddf4SSascha Klopp        $this->cando['modPass'] = $this->getConf('modPass');
41f4476bd9SJan Schumann    }
42f4476bd9SJan Schumann
43f4476bd9SJan Schumann    /**
44f4476bd9SJan Schumann     * Check user+password
45f4476bd9SJan Schumann     *
46f4476bd9SJan Schumann     * Checks if the given user exists and the given
47f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
48f4476bd9SJan Schumann     * to the LDAP server
49f4476bd9SJan Schumann     *
5070e4a085SAndreas Gohr     * @param string $user
5170e4a085SAndreas Gohr     * @param string $pass
52f4476bd9SJan Schumann     * @return  bool
53*c0c77cd2SAndreas Gohr     * @author  Andreas Gohr <andi@splitbrain.org>
54f4476bd9SJan Schumann     */
55d17fc5deSAndreas Gohr    public function checkPass($user, $pass)
56d17fc5deSAndreas Gohr    {
57f4476bd9SJan Schumann        // reject empty password
58f4476bd9SJan Schumann        if (empty($pass)) return false;
59d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return false;
60f4476bd9SJan Schumann
61f4476bd9SJan Schumann        // indirect user bind
6270e4a085SAndreas Gohr        if ($this->getConf('binddn') && $this->getConf('bindpw')) {
63f4476bd9SJan Schumann            // use superuser credentials
648ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
65d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
66f4476bd9SJan Schumann                return false;
67f4476bd9SJan Schumann            }
68f4476bd9SJan Schumann            $this->bound = 2;
6970e4a085SAndreas Gohr        } elseif ($this->getConf('binddn') &&
7070e4a085SAndreas Gohr            $this->getConf('usertree') &&
7170e4a085SAndreas Gohr            $this->getConf('userfilter')
7270e4a085SAndreas Gohr        ) {
73f4476bd9SJan Schumann            // special bind string
74d17fc5deSAndreas Gohr            $dn = $this->makeFilter(
7570e4a085SAndreas Gohr                $this->getConf('binddn'),
7670e4a085SAndreas Gohr                array('user' => $user, 'server' => $this->getConf('server'))
7770e4a085SAndreas Gohr            );
7870e4a085SAndreas Gohr        } elseif (strpos($this->getConf('usertree'), '%{user}')) {
79f4476bd9SJan Schumann            // direct user bind
80d17fc5deSAndreas Gohr            $dn = $this->makeFilter(
8170e4a085SAndreas Gohr                $this->getConf('usertree'),
8270e4a085SAndreas Gohr                array('user' => $user, 'server' => $this->getConf('server'))
8370e4a085SAndreas Gohr            );
84f4476bd9SJan Schumann        } else {
85f4476bd9SJan Schumann            // Anonymous bind
86f4476bd9SJan Schumann            if (!@ldap_bind($this->con)) {
87f4476bd9SJan Schumann                msg("LDAP: can not bind anonymously", -1);
88d17fc5deSAndreas Gohr                $this->debug('LDAP anonymous bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
89f4476bd9SJan Schumann                return false;
90f4476bd9SJan Schumann            }
91f4476bd9SJan Schumann        }
92f4476bd9SJan Schumann
93f4476bd9SJan Schumann        // Try to bind to with the dn if we have one.
94f4476bd9SJan Schumann        if (!empty($dn)) {
95f4476bd9SJan Schumann            // User/Password bind
96f4476bd9SJan Schumann            if (!@ldap_bind($this->con, $dn, $pass)) {
97d17fc5deSAndreas Gohr                $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
98d17fc5deSAndreas Gohr                $this->debug('LDAP user dn bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
99f4476bd9SJan Schumann                return false;
100f4476bd9SJan Schumann            }
101f4476bd9SJan Schumann            $this->bound = 1;
102f4476bd9SJan Schumann            return true;
103f4476bd9SJan Schumann        } else {
104f4476bd9SJan Schumann            // See if we can find the user
105d17fc5deSAndreas Gohr            $info = $this->fetchUserData($user, true);
106f4476bd9SJan Schumann            if (empty($info['dn'])) {
107f4476bd9SJan Schumann                return false;
108f4476bd9SJan Schumann            } else {
109f4476bd9SJan Schumann                $dn = $info['dn'];
110f4476bd9SJan Schumann            }
111f4476bd9SJan Schumann
112f4476bd9SJan Schumann            // Try to bind with the dn provided
113f4476bd9SJan Schumann            if (!@ldap_bind($this->con, $dn, $pass)) {
114d17fc5deSAndreas Gohr                $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
115d17fc5deSAndreas Gohr                $this->debug('LDAP user bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
116f4476bd9SJan Schumann                return false;
117f4476bd9SJan Schumann            }
118f4476bd9SJan Schumann            $this->bound = 1;
119f4476bd9SJan Schumann            return true;
120f4476bd9SJan Schumann        }
121f4476bd9SJan Schumann    }
122f4476bd9SJan Schumann
123f4476bd9SJan Schumann    /**
124f4476bd9SJan Schumann     * Return user info
125f4476bd9SJan Schumann     *
126f4476bd9SJan Schumann     * Returns info about the given user needs to contain
127f4476bd9SJan Schumann     * at least these fields:
128f4476bd9SJan Schumann     *
129f4476bd9SJan Schumann     * name string  full name of the user
130f4476bd9SJan Schumann     * mail string  email addres of the user
131f4476bd9SJan Schumann     * grps array   list of groups the user is in
132f4476bd9SJan Schumann     *
133f4476bd9SJan Schumann     * This LDAP specific function returns the following
134f4476bd9SJan Schumann     * addional fields:
135f4476bd9SJan Schumann     *
136f4476bd9SJan Schumann     * dn     string  distinguished name (DN)
137f4476bd9SJan Schumann     * uid    string  Posix User ID
138f4476bd9SJan Schumann     * inbind bool    for internal use - avoid loop in binding
139f4476bd9SJan Schumann     *
140*c0c77cd2SAndreas Gohr     * @param string $user
141*c0c77cd2SAndreas Gohr     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
142*c0c77cd2SAndreas Gohr     * @return  array containing user data or false
143f4476bd9SJan Schumann     * @author  <evaldas.auryla@pheur.org>
144f4476bd9SJan Schumann     * @author  Stephane Chazelas <stephane.chazelas@emerson.com>
1453e23f03eSSteScho     * @author  Steffen Schoch <schoch@dsb.net>
14670e4a085SAndreas Gohr     *
147*c0c77cd2SAndreas Gohr     * @author  Andreas Gohr <andi@splitbrain.org>
148*c0c77cd2SAndreas Gohr     * @author  Trouble
149*c0c77cd2SAndreas Gohr     * @author  Dan Allen <dan.j.allen@gmail.com>
150d397e6daSChristopher Smith     */
151d17fc5deSAndreas Gohr    public function getUserData($user, $requireGroups = true)
152d17fc5deSAndreas Gohr    {
153d17fc5deSAndreas Gohr        return $this->fetchUserData($user);
154d397e6daSChristopher Smith    }
155d397e6daSChristopher Smith
156d397e6daSChristopher Smith    /**
157d397e6daSChristopher Smith     * @param string $user
15870e4a085SAndreas Gohr     * @param bool $inbind authldap specific, true if in bind phase
159f4476bd9SJan Schumann     * @return  array containing user data or false
160f4476bd9SJan Schumann     */
161d17fc5deSAndreas Gohr    protected function fetchUserData($user, $inbind = false)
162d17fc5deSAndreas Gohr    {
163f4476bd9SJan Schumann        global $conf;
164d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return array();
165f4476bd9SJan Schumann
166f4476bd9SJan Schumann        // force superuser bind if wanted and not bound as superuser yet
16770e4a085SAndreas Gohr        if ($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
168f4476bd9SJan Schumann            // use superuser credentials
1698ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
170d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
171d17fc5deSAndreas Gohr                return array();
172f4476bd9SJan Schumann            }
173f4476bd9SJan Schumann            $this->bound = 2;
174f4476bd9SJan Schumann        } elseif ($this->bound == 0 && !$inbind) {
175f4476bd9SJan Schumann            // in some cases getUserData is called outside the authentication workflow
176f4476bd9SJan Schumann            // eg. for sending email notification on subscribed pages. This data might not
177f4476bd9SJan Schumann            // be accessible anonymously, so we try to rebind the current user here
178f4476bd9SJan Schumann            list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
179f4476bd9SJan Schumann            if ($loginuser && $loginpass) {
180b4304655SMichael Hamann                $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
181f4476bd9SJan Schumann                $this->checkPass($loginuser, $loginpass);
182f4476bd9SJan Schumann            }
183f4476bd9SJan Schumann        }
184f4476bd9SJan Schumann
18559bc3b48SGerrit Uitslag        $info = array();
186f4476bd9SJan Schumann        $info['user'] = $user;
187d17fc5deSAndreas Gohr        $this->debug('LDAP user to find: ' . hsc($info['user']), 0, __LINE__, __FILE__);
18840017f0bSItamar Shoham
18970e4a085SAndreas Gohr        $info['server'] = $this->getConf('server');
190d17fc5deSAndreas Gohr        $this->debug('LDAP Server: ' . hsc($info['server']), 0, __LINE__, __FILE__);
191f4476bd9SJan Schumann
192f4476bd9SJan Schumann        //get info for given user
193d17fc5deSAndreas Gohr        $base = $this->makeFilter($this->getConf('usertree'), $info);
19470e4a085SAndreas Gohr        if ($this->getConf('userfilter')) {
195d17fc5deSAndreas Gohr            $filter = $this->makeFilter($this->getConf('userfilter'), $info);
196f4476bd9SJan Schumann        } else {
197f4476bd9SJan Schumann            $filter = "(ObjectClass=*)";
198f4476bd9SJan Schumann        }
199f4476bd9SJan Schumann
200d17fc5deSAndreas Gohr        $this->debug('LDAP Filter: ' . hsc($filter), 0, __LINE__, __FILE__);
20140017f0bSItamar Shoham
202d17fc5deSAndreas Gohr        $this->debug('LDAP user search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
203d17fc5deSAndreas Gohr        $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
204*c0c77cd2SAndreas Gohr        $sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope'), $this->getConf('attributes'));
205*c0c77cd2SAndreas Gohr
20640017f0bSItamar Shoham
20740017f0bSItamar Shoham        $result = @ldap_get_entries($this->con, $sr);
20840017f0bSItamar Shoham
20940017f0bSItamar Shoham        // if result is not an array
21040017f0bSItamar Shoham        if (!is_array($result)) {
21140017f0bSItamar Shoham            // no objects found
212d17fc5deSAndreas Gohr            $this->debug('LDAP search returned non-array result: ' . hsc(print($result)), -1, __LINE__, __FILE__);
213d17fc5deSAndreas Gohr            return array();
21440017f0bSItamar Shoham        }
215f4476bd9SJan Schumann
216f4476bd9SJan Schumann        // Don't accept more or less than one response
21740017f0bSItamar Shoham        if ($result['count'] != 1) {
218d17fc5deSAndreas Gohr            $this->debug(
21964159a61SAndreas Gohr                'LDAP search returned ' . hsc($result['count']) . ' results while it should return 1!',
220d17fc5deSAndreas Gohr                -1,
221d17fc5deSAndreas Gohr                __LINE__,
222d17fc5deSAndreas Gohr                __FILE__
22364159a61SAndreas Gohr            );
22440017f0bSItamar Shoham            //for($i = 0; $i < $result["count"]; $i++) {
22564159a61SAndreas Gohr            //$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__);
22640017f0bSItamar Shoham            //}
227d17fc5deSAndreas Gohr            return array();
228f4476bd9SJan Schumann        }
229f4476bd9SJan Schumann
230d17fc5deSAndreas Gohr        $this->debug('LDAP search found single result !', 0, __LINE__, __FILE__);
23140017f0bSItamar Shoham
232f4476bd9SJan Schumann        $user_result = $result[0];
233f4476bd9SJan Schumann        ldap_free_result($sr);
234f4476bd9SJan Schumann
235f4476bd9SJan Schumann        // general user info
236f4476bd9SJan Schumann        $info['dn'] = $user_result['dn'];
237f4476bd9SJan Schumann        $info['gid'] = $user_result['gidnumber'][0];
238f4476bd9SJan Schumann        $info['mail'] = $user_result['mail'][0];
239f4476bd9SJan Schumann        $info['name'] = $user_result['cn'][0];
240f4476bd9SJan Schumann        $info['grps'] = array();
241f4476bd9SJan Schumann
242f4476bd9SJan Schumann        // overwrite if other attribs are specified.
24370e4a085SAndreas Gohr        if (is_array($this->getConf('mapping'))) {
24470e4a085SAndreas Gohr            foreach ($this->getConf('mapping') as $localkey => $key) {
245f4476bd9SJan Schumann                if (is_array($key)) {
246f4476bd9SJan Schumann                    // use regexp to clean up user_result
2478f1011e8SPhy                    // $key = array($key=>$regexp), only handles the first key-value
2488f1011e8SPhy                    $regexp = current($key);
2498f1011e8SPhy                    $key = key($key);
2504f11d93dSGerrit Uitslag                    if ($user_result[$key]) foreach ($user_result[$key] as $grpkey => $grp) {
2514f11d93dSGerrit Uitslag                        if ($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
252f4476bd9SJan Schumann                            if ($localkey == 'grps') {
253f4476bd9SJan Schumann                                $info[$localkey][] = $match[1];
254f4476bd9SJan Schumann                            } else {
255f4476bd9SJan Schumann                                $info[$localkey] = $match[1];
256f4476bd9SJan Schumann                            }
257f4476bd9SJan Schumann                        }
258f4476bd9SJan Schumann                    }
259f4476bd9SJan Schumann                } else {
260f4476bd9SJan Schumann                    $info[$localkey] = $user_result[$key][0];
261f4476bd9SJan Schumann                }
262f4476bd9SJan Schumann            }
263f4476bd9SJan Schumann        }
264f4476bd9SJan Schumann        $user_result = array_merge($info, $user_result);
265f4476bd9SJan Schumann
266f4476bd9SJan Schumann        //get groups for given user if grouptree is given
26770e4a085SAndreas Gohr        if ($this->getConf('grouptree') || $this->getConf('groupfilter')) {
268d17fc5deSAndreas Gohr            $base = $this->makeFilter($this->getConf('grouptree'), $user_result);
269d17fc5deSAndreas Gohr            $filter = $this->makeFilter($this->getConf('groupfilter'), $user_result);
270d17fc5deSAndreas Gohr            $sr = $this->ldapSearch(
27164159a61SAndreas Gohr                $this->con,
27264159a61SAndreas Gohr                $base,
27364159a61SAndreas Gohr                $filter,
27464159a61SAndreas Gohr                $this->getConf('groupscope'),
275d17fc5deSAndreas Gohr                array($this->getConf('groupkey'))
276d17fc5deSAndreas Gohr            );
277d17fc5deSAndreas Gohr            $this->debug('LDAP group search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
278d17fc5deSAndreas Gohr            $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
27970e4a085SAndreas Gohr
280f4476bd9SJan Schumann            if (!$sr) {
281f4476bd9SJan Schumann                msg("LDAP: Reading group memberships failed", -1);
282d17fc5deSAndreas Gohr                return array();
283f4476bd9SJan Schumann            }
284f4476bd9SJan Schumann            $result = ldap_get_entries($this->con, $sr);
285f4476bd9SJan Schumann            ldap_free_result($sr);
286f4476bd9SJan Schumann
287f4476bd9SJan Schumann            if (is_array($result)) foreach ($result as $grp) {
2889f72d639SAndreas Gohr                if (!empty($grp[$this->getConf('groupkey')])) {
2899f72d639SAndreas Gohr                    $group = $grp[$this->getConf('groupkey')];
2909f72d639SAndreas Gohr                    if (is_array($group)) {
2919f72d639SAndreas Gohr                        $group = $group[0];
2929f72d639SAndreas Gohr                    } else {
293d17fc5deSAndreas Gohr                        $this->debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
2949f72d639SAndreas Gohr                    }
2959f72d639SAndreas Gohr                    if ($group === '') continue;
2969f72d639SAndreas Gohr
297d17fc5deSAndreas Gohr                    $this->debug('LDAP usergroup: ' . hsc($group), 0, __LINE__, __FILE__);
2989f72d639SAndreas Gohr                    $info['grps'][] = $group;
299f4476bd9SJan Schumann                }
300f4476bd9SJan Schumann            }
301f4476bd9SJan Schumann        }
302f4476bd9SJan Schumann
303f4476bd9SJan Schumann        // always add the default group to the list of groups
30404e4890dSAndreas Gohr        if (!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) {
305f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
306f4476bd9SJan Schumann        }
307f4476bd9SJan Schumann        return $info;
308f4476bd9SJan Schumann    }
309f4476bd9SJan Schumann
310f4476bd9SJan Schumann    /**
31106da270eSAxel Angel     * Definition of the function modifyUser in order to modify the password
312b83b4364SGerrit Uitslag     *
313b83b4364SGerrit Uitslag     * @param string $user nick of the user to be changed
314b83b4364SGerrit Uitslag     * @param array $changes array of field/value pairs to be changed (password will be clear text)
315b83b4364SGerrit Uitslag     * @return  bool   true on success, false on error
31606da270eSAxel Angel     */
317d17fc5deSAndreas Gohr    public function modifyUser($user, $changes)
318d17fc5deSAndreas Gohr    {
31906da270eSAxel Angel
32006da270eSAxel Angel        // open the connection to the ldap
321d17fc5deSAndreas Gohr        if (!$this->openLDAP()) {
322d17fc5deSAndreas Gohr            $this->debug('LDAP cannot connect: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
32306da270eSAxel Angel            return false;
32406da270eSAxel Angel        }
32506da270eSAxel Angel
32606da270eSAxel Angel        // find the information about the user, in particular the "dn"
32706da270eSAxel Angel        $info = $this->getUserData($user, true);
32806da270eSAxel Angel        if (empty($info['dn'])) {
329d17fc5deSAndreas Gohr            $this->debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__);
33006da270eSAxel Angel            return false;
3318f2ea93bSAxel Angel        }
33206da270eSAxel Angel        $dn = $info['dn'];
33306da270eSAxel Angel
33406da270eSAxel Angel        // find the old password of the user
33506da270eSAxel Angel        list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
336719c6730SAxel Angel        if ($loginuser !== null) { // the user is currently logged in
33718496fe0SAndreas Gohr            $secret = auth_cookiesalt(!$loginsticky, true);
33806da270eSAxel Angel            $pass = auth_decrypt($loginpass, $secret);
33906da270eSAxel Angel
34006da270eSAxel Angel            // bind with the ldap
34106da270eSAxel Angel            if (!@ldap_bind($this->con, $dn, $pass)) {
342d17fc5deSAndreas Gohr                $this->debug(
343d17fc5deSAndreas Gohr                    'LDAP user bind failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
344d17fc5deSAndreas Gohr                    0,
345d17fc5deSAndreas Gohr                    __LINE__,
346d17fc5deSAndreas Gohr                    __FILE__
34764159a61SAndreas Gohr                );
34806da270eSAxel Angel                return false;
34906da270eSAxel Angel            }
350719c6730SAxel Angel        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
351719c6730SAxel Angel            // we are changing the password on behalf of the user (eg: forgotten password)
352719c6730SAxel Angel            // bind with the superuser ldap
3538ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
354d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
355719c6730SAxel Angel                return false;
356719c6730SAxel Angel            }
357d17fc5deSAndreas Gohr        } else {
358719c6730SAxel Angel            return false; // no otherway
359719c6730SAxel Angel        }
36006da270eSAxel Angel
36167723447SAxel Angel        // Generate the salted hashed password for LDAP
362c3cc6e05SAndreas Gohr        $phash = new \dokuwiki\PassHash();
36367723447SAxel Angel        $hash = $phash->hash_ssha($changes['pass']);
36467723447SAxel Angel
36506da270eSAxel Angel        // change the password
36606da270eSAxel Angel        if (!@ldap_mod_replace($this->con, $dn, array('userpassword' => $hash))) {
367d17fc5deSAndreas Gohr            $this->debug(
368d17fc5deSAndreas Gohr                'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
369d17fc5deSAndreas Gohr                0,
370d17fc5deSAndreas Gohr                __LINE__,
371d17fc5deSAndreas Gohr                __FILE__
37264159a61SAndreas Gohr            );
37306da270eSAxel Angel            return false;
37406da270eSAxel Angel        }
37506da270eSAxel Angel
37606da270eSAxel Angel        return true;
37706da270eSAxel Angel    }
37806da270eSAxel Angel
37906da270eSAxel Angel    /**
380f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
38170e4a085SAndreas Gohr     *
38270e4a085SAndreas Gohr     * @return bool
383f4476bd9SJan Schumann     */
384d17fc5deSAndreas Gohr    public function isCaseSensitive()
385d17fc5deSAndreas Gohr    {
386f4476bd9SJan Schumann        return false;
387f4476bd9SJan Schumann    }
388f4476bd9SJan Schumann
389f4476bd9SJan Schumann    /**
390f4476bd9SJan Schumann     * Bulk retrieval of user data
391f4476bd9SJan Schumann     *
39270e4a085SAndreas Gohr     * @param int $start index of first user to be returned
39370e4a085SAndreas Gohr     * @param int $limit max number of users to be returned
39470e4a085SAndreas Gohr     * @param array $filter array of field/pattern pairs, null for no filter
395f4476bd9SJan Schumann     * @return  array of userinfo (refer getUserData for internal userinfo details)
396*c0c77cd2SAndreas Gohr     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
397f4476bd9SJan Schumann     */
398d17fc5deSAndreas Gohr    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
399d17fc5deSAndreas Gohr    {
400d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return array();
401f4476bd9SJan Schumann
40270e4a085SAndreas Gohr        if (is_null($this->users)) {
403f4476bd9SJan Schumann            // Perform the search and grab all their details
40470e4a085SAndreas Gohr            if ($this->getConf('userfilter')) {
40570e4a085SAndreas Gohr                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
406f4476bd9SJan Schumann            } else {
407f4476bd9SJan Schumann                $all_filter = "(ObjectClass=*)";
408f4476bd9SJan Schumann            }
40970e4a085SAndreas Gohr            $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
410f4476bd9SJan Schumann            $entries = ldap_get_entries($this->con, $sr);
411f4476bd9SJan Schumann            $users_array = array();
4126619ddf4SSascha Klopp            $userkey = $this->getConf('userkey');
413f4476bd9SJan Schumann            for ($i = 0; $i < $entries["count"]; $i++) {
4146619ddf4SSascha Klopp                array_push($users_array, $entries[$i][$userkey][0]);
415f4476bd9SJan Schumann            }
416f4476bd9SJan Schumann            asort($users_array);
417f4476bd9SJan Schumann            $result = $users_array;
418f4476bd9SJan Schumann            if (!$result) return array();
419f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
420f4476bd9SJan Schumann        }
421f4476bd9SJan Schumann        $i = 0;
422f4476bd9SJan Schumann        $count = 0;
423d17fc5deSAndreas Gohr        $this->constructPattern($filter);
424f4476bd9SJan Schumann        $result = array();
425f4476bd9SJan Schumann
426f4476bd9SJan Schumann        foreach ($this->users as $user => &$info) {
427f4476bd9SJan Schumann            if ($i++ < $start) {
428f4476bd9SJan Schumann                continue;
429f4476bd9SJan Schumann            }
430f4476bd9SJan Schumann            if ($info === false) {
431f4476bd9SJan Schumann                $info = $this->getUserData($user);
432f4476bd9SJan Schumann            }
433d17fc5deSAndreas Gohr            if ($this->filter($user, $info)) {
434f4476bd9SJan Schumann                $result[$user] = $info;
4359a2c73e8SAndreas Gohr                if (($limit > 0) && (++$count >= $limit)) break;
436f4476bd9SJan Schumann            }
437f4476bd9SJan Schumann        }
438f4476bd9SJan Schumann        return $result;
439f4476bd9SJan Schumann    }
440f4476bd9SJan Schumann
441f4476bd9SJan Schumann    /**
442f4476bd9SJan Schumann     * Make LDAP filter strings.
443f4476bd9SJan Schumann     *
444f4476bd9SJan Schumann     * Used by auth_getUserData to make the filter
445f4476bd9SJan Schumann     * strings for grouptree and groupfilter
446f4476bd9SJan Schumann     *
44770e4a085SAndreas Gohr     * @param string $filter ldap search filter with placeholders
44870e4a085SAndreas Gohr     * @param array $placeholders placeholders to fill in
449f4476bd9SJan Schumann     * @return  string
450*c0c77cd2SAndreas Gohr     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
451f4476bd9SJan Schumann     */
452d17fc5deSAndreas Gohr    protected function makeFilter($filter, $placeholders)
453d17fc5deSAndreas Gohr    {
454f4476bd9SJan Schumann        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
455f4476bd9SJan Schumann        //replace each match
456f4476bd9SJan Schumann        foreach ($matches[1] as $match) {
457f4476bd9SJan Schumann            //take first element if array
458f4476bd9SJan Schumann            if (is_array($placeholders[$match])) {
459f4476bd9SJan Schumann                $value = $placeholders[$match][0];
460f4476bd9SJan Schumann            } else {
461f4476bd9SJan Schumann                $value = $placeholders[$match];
462f4476bd9SJan Schumann            }
463d17fc5deSAndreas Gohr            $value = $this->filterEscape($value);
464f4476bd9SJan Schumann            $filter = str_replace('%{' . $match . '}', $value, $filter);
465f4476bd9SJan Schumann        }
466f4476bd9SJan Schumann        return $filter;
467f4476bd9SJan Schumann    }
468f4476bd9SJan Schumann
469f4476bd9SJan Schumann    /**
47070e4a085SAndreas Gohr     * return true if $user + $info match $filter criteria, false otherwise
471f4476bd9SJan Schumann     *
47270e4a085SAndreas Gohr     * @param string $user the user's login name
47370e4a085SAndreas Gohr     * @param array $info the user's userinfo array
47470e4a085SAndreas Gohr     * @return bool
475*c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
476*c0c77cd2SAndreas Gohr     *
477f4476bd9SJan Schumann     */
478d17fc5deSAndreas Gohr    protected function filter($user, $info)
479d17fc5deSAndreas Gohr    {
480d17fc5deSAndreas Gohr        foreach ($this->pattern as $item => $pattern) {
481f4476bd9SJan Schumann            if ($item == 'user') {
48270e4a085SAndreas Gohr                if (!preg_match($pattern, $user)) return false;
483f4476bd9SJan Schumann            } elseif ($item == 'grps') {
48470e4a085SAndreas Gohr                if (!count(preg_grep($pattern, $info['grps']))) return false;
485f4476bd9SJan Schumann            } else {
48670e4a085SAndreas Gohr                if (!preg_match($pattern, $info[$item])) return false;
487f4476bd9SJan Schumann            }
488f4476bd9SJan Schumann        }
48970e4a085SAndreas Gohr        return true;
490f4476bd9SJan Schumann    }
491f4476bd9SJan Schumann
49270e4a085SAndreas Gohr    /**
49370e4a085SAndreas Gohr     * Set the filter pattern
49470e4a085SAndreas Gohr     *
49570e4a085SAndreas Gohr     * @param $filter
49670e4a085SAndreas Gohr     * @return void
497*c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
498*c0c77cd2SAndreas Gohr     *
49970e4a085SAndreas Gohr     */
500d17fc5deSAndreas Gohr    protected function constructPattern($filter)
501d17fc5deSAndreas Gohr    {
502d17fc5deSAndreas Gohr        $this->pattern = array();
503f4476bd9SJan Schumann        foreach ($filter as $item => $pattern) {
504d17fc5deSAndreas Gohr            $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
505f4476bd9SJan Schumann        }
506f4476bd9SJan Schumann    }
507f4476bd9SJan Schumann
508f4476bd9SJan Schumann    /**
509f4476bd9SJan Schumann     * Escape a string to be used in a LDAP filter
510f4476bd9SJan Schumann     *
511f4476bd9SJan Schumann     * Ported from Perl's Net::LDAP::Util escape_filter_value
512f4476bd9SJan Schumann     *
51370e4a085SAndreas Gohr     * @param string $string
51470e4a085SAndreas Gohr     * @return string
515*c0c77cd2SAndreas Gohr     * @author Andreas Gohr
516f4476bd9SJan Schumann     */
517d17fc5deSAndreas Gohr    protected function filterEscape($string)
518d17fc5deSAndreas Gohr    {
519234b5c9aSBernhard Liebl        // see https://github.com/adldap/adLDAP/issues/22
520234b5c9aSBernhard Liebl        return preg_replace_callback(
521234b5c9aSBernhard Liebl            '/([\x00-\x1F\*\(\)\\\\])/',
522234b5c9aSBernhard Liebl            function ($matches) {
523234b5c9aSBernhard Liebl                return "\\" . join("", unpack("H2", $matches[1]));
524234b5c9aSBernhard Liebl            },
52570e4a085SAndreas Gohr            $string
52670e4a085SAndreas Gohr        );
527f4476bd9SJan Schumann    }
528f4476bd9SJan Schumann
529f4476bd9SJan Schumann    /**
530f4476bd9SJan Schumann     * Opens a connection to the configured LDAP server and sets the wanted
531f4476bd9SJan Schumann     * option on the connection
532f4476bd9SJan Schumann     *
533f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
534f4476bd9SJan Schumann     */
535d17fc5deSAndreas Gohr    protected function openLDAP()
536d17fc5deSAndreas Gohr    {
537f4476bd9SJan Schumann        if ($this->con) return true; // connection already established
538f4476bd9SJan Schumann
539234b5c9aSBernhard Liebl        if ($this->getConf('debug')) {
540d17fc5deSAndreas Gohr            ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
541234b5c9aSBernhard Liebl        }
542234b5c9aSBernhard Liebl
543f4476bd9SJan Schumann        $this->bound = 0;
544f4476bd9SJan Schumann
54570e4a085SAndreas Gohr        $port = $this->getConf('port');
54693a7873eSAndreas Gohr        $bound = false;
54770e4a085SAndreas Gohr        $servers = explode(',', $this->getConf('server'));
54893a7873eSAndreas Gohr        foreach ($servers as $server) {
54993a7873eSAndreas Gohr            $server = trim($server);
55093a7873eSAndreas Gohr            $this->con = @ldap_connect($server, $port);
551f4476bd9SJan Schumann            if (!$this->con) {
55293a7873eSAndreas Gohr                continue;
553f4476bd9SJan Schumann            }
554f4476bd9SJan Schumann
55593a7873eSAndreas Gohr            /*
55693a7873eSAndreas Gohr             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
55793a7873eSAndreas Gohr             * not actually connect but just initializes the connecting parameters. The actual
55893a7873eSAndreas Gohr             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
55993a7873eSAndreas Gohr             *
56093a7873eSAndreas Gohr             * So we should try to bind to server in order to check its availability.
56193a7873eSAndreas Gohr             */
56293a7873eSAndreas Gohr
563f4476bd9SJan Schumann            //set protocol version and dependend options
56470e4a085SAndreas Gohr            if ($this->getConf('version')) {
56570e4a085SAndreas Gohr                if (!@ldap_set_option(
566d17fc5deSAndreas Gohr                    $this->con,
567d17fc5deSAndreas Gohr                    LDAP_OPT_PROTOCOL_VERSION,
56870e4a085SAndreas Gohr                    $this->getConf('version')
56970e4a085SAndreas Gohr                )
57070e4a085SAndreas Gohr                ) {
57170e4a085SAndreas Gohr                    msg('Setting LDAP Protocol version ' . $this->getConf('version') . ' failed', -1);
572d17fc5deSAndreas Gohr                    $this->debug('LDAP version set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
573f4476bd9SJan Schumann                } else {
574f4476bd9SJan Schumann                    //use TLS (needs version 3)
57570e4a085SAndreas Gohr                    if ($this->getConf('starttls')) {
576f4476bd9SJan Schumann                        if (!@ldap_start_tls($this->con)) {
577f4476bd9SJan Schumann                            msg('Starting TLS failed', -1);
578d17fc5deSAndreas Gohr                            $this->debug('LDAP TLS set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
579f4476bd9SJan Schumann                        }
580f4476bd9SJan Schumann                    }
581f4476bd9SJan Schumann                    // needs version 3
582d75d76b2SAndreas Gohr                    if ($this->getConf('referrals') > -1) {
58370e4a085SAndreas Gohr                        if (!@ldap_set_option(
584d17fc5deSAndreas Gohr                            $this->con,
585d17fc5deSAndreas Gohr                            LDAP_OPT_REFERRALS,
58670e4a085SAndreas Gohr                            $this->getConf('referrals')
58770e4a085SAndreas Gohr                        )
58870e4a085SAndreas Gohr                        ) {
589d75d76b2SAndreas Gohr                            msg('Setting LDAP referrals failed', -1);
590d17fc5deSAndreas Gohr                            $this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
591f4476bd9SJan Schumann                        }
592f4476bd9SJan Schumann                    }
593f4476bd9SJan Schumann                }
594f4476bd9SJan Schumann            }
595f4476bd9SJan Schumann
596f4476bd9SJan Schumann            //set deref mode
59770e4a085SAndreas Gohr            if ($this->getConf('deref')) {
59870e4a085SAndreas Gohr                if (!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
59970e4a085SAndreas Gohr                    msg('Setting LDAP Deref mode ' . $this->getConf('deref') . ' failed', -1);
600d17fc5deSAndreas Gohr                    $this->debug('LDAP deref set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
601f4476bd9SJan Schumann                }
602f4476bd9SJan Schumann            }
60393a7873eSAndreas Gohr            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
60493a7873eSAndreas Gohr            if (defined('LDAP_OPT_NETWORK_TIMEOUT')) {
60593a7873eSAndreas Gohr                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
60693a7873eSAndreas Gohr            }
607a426a6cdSAndreas Gohr
608a426a6cdSAndreas Gohr            if ($this->getConf('binddn') && $this->getConf('bindpw')) {
6098ef94e9eSAndreas Gohr                $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
610a426a6cdSAndreas Gohr                $this->bound = 2;
611a426a6cdSAndreas Gohr            } else {
61293a7873eSAndreas Gohr                $bound = @ldap_bind($this->con);
613a426a6cdSAndreas Gohr            }
61493a7873eSAndreas Gohr            if ($bound) {
61593a7873eSAndreas Gohr                break;
61693a7873eSAndreas Gohr            }
61793a7873eSAndreas Gohr        }
61893a7873eSAndreas Gohr
61993a7873eSAndreas Gohr        if (!$bound) {
62093a7873eSAndreas Gohr            msg("LDAP: couldn't connect to LDAP server", -1);
621d17fc5deSAndreas Gohr            $this->debug(ldap_error($this->con), 0, __LINE__, __FILE__);
62293a7873eSAndreas Gohr            return false;
62393a7873eSAndreas Gohr        }
62493a7873eSAndreas Gohr
62570e4a085SAndreas Gohr        $this->cando['getUsers'] = true;
626f4476bd9SJan Schumann        return true;
627f4476bd9SJan Schumann    }
628f4476bd9SJan Schumann
629f4476bd9SJan Schumann    /**
630f4476bd9SJan Schumann     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
631f4476bd9SJan Schumann     *
63270e4a085SAndreas Gohr     * @param resource $link_identifier
63370e4a085SAndreas Gohr     * @param string $base_dn
63470e4a085SAndreas Gohr     * @param string $filter
63570e4a085SAndreas Gohr     * @param string $scope can be 'base', 'one' or 'sub'
636e0c26282SGerrit Uitslag     * @param null|array $attributes
63770e4a085SAndreas Gohr     * @param int $attrsonly
63870e4a085SAndreas Gohr     * @param int $sizelimit
63970e4a085SAndreas Gohr     * @return resource
640*c0c77cd2SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
641f4476bd9SJan Schumann     */
642d17fc5deSAndreas Gohr    protected function ldapSearch(
643d17fc5deSAndreas Gohr        $link_identifier,
644d17fc5deSAndreas Gohr        $base_dn,
645d17fc5deSAndreas Gohr        $filter,
646d17fc5deSAndreas Gohr        $scope = 'sub',
647d17fc5deSAndreas Gohr        $attributes = null,
648d17fc5deSAndreas Gohr        $attrsonly = 0,
649d17fc5deSAndreas Gohr        $sizelimit = 0
650*c0c77cd2SAndreas Gohr    )
651*c0c77cd2SAndreas Gohr    {
652f4476bd9SJan Schumann        if (is_null($attributes)) $attributes = array();
653f4476bd9SJan Schumann
654f4476bd9SJan Schumann        if ($scope == 'base') {
65570e4a085SAndreas Gohr            return @ldap_read(
656d17fc5deSAndreas Gohr                $link_identifier,
657d17fc5deSAndreas Gohr                $base_dn,
658d17fc5deSAndreas Gohr                $filter,
659d17fc5deSAndreas Gohr                $attributes,
660d17fc5deSAndreas Gohr                $attrsonly,
661d17fc5deSAndreas Gohr                $sizelimit
66270e4a085SAndreas Gohr            );
663f4476bd9SJan Schumann        } elseif ($scope == 'one') {
66470e4a085SAndreas Gohr            return @ldap_list(
665d17fc5deSAndreas Gohr                $link_identifier,
666d17fc5deSAndreas Gohr                $base_dn,
667d17fc5deSAndreas Gohr                $filter,
668d17fc5deSAndreas Gohr                $attributes,
669d17fc5deSAndreas Gohr                $attrsonly,
670d17fc5deSAndreas Gohr                $sizelimit
67170e4a085SAndreas Gohr            );
672f4476bd9SJan Schumann        } else {
67370e4a085SAndreas Gohr            return @ldap_search(
674d17fc5deSAndreas Gohr                $link_identifier,
675d17fc5deSAndreas Gohr                $base_dn,
676d17fc5deSAndreas Gohr                $filter,
677d17fc5deSAndreas Gohr                $attributes,
678d17fc5deSAndreas Gohr                $attrsonly,
679d17fc5deSAndreas Gohr                $sizelimit
68070e4a085SAndreas Gohr            );
681f4476bd9SJan Schumann        }
682f4476bd9SJan Schumann    }
68370e4a085SAndreas Gohr
68470e4a085SAndreas Gohr    /**
68570e4a085SAndreas Gohr     * Wrapper around msg() but outputs only when debug is enabled
68670e4a085SAndreas Gohr     *
68770e4a085SAndreas Gohr     * @param string $message
68870e4a085SAndreas Gohr     * @param int $err
68970e4a085SAndreas Gohr     * @param int $line
69070e4a085SAndreas Gohr     * @param string $file
69170e4a085SAndreas Gohr     * @return void
69270e4a085SAndreas Gohr     */
693d17fc5deSAndreas Gohr    protected function debug($message, $err, $line, $file)
694d17fc5deSAndreas Gohr    {
69570e4a085SAndreas Gohr        if (!$this->getConf('debug')) return;
69670e4a085SAndreas Gohr        msg($message, $err, $line, $file);
69770e4a085SAndreas Gohr    }
698f4476bd9SJan Schumann}
699