xref: /dokuwiki/lib/plugins/authldap/auth.php (revision 64159a61e94d0ce680071c8890e144982c3a8cbe)
1f4476bd9SJan Schumann<?php
2f4476bd9SJan Schumann/**
3f4476bd9SJan Schumann * LDAP authentication backend
4f4476bd9SJan Schumann *
5f4476bd9SJan Schumann * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
6f4476bd9SJan Schumann * @author    Andreas Gohr <andi@splitbrain.org>
7f4476bd9SJan Schumann * @author    Chris Smith <chris@jalakaic.co.uk>
8f4476bd9SJan Schumann * @author    Jan Schumann <js@schumann-it.com>
9f4476bd9SJan Schumann */
1093a7873eSAndreas Gohrclass auth_plugin_authldap extends DokuWiki_Auth_Plugin {
1170e4a085SAndreas Gohr    /* @var resource $con holds the LDAP connection*/
1270e4a085SAndreas Gohr    protected $con = null;
1370e4a085SAndreas Gohr
1470e4a085SAndreas Gohr    /* @var int $bound What type of connection does already exist? */
1570e4a085SAndreas Gohr    protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
1670e4a085SAndreas Gohr
1770e4a085SAndreas Gohr    /* @var array $users User data cache */
1870e4a085SAndreas Gohr    protected $users = null;
1970e4a085SAndreas Gohr
2070e4a085SAndreas Gohr    /* @var array $_pattern User filter pattern */
2170e4a085SAndreas Gohr    protected $_pattern = null;
22f4476bd9SJan Schumann
23f4476bd9SJan Schumann    /**
24f4476bd9SJan Schumann     * Constructor
25f4476bd9SJan Schumann     */
2670e4a085SAndreas Gohr    public function __construct() {
27454d868bSAndreas Gohr        parent::__construct();
28454d868bSAndreas Gohr
29f4476bd9SJan Schumann        // ldap extension is needed
30f4476bd9SJan Schumann        if(!function_exists('ldap_connect')) {
3170e4a085SAndreas Gohr            $this->_debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
32f4476bd9SJan Schumann            $this->success = false;
33f4476bd9SJan Schumann            return;
34f4476bd9SJan Schumann        }
35f4476bd9SJan Schumann
3606da270eSAxel Angel        // Add the capabilities to change the password
376619ddf4SSascha Klopp        $this->cando['modPass'] = $this->getConf('modPass');
38f4476bd9SJan Schumann    }
39f4476bd9SJan Schumann
40f4476bd9SJan Schumann    /**
41f4476bd9SJan Schumann     * Check user+password
42f4476bd9SJan Schumann     *
43f4476bd9SJan Schumann     * Checks if the given user exists and the given
44f4476bd9SJan Schumann     * plaintext password is correct by trying to bind
45f4476bd9SJan Schumann     * to the LDAP server
46f4476bd9SJan Schumann     *
47f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
4870e4a085SAndreas Gohr     * @param string $user
4970e4a085SAndreas Gohr     * @param string $pass
50f4476bd9SJan Schumann     * @return  bool
51f4476bd9SJan Schumann     */
5270e4a085SAndreas Gohr    public function checkPass($user, $pass) {
53f4476bd9SJan Schumann        // reject empty password
54f4476bd9SJan Schumann        if(empty($pass)) return false;
55f4476bd9SJan Schumann        if(!$this->_openLDAP()) return false;
56f4476bd9SJan Schumann
57f4476bd9SJan Schumann        // indirect user bind
5870e4a085SAndreas Gohr        if($this->getConf('binddn') && $this->getConf('bindpw')) {
59f4476bd9SJan Schumann            // use superuser credentials
608ef94e9eSAndreas Gohr            if(!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
61*64159a61SAndreas Gohr                $this->_debug('LDAP bind as superuser: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
62f4476bd9SJan Schumann                return false;
63f4476bd9SJan Schumann            }
64f4476bd9SJan Schumann            $this->bound = 2;
6570e4a085SAndreas Gohr        } else if($this->getConf('binddn') &&
6670e4a085SAndreas Gohr            $this->getConf('usertree') &&
6770e4a085SAndreas Gohr            $this->getConf('userfilter')
6870e4a085SAndreas Gohr        ) {
69f4476bd9SJan Schumann            // special bind string
7070e4a085SAndreas Gohr            $dn = $this->_makeFilter(
7170e4a085SAndreas Gohr                $this->getConf('binddn'),
7270e4a085SAndreas Gohr                array('user'=> $user, 'server'=> $this->getConf('server'))
7370e4a085SAndreas Gohr            );
74f4476bd9SJan Schumann
7570e4a085SAndreas Gohr        } else if(strpos($this->getConf('usertree'), '%{user}')) {
76f4476bd9SJan Schumann            // direct user bind
7770e4a085SAndreas Gohr            $dn = $this->_makeFilter(
7870e4a085SAndreas Gohr                $this->getConf('usertree'),
7970e4a085SAndreas Gohr                array('user'=> $user, 'server'=> $this->getConf('server'))
8070e4a085SAndreas Gohr            );
81f4476bd9SJan Schumann
82f4476bd9SJan Schumann        } else {
83f4476bd9SJan Schumann            // Anonymous bind
84f4476bd9SJan Schumann            if(!@ldap_bind($this->con)) {
85f4476bd9SJan Schumann                msg("LDAP: can not bind anonymously", -1);
86*64159a61SAndreas Gohr                $this->_debug('LDAP anonymous bind: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
87f4476bd9SJan Schumann                return false;
88f4476bd9SJan Schumann            }
89f4476bd9SJan Schumann        }
90f4476bd9SJan Schumann
91f4476bd9SJan Schumann        // Try to bind to with the dn if we have one.
92f4476bd9SJan Schumann        if(!empty($dn)) {
93f4476bd9SJan Schumann            // User/Password bind
94f4476bd9SJan Schumann            if(!@ldap_bind($this->con, $dn, $pass)) {
9570e4a085SAndreas Gohr                $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
96*64159a61SAndreas Gohr                $this->_debug('LDAP user dn bind: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
97f4476bd9SJan Schumann                return false;
98f4476bd9SJan Schumann            }
99f4476bd9SJan Schumann            $this->bound = 1;
100f4476bd9SJan Schumann            return true;
101f4476bd9SJan Schumann        } else {
102f4476bd9SJan Schumann            // See if we can find the user
103d397e6daSChristopher Smith            $info = $this->_getUserData($user, true);
104f4476bd9SJan Schumann            if(empty($info['dn'])) {
105f4476bd9SJan Schumann                return false;
106f4476bd9SJan Schumann            } else {
107f4476bd9SJan Schumann                $dn = $info['dn'];
108f4476bd9SJan Schumann            }
109f4476bd9SJan Schumann
110f4476bd9SJan Schumann            // Try to bind with the dn provided
111f4476bd9SJan Schumann            if(!@ldap_bind($this->con, $dn, $pass)) {
11270e4a085SAndreas Gohr                $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
113*64159a61SAndreas Gohr                $this->_debug('LDAP user bind: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
114f4476bd9SJan Schumann                return false;
115f4476bd9SJan Schumann            }
116f4476bd9SJan Schumann            $this->bound = 1;
117f4476bd9SJan Schumann            return true;
118f4476bd9SJan Schumann        }
119f4476bd9SJan Schumann    }
120f4476bd9SJan Schumann
121f4476bd9SJan Schumann    /**
122f4476bd9SJan Schumann     * Return user info
123f4476bd9SJan Schumann     *
124f4476bd9SJan Schumann     * Returns info about the given user needs to contain
125f4476bd9SJan Schumann     * at least these fields:
126f4476bd9SJan Schumann     *
127f4476bd9SJan Schumann     * name string  full name of the user
128f4476bd9SJan Schumann     * mail string  email addres of the user
129f4476bd9SJan Schumann     * grps array   list of groups the user is in
130f4476bd9SJan Schumann     *
131f4476bd9SJan Schumann     * This LDAP specific function returns the following
132f4476bd9SJan Schumann     * addional fields:
133f4476bd9SJan Schumann     *
134f4476bd9SJan Schumann     * dn     string  distinguished name (DN)
135f4476bd9SJan Schumann     * uid    string  Posix User ID
136f4476bd9SJan Schumann     * inbind bool    for internal use - avoid loop in binding
137f4476bd9SJan Schumann     *
138f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
139f4476bd9SJan Schumann     * @author  Trouble
140f4476bd9SJan Schumann     * @author  Dan Allen <dan.j.allen@gmail.com>
141f4476bd9SJan Schumann     * @author  <evaldas.auryla@pheur.org>
142f4476bd9SJan Schumann     * @author  Stephane Chazelas <stephane.chazelas@emerson.com>
1433e23f03eSSteScho     * @author  Steffen Schoch <schoch@dsb.net>
14470e4a085SAndreas Gohr     *
14570e4a085SAndreas Gohr     * @param   string $user
1462046a654SChristopher Smith     * @param   bool   $requireGroups (optional) - ignored, groups are always supplied by this plugin
147d397e6daSChristopher Smith     * @return  array containing user data or false
148d397e6daSChristopher Smith     */
1492046a654SChristopher Smith    public function getUserData($user, $requireGroups=true) {
150d397e6daSChristopher Smith        return $this->_getUserData($user);
151d397e6daSChristopher Smith    }
152d397e6daSChristopher Smith
153d397e6daSChristopher Smith    /**
154d397e6daSChristopher Smith     * @param   string $user
15570e4a085SAndreas Gohr     * @param   bool   $inbind authldap specific, true if in bind phase
156f4476bd9SJan Schumann     * @return  array containing user data or false
157f4476bd9SJan Schumann     */
158d397e6daSChristopher Smith    protected function _getUserData($user, $inbind = false) {
159f4476bd9SJan Schumann        global $conf;
160f4476bd9SJan Schumann        if(!$this->_openLDAP()) return false;
161f4476bd9SJan Schumann
162f4476bd9SJan Schumann        // force superuser bind if wanted and not bound as superuser yet
16370e4a085SAndreas Gohr        if($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
164f4476bd9SJan Schumann            // use superuser credentials
1658ef94e9eSAndreas Gohr            if(!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
166*64159a61SAndreas Gohr                $this->_debug('LDAP bind as superuser: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
167f4476bd9SJan Schumann                return false;
168f4476bd9SJan Schumann            }
169f4476bd9SJan Schumann            $this->bound = 2;
170f4476bd9SJan Schumann        } elseif($this->bound == 0 && !$inbind) {
171f4476bd9SJan Schumann            // in some cases getUserData is called outside the authentication workflow
172f4476bd9SJan Schumann            // eg. for sending email notification on subscribed pages. This data might not
173f4476bd9SJan Schumann            // be accessible anonymously, so we try to rebind the current user here
174f4476bd9SJan Schumann            list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
175f4476bd9SJan Schumann            if($loginuser && $loginpass) {
176b4304655SMichael Hamann                $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
177f4476bd9SJan Schumann                $this->checkPass($loginuser, $loginpass);
178f4476bd9SJan Schumann            }
179f4476bd9SJan Schumann        }
180f4476bd9SJan Schumann
18159bc3b48SGerrit Uitslag        $info = array();
182f4476bd9SJan Schumann        $info['user']   = $user;
183*64159a61SAndreas Gohr		$this->_debug('LDAP user to find: '.hsc($info['user']), 0, __LINE__, __FILE__);
18440017f0bSItamar Shoham
18570e4a085SAndreas Gohr        $info['server'] = $this->getConf('server');
186*64159a61SAndreas Gohr		$this->_debug('LDAP Server: '.hsc($info['server']), 0, __LINE__, __FILE__);
18740017f0bSItamar Shoham
188f4476bd9SJan Schumann
189f4476bd9SJan Schumann        //get info for given user
19070e4a085SAndreas Gohr        $base = $this->_makeFilter($this->getConf('usertree'), $info);
19170e4a085SAndreas Gohr        if($this->getConf('userfilter')) {
19270e4a085SAndreas Gohr            $filter = $this->_makeFilter($this->getConf('userfilter'), $info);
193f4476bd9SJan Schumann        } else {
194f4476bd9SJan Schumann            $filter = "(ObjectClass=*)";
195f4476bd9SJan Schumann        }
196f4476bd9SJan Schumann
197*64159a61SAndreas Gohr		$this->_debug('LDAP Filter: '.hsc($filter), 0, __LINE__, __FILE__);
19840017f0bSItamar Shoham
199*64159a61SAndreas Gohr        $this->_debug('LDAP user search: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
200*64159a61SAndreas Gohr        $this->_debug('LDAP search at: '.hsc($base.' '.$filter), 0, __LINE__, __FILE__);
20140017f0bSItamar Shoham		$sr     = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('userscope'));
20240017f0bSItamar Shoham
20340017f0bSItamar Shoham		$result = @ldap_get_entries($this->con, $sr);
20440017f0bSItamar Shoham
20540017f0bSItamar Shoham        // if result is not an array
20640017f0bSItamar Shoham        if(!is_array($result)) {
20740017f0bSItamar Shoham			// no objects found
208*64159a61SAndreas Gohr			$this->_debug('LDAP search returned non-array result: '.hsc(print($result)), -1, __LINE__, __FILE__);
20940017f0bSItamar Shoham            return false;
21040017f0bSItamar Shoham        }
211f4476bd9SJan Schumann
212f4476bd9SJan Schumann		// Don't accept more or less than one response
21340017f0bSItamar Shoham		if ($result['count'] != 1)		{
214*64159a61SAndreas Gohr			$this->_debug(
215*64159a61SAndreas Gohr			    'LDAP search returned '.hsc($result['count']).' results while it should return 1!',
216*64159a61SAndreas Gohr                -1, __LINE__, __FILE__
217*64159a61SAndreas Gohr            );
21840017f0bSItamar Shoham			//for($i = 0; $i < $result["count"]; $i++) {
219*64159a61SAndreas Gohr				//$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__);
22040017f0bSItamar Shoham			//}
22140017f0bSItamar Shoham			return false;
222f4476bd9SJan Schumann		}
223f4476bd9SJan Schumann
22440017f0bSItamar Shoham
22540017f0bSItamar Shoham		$this->_debug('LDAP search found single result !', 0, __LINE__, __FILE__);
22640017f0bSItamar Shoham
227f4476bd9SJan Schumann        $user_result = $result[0];
228f4476bd9SJan Schumann        ldap_free_result($sr);
229f4476bd9SJan Schumann
230f4476bd9SJan Schumann        // general user info
231f4476bd9SJan Schumann        $info['dn']   = $user_result['dn'];
232f4476bd9SJan Schumann        $info['gid']  = $user_result['gidnumber'][0];
233f4476bd9SJan Schumann        $info['mail'] = $user_result['mail'][0];
234f4476bd9SJan Schumann        $info['name'] = $user_result['cn'][0];
235f4476bd9SJan Schumann        $info['grps'] = array();
236f4476bd9SJan Schumann
237f4476bd9SJan Schumann        // overwrite if other attribs are specified.
23870e4a085SAndreas Gohr        if(is_array($this->getConf('mapping'))) {
23970e4a085SAndreas Gohr            foreach($this->getConf('mapping') as $localkey => $key) {
240f4476bd9SJan Schumann                if(is_array($key)) {
241f4476bd9SJan Schumann                    // use regexp to clean up user_result
2428f1011e8SPhy                    // $key = array($key=>$regexp), only handles the first key-value
2438f1011e8SPhy                    $regexp = current($key);
2448f1011e8SPhy                    $key = key($key);
2454f11d93dSGerrit Uitslag                    if($user_result[$key]) foreach($user_result[$key] as $grpkey => $grp) {
2464f11d93dSGerrit Uitslag                        if($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
247f4476bd9SJan Schumann                            if($localkey == 'grps') {
248f4476bd9SJan Schumann                                $info[$localkey][] = $match[1];
249f4476bd9SJan Schumann                            } else {
250f4476bd9SJan Schumann                                $info[$localkey] = $match[1];
251f4476bd9SJan Schumann                            }
252f4476bd9SJan Schumann                        }
253f4476bd9SJan Schumann                    }
254f4476bd9SJan Schumann                } else {
255f4476bd9SJan Schumann                    $info[$localkey] = $user_result[$key][0];
256f4476bd9SJan Schumann                }
257f4476bd9SJan Schumann            }
258f4476bd9SJan Schumann        }
259f4476bd9SJan Schumann        $user_result = array_merge($info, $user_result);
260f4476bd9SJan Schumann
261f4476bd9SJan Schumann        //get groups for given user if grouptree is given
26270e4a085SAndreas Gohr        if($this->getConf('grouptree') || $this->getConf('groupfilter')) {
26370e4a085SAndreas Gohr            $base   = $this->_makeFilter($this->getConf('grouptree'), $user_result);
26470e4a085SAndreas Gohr            $filter = $this->_makeFilter($this->getConf('groupfilter'), $user_result);
265*64159a61SAndreas Gohr            $sr     = $this->_ldapsearch(
266*64159a61SAndreas Gohr                $this->con,
267*64159a61SAndreas Gohr                $base,
268*64159a61SAndreas Gohr                $filter,
269*64159a61SAndreas Gohr                $this->getConf('groupscope'),
270*64159a61SAndreas Gohr                array($this->getConf('groupkey')))
271*64159a61SAndreas Gohr            ;
272*64159a61SAndreas Gohr            $this->_debug('LDAP group search: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
273*64159a61SAndreas Gohr            $this->_debug('LDAP search at: '.hsc($base.' '.$filter), 0, __LINE__, __FILE__);
27470e4a085SAndreas Gohr
275f4476bd9SJan Schumann            if(!$sr) {
276f4476bd9SJan Schumann                msg("LDAP: Reading group memberships failed", -1);
277f4476bd9SJan Schumann                return false;
278f4476bd9SJan Schumann            }
279f4476bd9SJan Schumann            $result = ldap_get_entries($this->con, $sr);
280f4476bd9SJan Schumann            ldap_free_result($sr);
281f4476bd9SJan Schumann
282f4476bd9SJan Schumann            if(is_array($result)) foreach($result as $grp) {
2839f72d639SAndreas Gohr                if(!empty($grp[$this->getConf('groupkey')])) {
2849f72d639SAndreas Gohr                    $group = $grp[$this->getConf('groupkey')];
2859f72d639SAndreas Gohr                    if(is_array($group)){
2869f72d639SAndreas Gohr                        $group = $group[0];
2879f72d639SAndreas Gohr                    } else {
2889f72d639SAndreas Gohr                        $this->_debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
2899f72d639SAndreas Gohr                    }
2909f72d639SAndreas Gohr                    if($group === '') continue;
2919f72d639SAndreas Gohr
292*64159a61SAndreas Gohr                    $this->_debug('LDAP usergroup: '.hsc($group), 0, __LINE__, __FILE__);
2939f72d639SAndreas Gohr                    $info['grps'][] = $group;
294f4476bd9SJan Schumann                }
295f4476bd9SJan Schumann            }
296f4476bd9SJan Schumann        }
297f4476bd9SJan Schumann
298f4476bd9SJan Schumann        // always add the default group to the list of groups
29904e4890dSAndreas Gohr        if(!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) {
300f4476bd9SJan Schumann            $info['grps'][] = $conf['defaultgroup'];
301f4476bd9SJan Schumann        }
302f4476bd9SJan Schumann        return $info;
303f4476bd9SJan Schumann    }
304f4476bd9SJan Schumann
305f4476bd9SJan Schumann    /**
30606da270eSAxel Angel     * Definition of the function modifyUser in order to modify the password
307b83b4364SGerrit Uitslag     *
308b83b4364SGerrit Uitslag     * @param   string $user    nick of the user to be changed
309b83b4364SGerrit Uitslag     * @param   array  $changes array of field/value pairs to be changed (password will be clear text)
310b83b4364SGerrit Uitslag     * @return  bool   true on success, false on error
31106da270eSAxel Angel     */
31206da270eSAxel Angel
31306da270eSAxel Angel    function modifyUser($user,$changes){
31406da270eSAxel Angel
31506da270eSAxel Angel        // open the connection to the ldap
31606da270eSAxel Angel        if(!$this->_openLDAP()){
317*64159a61SAndreas Gohr            $this->_debug('LDAP cannot connect: '. hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
31806da270eSAxel Angel            return false;
31906da270eSAxel Angel        }
32006da270eSAxel Angel
32106da270eSAxel Angel        // find the information about the user, in particular the "dn"
32206da270eSAxel Angel        $info = $this->getUserData($user,true);
32306da270eSAxel Angel        if(empty($info['dn'])) {
3248f03c311SPatrick Brown            $this->_debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__);
32506da270eSAxel Angel            return false;
3268f2ea93bSAxel Angel        }
32706da270eSAxel Angel        $dn = $info['dn'];
32806da270eSAxel Angel
32906da270eSAxel Angel        // find the old password of the user
33006da270eSAxel Angel        list($loginuser,$loginsticky,$loginpass) = auth_getCookie();
331719c6730SAxel Angel        if ($loginuser !== null) { // the user is currently logged in
33218496fe0SAndreas Gohr            $secret = auth_cookiesalt(!$loginsticky, true);
33306da270eSAxel Angel            $pass   = auth_decrypt($loginpass, $secret);
33406da270eSAxel Angel
33506da270eSAxel Angel            // bind with the ldap
33606da270eSAxel Angel            if(!@ldap_bind($this->con, $dn, $pass)){
337*64159a61SAndreas Gohr                $this->_debug(
338*64159a61SAndreas Gohr                    'LDAP user bind failed: '. hsc($dn) .': '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__
339*64159a61SAndreas Gohr                );
34006da270eSAxel Angel                return false;
34106da270eSAxel Angel            }
342719c6730SAxel Angel        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
343719c6730SAxel Angel            // we are changing the password on behalf of the user (eg: forgotten password)
344719c6730SAxel Angel            // bind with the superuser ldap
3458ef94e9eSAndreas Gohr            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))){
346*64159a61SAndreas Gohr                $this->_debug('LDAP bind as superuser: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
347719c6730SAxel Angel                return false;
348719c6730SAxel Angel            }
349719c6730SAxel Angel        }
350719c6730SAxel Angel        else {
351719c6730SAxel Angel            return false; // no otherway
352719c6730SAxel Angel        }
35306da270eSAxel Angel
35467723447SAxel Angel        // Generate the salted hashed password for LDAP
35567723447SAxel Angel        $phash = new PassHash();
35667723447SAxel Angel        $hash = $phash->hash_ssha($changes['pass']);
35767723447SAxel Angel
35806da270eSAxel Angel        // change the password
35906da270eSAxel Angel        if(!@ldap_mod_replace($this->con, $dn,array('userpassword' => $hash))){
360*64159a61SAndreas Gohr            $this->_debug(
361*64159a61SAndreas Gohr                'LDAP mod replace failed: '. hsc($dn) .': '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__
362*64159a61SAndreas Gohr            );
36306da270eSAxel Angel            return false;
36406da270eSAxel Angel        }
36506da270eSAxel Angel
36606da270eSAxel Angel        return true;
36706da270eSAxel Angel    }
36806da270eSAxel Angel
36906da270eSAxel Angel    /**
370f4476bd9SJan Schumann     * Most values in LDAP are case-insensitive
37170e4a085SAndreas Gohr     *
37270e4a085SAndreas Gohr     * @return bool
373f4476bd9SJan Schumann     */
37470e4a085SAndreas Gohr    public function isCaseSensitive() {
375f4476bd9SJan Schumann        return false;
376f4476bd9SJan Schumann    }
377f4476bd9SJan Schumann
378f4476bd9SJan Schumann    /**
379f4476bd9SJan Schumann     * Bulk retrieval of user data
380f4476bd9SJan Schumann     *
381f4476bd9SJan Schumann     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
38270e4a085SAndreas Gohr     * @param   int   $start     index of first user to be returned
38370e4a085SAndreas Gohr     * @param   int   $limit     max number of users to be returned
38470e4a085SAndreas Gohr     * @param   array $filter  array of field/pattern pairs, null for no filter
385f4476bd9SJan Schumann     * @return  array of userinfo (refer getUserData for internal userinfo details)
386f4476bd9SJan Schumann     */
3879a2c73e8SAndreas Gohr    function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
388f4476bd9SJan Schumann        if(!$this->_openLDAP()) return false;
389f4476bd9SJan Schumann
39070e4a085SAndreas Gohr        if(is_null($this->users)) {
391f4476bd9SJan Schumann            // Perform the search and grab all their details
39270e4a085SAndreas Gohr            if($this->getConf('userfilter')) {
39370e4a085SAndreas Gohr                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
394f4476bd9SJan Schumann            } else {
395f4476bd9SJan Schumann                $all_filter = "(ObjectClass=*)";
396f4476bd9SJan Schumann            }
39770e4a085SAndreas Gohr            $sr          = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
398f4476bd9SJan Schumann            $entries     = ldap_get_entries($this->con, $sr);
399f4476bd9SJan Schumann            $users_array = array();
4006619ddf4SSascha Klopp            $userkey     = $this->getConf('userkey');
401f4476bd9SJan Schumann            for($i = 0; $i < $entries["count"]; $i++) {
4026619ddf4SSascha Klopp                array_push($users_array, $entries[$i][$userkey][0]);
403f4476bd9SJan Schumann            }
404f4476bd9SJan Schumann            asort($users_array);
405f4476bd9SJan Schumann            $result = $users_array;
406f4476bd9SJan Schumann            if(!$result) return array();
407f4476bd9SJan Schumann            $this->users = array_fill_keys($result, false);
408f4476bd9SJan Schumann        }
409f4476bd9SJan Schumann        $i     = 0;
410f4476bd9SJan Schumann        $count = 0;
411f4476bd9SJan Schumann        $this->_constructPattern($filter);
412f4476bd9SJan Schumann        $result = array();
413f4476bd9SJan Schumann
414f4476bd9SJan Schumann        foreach($this->users as $user => &$info) {
415f4476bd9SJan Schumann            if($i++ < $start) {
416f4476bd9SJan Schumann                continue;
417f4476bd9SJan Schumann            }
418f4476bd9SJan Schumann            if($info === false) {
419f4476bd9SJan Schumann                $info = $this->getUserData($user);
420f4476bd9SJan Schumann            }
421f4476bd9SJan Schumann            if($this->_filter($user, $info)) {
422f4476bd9SJan Schumann                $result[$user] = $info;
4239a2c73e8SAndreas Gohr                if(($limit > 0) && (++$count >= $limit)) break;
424f4476bd9SJan Schumann            }
425f4476bd9SJan Schumann        }
426f4476bd9SJan Schumann        return $result;
427f4476bd9SJan Schumann    }
428f4476bd9SJan Schumann
429f4476bd9SJan Schumann    /**
430f4476bd9SJan Schumann     * Make LDAP filter strings.
431f4476bd9SJan Schumann     *
432f4476bd9SJan Schumann     * Used by auth_getUserData to make the filter
433f4476bd9SJan Schumann     * strings for grouptree and groupfilter
434f4476bd9SJan Schumann     *
435f4476bd9SJan Schumann     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
43670e4a085SAndreas Gohr     * @param   string $filter ldap search filter with placeholders
43770e4a085SAndreas Gohr     * @param   array  $placeholders placeholders to fill in
438f4476bd9SJan Schumann     * @return  string
439f4476bd9SJan Schumann     */
44070e4a085SAndreas Gohr    protected function _makeFilter($filter, $placeholders) {
441f4476bd9SJan Schumann        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
442f4476bd9SJan Schumann        //replace each match
443f4476bd9SJan Schumann        foreach($matches[1] as $match) {
444f4476bd9SJan Schumann            //take first element if array
445f4476bd9SJan Schumann            if(is_array($placeholders[$match])) {
446f4476bd9SJan Schumann                $value = $placeholders[$match][0];
447f4476bd9SJan Schumann            } else {
448f4476bd9SJan Schumann                $value = $placeholders[$match];
449f4476bd9SJan Schumann            }
450f4476bd9SJan Schumann            $value  = $this->_filterEscape($value);
451f4476bd9SJan Schumann            $filter = str_replace('%{'.$match.'}', $value, $filter);
452f4476bd9SJan Schumann        }
453f4476bd9SJan Schumann        return $filter;
454f4476bd9SJan Schumann    }
455f4476bd9SJan Schumann
456f4476bd9SJan Schumann    /**
45770e4a085SAndreas Gohr     * return true if $user + $info match $filter criteria, false otherwise
458f4476bd9SJan Schumann     *
459f4476bd9SJan Schumann     * @author Chris Smith <chris@jalakai.co.uk>
46070e4a085SAndreas Gohr     *
46170e4a085SAndreas Gohr     * @param  string $user the user's login name
46270e4a085SAndreas Gohr     * @param  array  $info the user's userinfo array
46370e4a085SAndreas Gohr     * @return bool
464f4476bd9SJan Schumann     */
46570e4a085SAndreas Gohr    protected  function _filter($user, $info) {
466f4476bd9SJan Schumann        foreach($this->_pattern as $item => $pattern) {
467f4476bd9SJan Schumann            if($item == 'user') {
46870e4a085SAndreas Gohr                if(!preg_match($pattern, $user)) return false;
469f4476bd9SJan Schumann            } else if($item == 'grps') {
47070e4a085SAndreas Gohr                if(!count(preg_grep($pattern, $info['grps']))) return false;
471f4476bd9SJan Schumann            } else {
47270e4a085SAndreas Gohr                if(!preg_match($pattern, $info[$item])) return false;
473f4476bd9SJan Schumann            }
474f4476bd9SJan Schumann        }
47570e4a085SAndreas Gohr        return true;
476f4476bd9SJan Schumann    }
477f4476bd9SJan Schumann
47870e4a085SAndreas Gohr    /**
47970e4a085SAndreas Gohr     * Set the filter pattern
48070e4a085SAndreas Gohr     *
48170e4a085SAndreas Gohr     * @author Chris Smith <chris@jalakai.co.uk>
48270e4a085SAndreas Gohr     *
48370e4a085SAndreas Gohr     * @param $filter
48470e4a085SAndreas Gohr     * @return void
48570e4a085SAndreas Gohr     */
48670e4a085SAndreas Gohr    protected function _constructPattern($filter) {
487f4476bd9SJan Schumann        $this->_pattern = array();
488f4476bd9SJan Schumann        foreach($filter as $item => $pattern) {
489f4476bd9SJan Schumann            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
490f4476bd9SJan Schumann        }
491f4476bd9SJan Schumann    }
492f4476bd9SJan Schumann
493f4476bd9SJan Schumann    /**
494f4476bd9SJan Schumann     * Escape a string to be used in a LDAP filter
495f4476bd9SJan Schumann     *
496f4476bd9SJan Schumann     * Ported from Perl's Net::LDAP::Util escape_filter_value
497f4476bd9SJan Schumann     *
498f4476bd9SJan Schumann     * @author Andreas Gohr
49970e4a085SAndreas Gohr     * @param  string $string
50070e4a085SAndreas Gohr     * @return string
501f4476bd9SJan Schumann     */
50270e4a085SAndreas Gohr    protected function _filterEscape($string) {
503234b5c9aSBernhard Liebl        // see https://github.com/adldap/adLDAP/issues/22
504234b5c9aSBernhard Liebl        return preg_replace_callback(
505234b5c9aSBernhard Liebl            '/([\x00-\x1F\*\(\)\\\\])/',
506234b5c9aSBernhard Liebl            function ($matches) {
507234b5c9aSBernhard Liebl                return "\\".join("", unpack("H2", $matches[1]));
508234b5c9aSBernhard Liebl            },
50970e4a085SAndreas Gohr            $string
51070e4a085SAndreas Gohr        );
511f4476bd9SJan Schumann    }
512f4476bd9SJan Schumann
513f4476bd9SJan Schumann    /**
514f4476bd9SJan Schumann     * Opens a connection to the configured LDAP server and sets the wanted
515f4476bd9SJan Schumann     * option on the connection
516f4476bd9SJan Schumann     *
517f4476bd9SJan Schumann     * @author  Andreas Gohr <andi@splitbrain.org>
518f4476bd9SJan Schumann     */
51970e4a085SAndreas Gohr    protected function _openLDAP() {
520f4476bd9SJan Schumann        if($this->con) return true; // connection already established
521f4476bd9SJan Schumann
522234b5c9aSBernhard Liebl        if($this->getConf('debug')) {
523234b5c9aSBernhard Liebl            ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
524234b5c9aSBernhard Liebl        }
525234b5c9aSBernhard Liebl
526f4476bd9SJan Schumann        $this->bound = 0;
527f4476bd9SJan Schumann
52870e4a085SAndreas Gohr        $port    = $this->getConf('port');
52993a7873eSAndreas Gohr        $bound   = false;
53070e4a085SAndreas Gohr        $servers = explode(',', $this->getConf('server'));
53193a7873eSAndreas Gohr        foreach($servers as $server) {
53293a7873eSAndreas Gohr            $server    = trim($server);
53393a7873eSAndreas Gohr            $this->con = @ldap_connect($server, $port);
534f4476bd9SJan Schumann            if(!$this->con) {
53593a7873eSAndreas Gohr                continue;
536f4476bd9SJan Schumann            }
537f4476bd9SJan Schumann
53893a7873eSAndreas Gohr            /*
53993a7873eSAndreas Gohr             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
54093a7873eSAndreas Gohr             * not actually connect but just initializes the connecting parameters. The actual
54193a7873eSAndreas Gohr             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
54293a7873eSAndreas Gohr             *
54393a7873eSAndreas Gohr             * So we should try to bind to server in order to check its availability.
54493a7873eSAndreas Gohr             */
54593a7873eSAndreas Gohr
546f4476bd9SJan Schumann            //set protocol version and dependend options
54770e4a085SAndreas Gohr            if($this->getConf('version')) {
54870e4a085SAndreas Gohr                if(!@ldap_set_option(
54970e4a085SAndreas Gohr                    $this->con, LDAP_OPT_PROTOCOL_VERSION,
55070e4a085SAndreas Gohr                    $this->getConf('version')
55170e4a085SAndreas Gohr                )
55270e4a085SAndreas Gohr                ) {
55370e4a085SAndreas Gohr                    msg('Setting LDAP Protocol version '.$this->getConf('version').' failed', -1);
554*64159a61SAndreas Gohr                    $this->_debug('LDAP version set: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
555f4476bd9SJan Schumann                } else {
556f4476bd9SJan Schumann                    //use TLS (needs version 3)
55770e4a085SAndreas Gohr                    if($this->getConf('starttls')) {
558f4476bd9SJan Schumann                        if(!@ldap_start_tls($this->con)) {
559f4476bd9SJan Schumann                            msg('Starting TLS failed', -1);
560*64159a61SAndreas Gohr                            $this->_debug('LDAP TLS set: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
561f4476bd9SJan Schumann                        }
562f4476bd9SJan Schumann                    }
563f4476bd9SJan Schumann                    // needs version 3
564d75d76b2SAndreas Gohr                    if($this->getConf('referrals') > -1) {
56570e4a085SAndreas Gohr                        if(!@ldap_set_option(
56670e4a085SAndreas Gohr                            $this->con, LDAP_OPT_REFERRALS,
56770e4a085SAndreas Gohr                            $this->getConf('referrals')
56870e4a085SAndreas Gohr                        )
56970e4a085SAndreas Gohr                        ) {
570d75d76b2SAndreas Gohr                            msg('Setting LDAP referrals failed', -1);
571*64159a61SAndreas Gohr                            $this->_debug('LDAP referal set: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
572f4476bd9SJan Schumann                        }
573f4476bd9SJan Schumann                    }
574f4476bd9SJan Schumann                }
575f4476bd9SJan Schumann            }
576f4476bd9SJan Schumann
577f4476bd9SJan Schumann            //set deref mode
57870e4a085SAndreas Gohr            if($this->getConf('deref')) {
57970e4a085SAndreas Gohr                if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
58070e4a085SAndreas Gohr                    msg('Setting LDAP Deref mode '.$this->getConf('deref').' failed', -1);
581*64159a61SAndreas Gohr                    $this->_debug('LDAP deref set: '.hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
582f4476bd9SJan Schumann                }
583f4476bd9SJan Schumann            }
58493a7873eSAndreas Gohr            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
58593a7873eSAndreas Gohr            if(defined('LDAP_OPT_NETWORK_TIMEOUT')) {
58693a7873eSAndreas Gohr                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
58793a7873eSAndreas Gohr            }
588a426a6cdSAndreas Gohr
589a426a6cdSAndreas Gohr            if($this->getConf('binddn') && $this->getConf('bindpw')) {
5908ef94e9eSAndreas Gohr                $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
591a426a6cdSAndreas Gohr                $this->bound = 2;
592a426a6cdSAndreas Gohr            } else {
59393a7873eSAndreas Gohr                $bound = @ldap_bind($this->con);
594a426a6cdSAndreas Gohr            }
59593a7873eSAndreas Gohr            if($bound) {
59693a7873eSAndreas Gohr                break;
59793a7873eSAndreas Gohr            }
59893a7873eSAndreas Gohr        }
59993a7873eSAndreas Gohr
60093a7873eSAndreas Gohr        if(!$bound) {
60193a7873eSAndreas Gohr            msg("LDAP: couldn't connect to LDAP server", -1);
602234b5c9aSBernhard Liebl            $this->_debug(ldap_error($this->con), 0, __LINE__, __FILE__);
60393a7873eSAndreas Gohr            return false;
60493a7873eSAndreas Gohr        }
60593a7873eSAndreas Gohr
60670e4a085SAndreas Gohr        $this->cando['getUsers'] = true;
607f4476bd9SJan Schumann        return true;
608f4476bd9SJan Schumann    }
609f4476bd9SJan Schumann
610f4476bd9SJan Schumann    /**
611f4476bd9SJan Schumann     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
612f4476bd9SJan Schumann     *
613f4476bd9SJan Schumann     * @author Andreas Gohr <andi@splitbrain.org>
61470e4a085SAndreas Gohr     * @param resource   $link_identifier
61570e4a085SAndreas Gohr     * @param string     $base_dn
61670e4a085SAndreas Gohr     * @param string     $filter
61770e4a085SAndreas Gohr     * @param string     $scope can be 'base', 'one' or 'sub'
618e0c26282SGerrit Uitslag     * @param null|array $attributes
61970e4a085SAndreas Gohr     * @param int        $attrsonly
62070e4a085SAndreas Gohr     * @param int        $sizelimit
62170e4a085SAndreas Gohr     * @return resource
622f4476bd9SJan Schumann     */
62370e4a085SAndreas Gohr    protected function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null,
624e7fbe189SAndreas Gohr                         $attrsonly = 0, $sizelimit = 0) {
625f4476bd9SJan Schumann        if(is_null($attributes)) $attributes = array();
626f4476bd9SJan Schumann
627f4476bd9SJan Schumann        if($scope == 'base') {
62870e4a085SAndreas Gohr            return @ldap_read(
62970e4a085SAndreas Gohr                $link_identifier, $base_dn, $filter, $attributes,
630e7fbe189SAndreas Gohr                $attrsonly, $sizelimit
63170e4a085SAndreas Gohr            );
632f4476bd9SJan Schumann        } elseif($scope == 'one') {
63370e4a085SAndreas Gohr            return @ldap_list(
63470e4a085SAndreas Gohr                $link_identifier, $base_dn, $filter, $attributes,
635e7fbe189SAndreas Gohr                $attrsonly, $sizelimit
63670e4a085SAndreas Gohr            );
637f4476bd9SJan Schumann        } else {
63870e4a085SAndreas Gohr            return @ldap_search(
63970e4a085SAndreas Gohr                $link_identifier, $base_dn, $filter, $attributes,
640e7fbe189SAndreas Gohr                $attrsonly, $sizelimit
64170e4a085SAndreas Gohr            );
642f4476bd9SJan Schumann        }
643f4476bd9SJan Schumann    }
64470e4a085SAndreas Gohr
64570e4a085SAndreas Gohr    /**
64670e4a085SAndreas Gohr     * Wrapper around msg() but outputs only when debug is enabled
64770e4a085SAndreas Gohr     *
64870e4a085SAndreas Gohr     * @param string $message
64970e4a085SAndreas Gohr     * @param int    $err
65070e4a085SAndreas Gohr     * @param int    $line
65170e4a085SAndreas Gohr     * @param string $file
65270e4a085SAndreas Gohr     * @return void
65370e4a085SAndreas Gohr     */
65470e4a085SAndreas Gohr    protected function _debug($message, $err, $line, $file) {
65570e4a085SAndreas Gohr        if(!$this->getConf('debug')) return;
65670e4a085SAndreas Gohr        msg($message, $err, $line, $file);
65770e4a085SAndreas Gohr    }
65870e4a085SAndreas Gohr
659f4476bd9SJan Schumann}
660