xref: /dokuwiki/lib/plugins/authldap/auth.php (revision 83616da3051ba49ad939634aabe78b8e7483af5b)
1f4476bd9SJan Schumann<?php
20489c64bSMoisés Braga Ribeirouse dokuwiki\Utf8\Sort;
3d17fc5deSAndreas Gohr
4f4476bd9SJan Schumann/**
5f4476bd9SJan Schumann * LDAP authentication backend
6f4476bd9SJan Schumann *
7f4476bd9SJan Schumann * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
8f4476bd9SJan Schumann * @author    Andreas Gohr <andi@splitbrain.org>
9f4476bd9SJan Schumann * @author    Chris Smith <chris@jalakaic.co.uk>
10f4476bd9SJan Schumann * @author    Jan Schumann <js@schumann-it.com>
11f4476bd9SJan Schumann */
12d17fc5deSAndreas Gohrclass auth_plugin_authldap extends DokuWiki_Auth_Plugin
13d17fc5deSAndreas Gohr{
1470e4a085SAndreas Gohr    /* @var resource $con holds the LDAP connection */
1570e4a085SAndreas Gohr    protected $con = null;
1670e4a085SAndreas Gohr
1770e4a085SAndreas Gohr    /* @var int $bound What type of connection does already exist? */
1870e4a085SAndreas Gohr    protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
1970e4a085SAndreas Gohr
2070e4a085SAndreas Gohr    /* @var array $users User data cache */
2170e4a085SAndreas Gohr    protected $users = null;
2270e4a085SAndreas Gohr
23d17fc5deSAndreas Gohr    /* @var array $pattern User filter pattern */
24d17fc5deSAndreas Gohr    protected $pattern = null;
25f4476bd9SJan Schumann
26f4476bd9SJan Schumann    /**
27f4476bd9SJan Schumann     * Constructor
28f4476bd9SJan Schumann     */
29d17fc5deSAndreas Gohr    public function __construct()
30d17fc5deSAndreas Gohr    {
31454d868bSAndreas Gohr        parent::__construct();
32454d868bSAndreas Gohr
33f4476bd9SJan Schumann        // ldap extension is needed
34f4476bd9SJan Schumann        if (!function_exists('ldap_connect')) {
35d17fc5deSAndreas Gohr            $this->debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
36f4476bd9SJan Schumann            $this->success = false;
37f4476bd9SJan Schumann            return;
38f4476bd9SJan Schumann        }
39f4476bd9SJan Schumann
4006da270eSAxel Angel        // Add the capabilities to change the password
416619ddf4SSascha Klopp        $this->cando['modPass'] = $this->getConf('modPass');
42f4476bd9SJan Schumann    }
43f4476bd9SJan Schumann
44f4476bd9SJan Schumann    /**
45f4476bd9SJan Schumann     * Check user+password
46f4476bd9SJan Schumann     *
47f4476bd9SJan Schumann     * Checks if the given user exists and the given
48f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
49f4476bd9SJan Schumann     * to the LDAP server
50f4476bd9SJan Schumann     *
5170e4a085SAndreas Gohr     * @param string $user
5270e4a085SAndreas Gohr     * @param string $pass
53f4476bd9SJan Schumann     * @return  bool
54c0c77cd2SAndreas Gohr     * @author  Andreas Gohr <andi@splitbrain.org>
55f4476bd9SJan Schumann     */
56d17fc5deSAndreas Gohr    public function checkPass($user, $pass)
57d17fc5deSAndreas Gohr    {
58f4476bd9SJan Schumann        // reject empty password
59f4476bd9SJan Schumann        if (empty($pass)) return false;
60d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return false;
61f4476bd9SJan Schumann
62f4476bd9SJan Schumann        // indirect user bind
6370e4a085SAndreas Gohr        if ($this->getConf('binddn') && $this->getConf('bindpw')) {
64f4476bd9SJan Schumann            // use superuser credentials
658ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
66d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
67f4476bd9SJan Schumann                return false;
68f4476bd9SJan Schumann            }
69f4476bd9SJan Schumann            $this->bound = 2;
7070e4a085SAndreas Gohr        } elseif ($this->getConf('binddn') &&
7170e4a085SAndreas Gohr            $this->getConf('usertree') &&
7270e4a085SAndreas Gohr            $this->getConf('userfilter')
7370e4a085SAndreas Gohr        ) {
74f4476bd9SJan Schumann            // special bind string
75d17fc5deSAndreas Gohr            $dn = $this->makeFilter(
7670e4a085SAndreas Gohr                $this->getConf('binddn'),
7770e4a085SAndreas Gohr                array('user' => $user, 'server' => $this->getConf('server'))
7870e4a085SAndreas Gohr            );
7970e4a085SAndreas Gohr        } elseif (strpos($this->getConf('usertree'), '%{user}')) {
80f4476bd9SJan Schumann            // direct user bind
81d17fc5deSAndreas Gohr            $dn = $this->makeFilter(
8270e4a085SAndreas Gohr                $this->getConf('usertree'),
8370e4a085SAndreas Gohr                array('user' => $user, 'server' => $this->getConf('server'))
8470e4a085SAndreas Gohr            );
85f4476bd9SJan Schumann        } else {
86f4476bd9SJan Schumann            // Anonymous bind
87f4476bd9SJan Schumann            if (!@ldap_bind($this->con)) {
88f4476bd9SJan Schumann                msg("LDAP: can not bind anonymously", -1);
89d17fc5deSAndreas Gohr                $this->debug('LDAP anonymous bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
90f4476bd9SJan Schumann                return false;
91f4476bd9SJan Schumann            }
92f4476bd9SJan Schumann        }
93f4476bd9SJan Schumann
94f4476bd9SJan Schumann        // Try to bind to with the dn if we have one.
95f4476bd9SJan Schumann        if (!empty($dn)) {
96f4476bd9SJan Schumann            // User/Password bind
97f4476bd9SJan Schumann            if (!@ldap_bind($this->con, $dn, $pass)) {
98d17fc5deSAndreas Gohr                $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
99d17fc5deSAndreas Gohr                $this->debug('LDAP user dn bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
100f4476bd9SJan Schumann                return false;
101f4476bd9SJan Schumann            }
102f4476bd9SJan Schumann            $this->bound = 1;
103f4476bd9SJan Schumann            return true;
104f4476bd9SJan Schumann        } else {
105f4476bd9SJan Schumann            // See if we can find the user
106d17fc5deSAndreas Gohr            $info = $this->fetchUserData($user, true);
107f4476bd9SJan Schumann            if (empty($info['dn'])) {
108f4476bd9SJan Schumann                return false;
109f4476bd9SJan Schumann            } else {
110f4476bd9SJan Schumann                $dn = $info['dn'];
111f4476bd9SJan Schumann            }
112f4476bd9SJan Schumann
113f4476bd9SJan Schumann            // Try to bind with the dn provided
114f4476bd9SJan Schumann            if (!@ldap_bind($this->con, $dn, $pass)) {
115d17fc5deSAndreas Gohr                $this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
116d17fc5deSAndreas Gohr                $this->debug('LDAP user bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
117f4476bd9SJan Schumann                return false;
118f4476bd9SJan Schumann            }
119f4476bd9SJan Schumann            $this->bound = 1;
120f4476bd9SJan Schumann            return true;
121f4476bd9SJan Schumann        }
122f4476bd9SJan Schumann    }
123f4476bd9SJan Schumann
124f4476bd9SJan Schumann    /**
125f4476bd9SJan Schumann     * Return user info
126f4476bd9SJan Schumann     *
127f4476bd9SJan Schumann     * Returns info about the given user needs to contain
128f4476bd9SJan Schumann     * at least these fields:
129f4476bd9SJan Schumann     *
130f4476bd9SJan Schumann     * name string  full name of the user
131f4476bd9SJan Schumann     * mail string  email addres of the user
132f4476bd9SJan Schumann     * grps array   list of groups the user is in
133f4476bd9SJan Schumann     *
134f4476bd9SJan Schumann     * This LDAP specific function returns the following
135f4476bd9SJan Schumann     * addional fields:
136f4476bd9SJan Schumann     *
137f4476bd9SJan Schumann     * dn     string  distinguished name (DN)
138f4476bd9SJan Schumann     * uid    string  Posix User ID
139f4476bd9SJan Schumann     * inbind bool    for internal use - avoid loop in binding
140f4476bd9SJan Schumann     *
141c0c77cd2SAndreas Gohr     * @param string $user
142c0c77cd2SAndreas Gohr     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
143c0c77cd2SAndreas Gohr     * @return  array containing user data or false
144f4476bd9SJan Schumann     * @author  <evaldas.auryla@pheur.org>
145f4476bd9SJan Schumann     * @author  Stephane Chazelas <stephane.chazelas@emerson.com>
1463e23f03eSSteScho     * @author  Steffen Schoch <schoch@dsb.net>
14770e4a085SAndreas Gohr     *
148c0c77cd2SAndreas Gohr     * @author  Andreas Gohr <andi@splitbrain.org>
149c0c77cd2SAndreas Gohr     * @author  Trouble
150c0c77cd2SAndreas Gohr     * @author  Dan Allen <dan.j.allen@gmail.com>
151d397e6daSChristopher Smith     */
152d17fc5deSAndreas Gohr    public function getUserData($user, $requireGroups = true)
153d17fc5deSAndreas Gohr    {
154d17fc5deSAndreas Gohr        return $this->fetchUserData($user);
155d397e6daSChristopher Smith    }
156d397e6daSChristopher Smith
157d397e6daSChristopher Smith    /**
158d397e6daSChristopher Smith     * @param string $user
15970e4a085SAndreas Gohr     * @param bool $inbind authldap specific, true if in bind phase
160f4476bd9SJan Schumann     * @return  array containing user data or false
161f4476bd9SJan Schumann     */
162d17fc5deSAndreas Gohr    protected function fetchUserData($user, $inbind = false)
163d17fc5deSAndreas Gohr    {
164f4476bd9SJan Schumann        global $conf;
165d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return array();
166f4476bd9SJan Schumann
167f4476bd9SJan Schumann        // force superuser bind if wanted and not bound as superuser yet
16870e4a085SAndreas Gohr        if ($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
169f4476bd9SJan Schumann            // use superuser credentials
1708ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
171d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
172d17fc5deSAndreas Gohr                return array();
173f4476bd9SJan Schumann            }
174f4476bd9SJan Schumann            $this->bound = 2;
175f4476bd9SJan Schumann        } elseif ($this->bound == 0 && !$inbind) {
176f4476bd9SJan Schumann            // in some cases getUserData is called outside the authentication workflow
177f4476bd9SJan Schumann            // eg. for sending email notification on subscribed pages. This data might not
178f4476bd9SJan Schumann            // be accessible anonymously, so we try to rebind the current user here
179f4476bd9SJan Schumann            list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
180f4476bd9SJan Schumann            if ($loginuser && $loginpass) {
181b4304655SMichael Hamann                $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
182f4476bd9SJan Schumann                $this->checkPass($loginuser, $loginpass);
183f4476bd9SJan Schumann            }
184f4476bd9SJan Schumann        }
185f4476bd9SJan Schumann
18659bc3b48SGerrit Uitslag        $info = array();
187f4476bd9SJan Schumann        $info['user'] = $user;
188d17fc5deSAndreas Gohr        $this->debug('LDAP user to find: ' . hsc($info['user']), 0, __LINE__, __FILE__);
18940017f0bSItamar Shoham
19070e4a085SAndreas Gohr        $info['server'] = $this->getConf('server');
191d17fc5deSAndreas Gohr        $this->debug('LDAP Server: ' . hsc($info['server']), 0, __LINE__, __FILE__);
192f4476bd9SJan Schumann
193f4476bd9SJan Schumann        //get info for given user
194d17fc5deSAndreas Gohr        $base = $this->makeFilter($this->getConf('usertree'), $info);
19570e4a085SAndreas Gohr        if ($this->getConf('userfilter')) {
196d17fc5deSAndreas Gohr            $filter = $this->makeFilter($this->getConf('userfilter'), $info);
197f4476bd9SJan Schumann        } else {
198f4476bd9SJan Schumann            $filter = "(ObjectClass=*)";
199f4476bd9SJan Schumann        }
200f4476bd9SJan Schumann
201d17fc5deSAndreas Gohr        $this->debug('LDAP Filter: ' . hsc($filter), 0, __LINE__, __FILE__);
20240017f0bSItamar Shoham
203d17fc5deSAndreas Gohr        $this->debug('LDAP user search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
204d17fc5deSAndreas Gohr        $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
205c0c77cd2SAndreas Gohr        $sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope'), $this->getConf('attributes'));
206*83616da3Shydrian        if ($sr === false) {
207*83616da3Shydrian           $this->debug('User ldap_search failed. Check configuration.', 0, __LINE__, __FILE__);
208*83616da3Shydrian           return array();
209*83616da3Shydrian        }
21040017f0bSItamar Shoham
21140017f0bSItamar Shoham        $result = @ldap_get_entries($this->con, $sr);
21240017f0bSItamar Shoham
21340017f0bSItamar Shoham        // if result is not an array
21440017f0bSItamar Shoham        if (!is_array($result)) {
21540017f0bSItamar Shoham            // no objects found
216d17fc5deSAndreas Gohr            $this->debug('LDAP search returned non-array result: ' . hsc(print($result)), -1, __LINE__, __FILE__);
217d17fc5deSAndreas Gohr            return array();
21840017f0bSItamar Shoham        }
219f4476bd9SJan Schumann
220f4476bd9SJan Schumann        // Don't accept more or less than one response
22140017f0bSItamar Shoham        if ($result['count'] != 1) {
222d17fc5deSAndreas Gohr            $this->debug(
22364159a61SAndreas Gohr                'LDAP search returned ' . hsc($result['count']) . ' results while it should return 1!',
224d17fc5deSAndreas Gohr                -1,
225d17fc5deSAndreas Gohr                __LINE__,
226d17fc5deSAndreas Gohr                __FILE__
22764159a61SAndreas Gohr            );
22840017f0bSItamar Shoham            //for($i = 0; $i < $result["count"]; $i++) {
22964159a61SAndreas Gohr            //$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__);
23040017f0bSItamar Shoham            //}
231d17fc5deSAndreas Gohr            return array();
232f4476bd9SJan Schumann        }
233f4476bd9SJan Schumann
234d17fc5deSAndreas Gohr        $this->debug('LDAP search found single result !', 0, __LINE__, __FILE__);
23540017f0bSItamar Shoham
236f4476bd9SJan Schumann        $user_result = $result[0];
237f4476bd9SJan Schumann        ldap_free_result($sr);
238f4476bd9SJan Schumann
239f4476bd9SJan Schumann        // general user info
240f4476bd9SJan Schumann        $info['dn'] = $user_result['dn'];
241f4476bd9SJan Schumann        $info['gid'] = $user_result['gidnumber'][0];
242f4476bd9SJan Schumann        $info['mail'] = $user_result['mail'][0];
243f4476bd9SJan Schumann        $info['name'] = $user_result['cn'][0];
244f4476bd9SJan Schumann        $info['grps'] = array();
245f4476bd9SJan Schumann
246f4476bd9SJan Schumann        // overwrite if other attribs are specified.
24770e4a085SAndreas Gohr        if (is_array($this->getConf('mapping'))) {
24870e4a085SAndreas Gohr            foreach ($this->getConf('mapping') as $localkey => $key) {
249f4476bd9SJan Schumann                if (is_array($key)) {
250f4476bd9SJan Schumann                    // use regexp to clean up user_result
2518f1011e8SPhy                    // $key = array($key=>$regexp), only handles the first key-value
2528f1011e8SPhy                    $regexp = current($key);
2538f1011e8SPhy                    $key = key($key);
2544f11d93dSGerrit Uitslag                    if ($user_result[$key]) foreach ($user_result[$key] as $grpkey => $grp) {
2554f11d93dSGerrit Uitslag                        if ($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
256f4476bd9SJan Schumann                            if ($localkey == 'grps') {
257f4476bd9SJan Schumann                                $info[$localkey][] = $match[1];
258f4476bd9SJan Schumann                            } else {
259f4476bd9SJan Schumann                                $info[$localkey] = $match[1];
260f4476bd9SJan Schumann                            }
261f4476bd9SJan Schumann                        }
262f4476bd9SJan Schumann                    }
263f4476bd9SJan Schumann                } else {
264f4476bd9SJan Schumann                    $info[$localkey] = $user_result[$key][0];
265f4476bd9SJan Schumann                }
266f4476bd9SJan Schumann            }
267f4476bd9SJan Schumann        }
268f4476bd9SJan Schumann        $user_result = array_merge($info, $user_result);
269f4476bd9SJan Schumann
270f4476bd9SJan Schumann        //get groups for given user if grouptree is given
27170e4a085SAndreas Gohr        if ($this->getConf('grouptree') || $this->getConf('groupfilter')) {
272d17fc5deSAndreas Gohr            $base = $this->makeFilter($this->getConf('grouptree'), $user_result);
273d17fc5deSAndreas Gohr            $filter = $this->makeFilter($this->getConf('groupfilter'), $user_result);
274d17fc5deSAndreas Gohr            $sr = $this->ldapSearch(
27564159a61SAndreas Gohr                $this->con,
27664159a61SAndreas Gohr                $base,
27764159a61SAndreas Gohr                $filter,
27864159a61SAndreas Gohr                $this->getConf('groupscope'),
279d17fc5deSAndreas Gohr                array($this->getConf('groupkey'))
280d17fc5deSAndreas Gohr            );
281d17fc5deSAndreas Gohr            $this->debug('LDAP group search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
282d17fc5deSAndreas Gohr            $this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
28370e4a085SAndreas Gohr
284f4476bd9SJan Schumann            if (!$sr) {
285f4476bd9SJan Schumann                msg("LDAP: Reading group memberships failed", -1);
286d17fc5deSAndreas Gohr                return array();
287f4476bd9SJan Schumann            }
288f4476bd9SJan Schumann            $result = ldap_get_entries($this->con, $sr);
289f4476bd9SJan Schumann            ldap_free_result($sr);
290f4476bd9SJan Schumann
291f4476bd9SJan Schumann            if (is_array($result)) foreach ($result as $grp) {
2929f72d639SAndreas Gohr                if (!empty($grp[$this->getConf('groupkey')])) {
2939f72d639SAndreas Gohr                    $group = $grp[$this->getConf('groupkey')];
2949f72d639SAndreas Gohr                    if (is_array($group)) {
2959f72d639SAndreas Gohr                        $group = $group[0];
2969f72d639SAndreas Gohr                    } else {
297d17fc5deSAndreas Gohr                        $this->debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
2989f72d639SAndreas Gohr                    }
2999f72d639SAndreas Gohr                    if ($group === '') continue;
3009f72d639SAndreas Gohr
301d17fc5deSAndreas Gohr                    $this->debug('LDAP usergroup: ' . hsc($group), 0, __LINE__, __FILE__);
3029f72d639SAndreas Gohr                    $info['grps'][] = $group;
303f4476bd9SJan Schumann                }
304f4476bd9SJan Schumann            }
305f4476bd9SJan Schumann        }
306f4476bd9SJan Schumann
307f4476bd9SJan Schumann        // always add the default group to the list of groups
30804e4890dSAndreas Gohr        if (!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) {
309f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
310f4476bd9SJan Schumann        }
311f4476bd9SJan Schumann        return $info;
312f4476bd9SJan Schumann    }
313f4476bd9SJan Schumann
314f4476bd9SJan Schumann    /**
31506da270eSAxel Angel     * Definition of the function modifyUser in order to modify the password
316b83b4364SGerrit Uitslag     *
317b83b4364SGerrit Uitslag     * @param string $user nick of the user to be changed
318b83b4364SGerrit Uitslag     * @param array $changes array of field/value pairs to be changed (password will be clear text)
319b83b4364SGerrit Uitslag     * @return  bool   true on success, false on error
32006da270eSAxel Angel     */
321d17fc5deSAndreas Gohr    public function modifyUser($user, $changes)
322d17fc5deSAndreas Gohr    {
32306da270eSAxel Angel
32406da270eSAxel Angel        // open the connection to the ldap
325d17fc5deSAndreas Gohr        if (!$this->openLDAP()) {
326d17fc5deSAndreas Gohr            $this->debug('LDAP cannot connect: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
32706da270eSAxel Angel            return false;
32806da270eSAxel Angel        }
32906da270eSAxel Angel
33006da270eSAxel Angel        // find the information about the user, in particular the "dn"
33106da270eSAxel Angel        $info = $this->getUserData($user, true);
33206da270eSAxel Angel        if (empty($info['dn'])) {
333d17fc5deSAndreas Gohr            $this->debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__);
33406da270eSAxel Angel            return false;
3358f2ea93bSAxel Angel        }
33606da270eSAxel Angel        $dn = $info['dn'];
33706da270eSAxel Angel
33806da270eSAxel Angel        // find the old password of the user
33906da270eSAxel Angel        list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
340719c6730SAxel Angel        if ($loginuser !== null) { // the user is currently logged in
34118496fe0SAndreas Gohr            $secret = auth_cookiesalt(!$loginsticky, true);
34206da270eSAxel Angel            $pass = auth_decrypt($loginpass, $secret);
34306da270eSAxel Angel
34406da270eSAxel Angel            // bind with the ldap
34506da270eSAxel Angel            if (!@ldap_bind($this->con, $dn, $pass)) {
346d17fc5deSAndreas Gohr                $this->debug(
347d17fc5deSAndreas Gohr                    'LDAP user bind failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
348d17fc5deSAndreas Gohr                    0,
349d17fc5deSAndreas Gohr                    __LINE__,
350d17fc5deSAndreas Gohr                    __FILE__
35164159a61SAndreas Gohr                );
35206da270eSAxel Angel                return false;
35306da270eSAxel Angel            }
354719c6730SAxel Angel        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
355719c6730SAxel Angel            // we are changing the password on behalf of the user (eg: forgotten password)
356719c6730SAxel Angel            // bind with the superuser ldap
3578ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
358d17fc5deSAndreas Gohr                $this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
359719c6730SAxel Angel                return false;
360719c6730SAxel Angel            }
361d17fc5deSAndreas Gohr        } else {
362719c6730SAxel Angel            return false; // no otherway
363719c6730SAxel Angel        }
36406da270eSAxel Angel
36567723447SAxel Angel        // Generate the salted hashed password for LDAP
366c3cc6e05SAndreas Gohr        $phash = new \dokuwiki\PassHash();
36767723447SAxel Angel        $hash = $phash->hash_ssha($changes['pass']);
36867723447SAxel Angel
36906da270eSAxel Angel        // change the password
37006da270eSAxel Angel        if (!@ldap_mod_replace($this->con, $dn, array('userpassword' => $hash))) {
371d17fc5deSAndreas Gohr            $this->debug(
372d17fc5deSAndreas Gohr                'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
373d17fc5deSAndreas Gohr                0,
374d17fc5deSAndreas Gohr                __LINE__,
375d17fc5deSAndreas Gohr                __FILE__
37664159a61SAndreas Gohr            );
37706da270eSAxel Angel            return false;
37806da270eSAxel Angel        }
37906da270eSAxel Angel
38006da270eSAxel Angel        return true;
38106da270eSAxel Angel    }
38206da270eSAxel Angel
38306da270eSAxel Angel    /**
384f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
38570e4a085SAndreas Gohr     *
38670e4a085SAndreas Gohr     * @return bool
387f4476bd9SJan Schumann     */
388d17fc5deSAndreas Gohr    public function isCaseSensitive()
389d17fc5deSAndreas Gohr    {
390f4476bd9SJan Schumann        return false;
391f4476bd9SJan Schumann    }
392f4476bd9SJan Schumann
393f4476bd9SJan Schumann    /**
394f4476bd9SJan Schumann     * Bulk retrieval of user data
395f4476bd9SJan Schumann     *
39670e4a085SAndreas Gohr     * @param int $start index of first user to be returned
39770e4a085SAndreas Gohr     * @param int $limit max number of users to be returned
39870e4a085SAndreas Gohr     * @param array $filter array of field/pattern pairs, null for no filter
399f4476bd9SJan Schumann     * @return  array of userinfo (refer getUserData for internal userinfo details)
400c0c77cd2SAndreas Gohr     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
401f4476bd9SJan Schumann     */
402d17fc5deSAndreas Gohr    public function retrieveUsers($start = 0, $limit = 0, $filter = array())
403d17fc5deSAndreas Gohr    {
404d17fc5deSAndreas Gohr        if (!$this->openLDAP()) return array();
405f4476bd9SJan Schumann
40670e4a085SAndreas Gohr        if (is_null($this->users)) {
407f4476bd9SJan Schumann            // Perform the search and grab all their details
40870e4a085SAndreas Gohr            if ($this->getConf('userfilter')) {
40970e4a085SAndreas Gohr                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
410f4476bd9SJan Schumann            } else {
411f4476bd9SJan Schumann                $all_filter = "(ObjectClass=*)";
412f4476bd9SJan Schumann            }
41370e4a085SAndreas Gohr            $sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
414f4476bd9SJan Schumann            $entries = ldap_get_entries($this->con, $sr);
415f4476bd9SJan Schumann            $users_array = array();
4166619ddf4SSascha Klopp            $userkey = $this->getConf('userkey');
417f4476bd9SJan Schumann            for ($i = 0; $i < $entries["count"]; $i++) {
4186619ddf4SSascha Klopp                array_push($users_array, $entries[$i][$userkey][0]);
419f4476bd9SJan Schumann            }
4200489c64bSMoisés Braga Ribeiro            Sort::asort($users_array);
421f4476bd9SJan Schumann            $result = $users_array;
422f4476bd9SJan Schumann            if (!$result) return array();
423f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
424f4476bd9SJan Schumann        }
425f4476bd9SJan Schumann        $i = 0;
426f4476bd9SJan Schumann        $count = 0;
427d17fc5deSAndreas Gohr        $this->constructPattern($filter);
428f4476bd9SJan Schumann        $result = array();
429f4476bd9SJan Schumann
430f4476bd9SJan Schumann        foreach ($this->users as $user => &$info) {
431f4476bd9SJan Schumann            if ($i++ < $start) {
432f4476bd9SJan Schumann                continue;
433f4476bd9SJan Schumann            }
434f4476bd9SJan Schumann            if ($info === false) {
435f4476bd9SJan Schumann                $info = $this->getUserData($user);
436f4476bd9SJan Schumann            }
437d17fc5deSAndreas Gohr            if ($this->filter($user, $info)) {
438f4476bd9SJan Schumann                $result[$user] = $info;
4399a2c73e8SAndreas Gohr                if (($limit > 0) && (++$count >= $limit)) break;
440f4476bd9SJan Schumann            }
441f4476bd9SJan Schumann        }
442f4476bd9SJan Schumann        return $result;
443f4476bd9SJan Schumann    }
444f4476bd9SJan Schumann
445f4476bd9SJan Schumann    /**
446f4476bd9SJan Schumann     * Make LDAP filter strings.
447f4476bd9SJan Schumann     *
448f4476bd9SJan Schumann     * Used by auth_getUserData to make the filter
449f4476bd9SJan Schumann     * strings for grouptree and groupfilter
450f4476bd9SJan Schumann     *
45170e4a085SAndreas Gohr     * @param string $filter ldap search filter with placeholders
45270e4a085SAndreas Gohr     * @param array $placeholders placeholders to fill in
453f4476bd9SJan Schumann     * @return  string
454c0c77cd2SAndreas Gohr     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
455f4476bd9SJan Schumann     */
456d17fc5deSAndreas Gohr    protected function makeFilter($filter, $placeholders)
457d17fc5deSAndreas Gohr    {
458f4476bd9SJan Schumann        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
459f4476bd9SJan Schumann        //replace each match
460f4476bd9SJan Schumann        foreach ($matches[1] as $match) {
461f4476bd9SJan Schumann            //take first element if array
462f4476bd9SJan Schumann            if (is_array($placeholders[$match])) {
463f4476bd9SJan Schumann                $value = $placeholders[$match][0];
464f4476bd9SJan Schumann            } else {
465f4476bd9SJan Schumann                $value = $placeholders[$match];
466f4476bd9SJan Schumann            }
467d17fc5deSAndreas Gohr            $value = $this->filterEscape($value);
468f4476bd9SJan Schumann            $filter = str_replace('%{' . $match . '}', $value, $filter);
469f4476bd9SJan Schumann        }
470f4476bd9SJan Schumann        return $filter;
471f4476bd9SJan Schumann    }
472f4476bd9SJan Schumann
473f4476bd9SJan Schumann    /**
47470e4a085SAndreas Gohr     * return true if $user + $info match $filter criteria, false otherwise
475f4476bd9SJan Schumann     *
47670e4a085SAndreas Gohr     * @param string $user the user's login name
47770e4a085SAndreas Gohr     * @param array $info the user's userinfo array
47870e4a085SAndreas Gohr     * @return bool
479c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
480c0c77cd2SAndreas Gohr     *
481f4476bd9SJan Schumann     */
482d17fc5deSAndreas Gohr    protected function filter($user, $info)
483d17fc5deSAndreas Gohr    {
484d17fc5deSAndreas Gohr        foreach ($this->pattern as $item => $pattern) {
485f4476bd9SJan Schumann            if ($item == 'user') {
48670e4a085SAndreas Gohr                if (!preg_match($pattern, $user)) return false;
487f4476bd9SJan Schumann            } elseif ($item == 'grps') {
48870e4a085SAndreas Gohr                if (!count(preg_grep($pattern, $info['grps']))) return false;
489f4476bd9SJan Schumann            } else {
49070e4a085SAndreas Gohr                if (!preg_match($pattern, $info[$item])) return false;
491f4476bd9SJan Schumann            }
492f4476bd9SJan Schumann        }
49370e4a085SAndreas Gohr        return true;
494f4476bd9SJan Schumann    }
495f4476bd9SJan Schumann
49670e4a085SAndreas Gohr    /**
49770e4a085SAndreas Gohr     * Set the filter pattern
49870e4a085SAndreas Gohr     *
49970e4a085SAndreas Gohr     * @param $filter
50070e4a085SAndreas Gohr     * @return void
501c0c77cd2SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
502c0c77cd2SAndreas Gohr     *
50370e4a085SAndreas Gohr     */
504d17fc5deSAndreas Gohr    protected function constructPattern($filter)
505d17fc5deSAndreas Gohr    {
506d17fc5deSAndreas Gohr        $this->pattern = array();
507f4476bd9SJan Schumann        foreach ($filter as $item => $pattern) {
508d17fc5deSAndreas Gohr            $this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
509f4476bd9SJan Schumann        }
510f4476bd9SJan Schumann    }
511f4476bd9SJan Schumann
512f4476bd9SJan Schumann    /**
513f4476bd9SJan Schumann     * Escape a string to be used in a LDAP filter
514f4476bd9SJan Schumann     *
515f4476bd9SJan Schumann     * Ported from Perl's Net::LDAP::Util escape_filter_value
516f4476bd9SJan Schumann     *
51770e4a085SAndreas Gohr     * @param string $string
51870e4a085SAndreas Gohr     * @return string
519c0c77cd2SAndreas Gohr     * @author Andreas Gohr
520f4476bd9SJan Schumann     */
521d17fc5deSAndreas Gohr    protected function filterEscape($string)
522d17fc5deSAndreas Gohr    {
523234b5c9aSBernhard Liebl        // see https://github.com/adldap/adLDAP/issues/22
524234b5c9aSBernhard Liebl        return preg_replace_callback(
525234b5c9aSBernhard Liebl            '/([\x00-\x1F\*\(\)\\\\])/',
526234b5c9aSBernhard Liebl            function ($matches) {
527234b5c9aSBernhard Liebl                return "\\" . join("", unpack("H2", $matches[1]));
528234b5c9aSBernhard Liebl            },
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')) {
56970e4a085SAndreas Gohr                if (!@ldap_set_option(
570d17fc5deSAndreas Gohr                    $this->con,
571d17fc5deSAndreas Gohr                    LDAP_OPT_PROTOCOL_VERSION,
57270e4a085SAndreas Gohr                    $this->getConf('version')
57370e4a085SAndreas Gohr                )
57470e4a085SAndreas Gohr                ) {
57570e4a085SAndreas Gohr                    msg('Setting LDAP Protocol version ' . $this->getConf('version') . ' failed', -1);
576d17fc5deSAndreas Gohr                    $this->debug('LDAP version set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
577f4476bd9SJan Schumann                } else {
578f4476bd9SJan Schumann                    //use TLS (needs version 3)
57970e4a085SAndreas Gohr                    if ($this->getConf('starttls')) {
580f4476bd9SJan Schumann                        if (!@ldap_start_tls($this->con)) {
581f4476bd9SJan Schumann                            msg('Starting TLS failed', -1);
582d17fc5deSAndreas Gohr                            $this->debug('LDAP TLS set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
583f4476bd9SJan Schumann                        }
584f4476bd9SJan Schumann                    }
585f4476bd9SJan Schumann                    // needs version 3
586d75d76b2SAndreas Gohr                    if ($this->getConf('referrals') > -1) {
58770e4a085SAndreas Gohr                        if (!@ldap_set_option(
588d17fc5deSAndreas Gohr                            $this->con,
589d17fc5deSAndreas Gohr                            LDAP_OPT_REFERRALS,
59070e4a085SAndreas Gohr                            $this->getConf('referrals')
59170e4a085SAndreas Gohr                        )
59270e4a085SAndreas Gohr                        ) {
593d75d76b2SAndreas Gohr                            msg('Setting LDAP referrals failed', -1);
594d17fc5deSAndreas Gohr                            $this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
595f4476bd9SJan Schumann                        }
596f4476bd9SJan Schumann                    }
597f4476bd9SJan Schumann                }
598f4476bd9SJan Schumann            }
599f4476bd9SJan Schumann
600f4476bd9SJan Schumann            //set deref mode
60170e4a085SAndreas Gohr            if ($this->getConf('deref')) {
60270e4a085SAndreas Gohr                if (!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
60370e4a085SAndreas Gohr                    msg('Setting LDAP Deref mode ' . $this->getConf('deref') . ' failed', -1);
604d17fc5deSAndreas Gohr                    $this->debug('LDAP deref set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
605f4476bd9SJan Schumann                }
606f4476bd9SJan Schumann            }
60793a7873eSAndreas Gohr            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
60893a7873eSAndreas Gohr            if (defined('LDAP_OPT_NETWORK_TIMEOUT')) {
60993a7873eSAndreas Gohr                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
61093a7873eSAndreas Gohr            }
611a426a6cdSAndreas Gohr
612a426a6cdSAndreas Gohr            if ($this->getConf('binddn') && $this->getConf('bindpw')) {
6138ef94e9eSAndreas Gohr                $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
614a426a6cdSAndreas Gohr                $this->bound = 2;
615a426a6cdSAndreas Gohr            } else {
61693a7873eSAndreas Gohr                $bound = @ldap_bind($this->con);
617a426a6cdSAndreas Gohr            }
61893a7873eSAndreas Gohr            if ($bound) {
61993a7873eSAndreas Gohr                break;
62093a7873eSAndreas Gohr            }
62193a7873eSAndreas Gohr        }
62293a7873eSAndreas Gohr
62393a7873eSAndreas Gohr        if (!$bound) {
62493a7873eSAndreas Gohr            msg("LDAP: couldn't connect to LDAP server", -1);
625d17fc5deSAndreas Gohr            $this->debug(ldap_error($this->con), 0, __LINE__, __FILE__);
62693a7873eSAndreas Gohr            return false;
62793a7873eSAndreas Gohr        }
62893a7873eSAndreas Gohr
62970e4a085SAndreas Gohr        $this->cando['getUsers'] = true;
630f4476bd9SJan Schumann        return true;
631f4476bd9SJan Schumann    }
632f4476bd9SJan Schumann
633f4476bd9SJan Schumann    /**
634f4476bd9SJan Schumann     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
635f4476bd9SJan Schumann     *
63670e4a085SAndreas Gohr     * @param resource $link_identifier
63770e4a085SAndreas Gohr     * @param string $base_dn
63870e4a085SAndreas Gohr     * @param string $filter
63970e4a085SAndreas Gohr     * @param string $scope can be 'base', 'one' or 'sub'
640e0c26282SGerrit Uitslag     * @param null|array $attributes
64170e4a085SAndreas Gohr     * @param int $attrsonly
64270e4a085SAndreas Gohr     * @param int $sizelimit
64370e4a085SAndreas Gohr     * @return resource
644c0c77cd2SAndreas Gohr     * @author Andreas Gohr <andi@splitbrain.org>
645f4476bd9SJan Schumann     */
646d17fc5deSAndreas Gohr    protected function ldapSearch(
647d17fc5deSAndreas Gohr        $link_identifier,
648d17fc5deSAndreas Gohr        $base_dn,
649d17fc5deSAndreas Gohr        $filter,
650d17fc5deSAndreas Gohr        $scope = 'sub',
651d17fc5deSAndreas Gohr        $attributes = null,
652d17fc5deSAndreas Gohr        $attrsonly = 0,
653d17fc5deSAndreas Gohr        $sizelimit = 0
654c0c77cd2SAndreas Gohr    )
655c0c77cd2SAndreas Gohr    {
656f4476bd9SJan Schumann        if (is_null($attributes)) $attributes = array();
657f4476bd9SJan Schumann
658f4476bd9SJan Schumann        if ($scope == 'base') {
65970e4a085SAndreas Gohr            return @ldap_read(
660d17fc5deSAndreas Gohr                $link_identifier,
661d17fc5deSAndreas Gohr                $base_dn,
662d17fc5deSAndreas Gohr                $filter,
663d17fc5deSAndreas Gohr                $attributes,
664d17fc5deSAndreas Gohr                $attrsonly,
665d17fc5deSAndreas Gohr                $sizelimit
66670e4a085SAndreas Gohr            );
667f4476bd9SJan Schumann        } elseif ($scope == 'one') {
66870e4a085SAndreas Gohr            return @ldap_list(
669d17fc5deSAndreas Gohr                $link_identifier,
670d17fc5deSAndreas Gohr                $base_dn,
671d17fc5deSAndreas Gohr                $filter,
672d17fc5deSAndreas Gohr                $attributes,
673d17fc5deSAndreas Gohr                $attrsonly,
674d17fc5deSAndreas Gohr                $sizelimit
67570e4a085SAndreas Gohr            );
676f4476bd9SJan Schumann        } else {
67770e4a085SAndreas Gohr            return @ldap_search(
678d17fc5deSAndreas Gohr                $link_identifier,
679d17fc5deSAndreas Gohr                $base_dn,
680d17fc5deSAndreas Gohr                $filter,
681d17fc5deSAndreas Gohr                $attributes,
682d17fc5deSAndreas Gohr                $attrsonly,
683d17fc5deSAndreas Gohr                $sizelimit
68470e4a085SAndreas Gohr            );
685f4476bd9SJan Schumann        }
686f4476bd9SJan Schumann    }
68770e4a085SAndreas Gohr
68870e4a085SAndreas Gohr    /**
68970e4a085SAndreas Gohr     * Wrapper around msg() but outputs only when debug is enabled
69070e4a085SAndreas Gohr     *
69170e4a085SAndreas Gohr     * @param string $message
69270e4a085SAndreas Gohr     * @param int $err
69370e4a085SAndreas Gohr     * @param int $line
69470e4a085SAndreas Gohr     * @param string $file
69570e4a085SAndreas Gohr     * @return void
69670e4a085SAndreas Gohr     */
697d17fc5deSAndreas Gohr    protected function debug($message, $err, $line, $file)
698d17fc5deSAndreas Gohr    {
69970e4a085SAndreas Gohr        if (!$this->getConf('debug')) return;
70070e4a085SAndreas Gohr        msg($message, $err, $line, $file);
70170e4a085SAndreas Gohr    }
702f4476bd9SJan Schumann}
703