xref: /dokuwiki/lib/plugins/authldap/auth.php (revision 67723447f02824ff2df7daa0f1f97d8b289c5d7a)
1<?php
2// must be run within Dokuwiki
3if(!defined('DOKU_INC')) die();
4
5/**
6 * LDAP authentication backend
7 *
8 * @license   GPL 2 (http://www.gnu.org/licenses/gpl.html)
9 * @author    Andreas Gohr <andi@splitbrain.org>
10 * @author    Chris Smith <chris@jalakaic.co.uk>
11 * @author    Jan Schumann <js@schumann-it.com>
12 */
13class auth_plugin_authldap extends DokuWiki_Auth_Plugin {
14    /* @var resource $con holds the LDAP connection*/
15    protected $con = null;
16
17    /* @var int $bound What type of connection does already exist? */
18    protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
19
20    /* @var array $users User data cache */
21    protected $users = null;
22
23    /* @var array $_pattern User filter pattern */
24    protected $_pattern = null;
25
26    /**
27     * Constructor
28     */
29    public function __construct() {
30        parent::__construct();
31
32        // ldap extension is needed
33        if(!function_exists('ldap_connect')) {
34            $this->_debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
35            $this->success = false;
36            return;
37        }
38
39        // Add the capabilities to change the password
40        $this->cando['modPass'] = true;
41    }
42
43    /**
44     * Check user+password
45     *
46     * Checks if the given user exists and the given
47     * plaintext password is correct by trying to bind
48     * to the LDAP server
49     *
50     * @author  Andreas Gohr <andi@splitbrain.org>
51     * @param string $user
52     * @param string $pass
53     * @return  bool
54     */
55    public function checkPass($user, $pass) {
56        // reject empty password
57        if(empty($pass)) return false;
58        if(!$this->_openLDAP()) return false;
59
60        // indirect user bind
61        if($this->getConf('binddn') && $this->getConf('bindpw')) {
62            // use superuser credentials
63            if(!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))) {
64                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
65                return false;
66            }
67            $this->bound = 2;
68        } else if($this->getConf('binddn') &&
69            $this->getConf('usertree') &&
70            $this->getConf('userfilter')
71        ) {
72            // special bind string
73            $dn = $this->_makeFilter(
74                $this->getConf('binddn'),
75                array('user'=> $user, 'server'=> $this->getConf('server'))
76            );
77
78        } else if(strpos($this->getConf('usertree'), '%{user}')) {
79            // direct user bind
80            $dn = $this->_makeFilter(
81                $this->getConf('usertree'),
82                array('user'=> $user, 'server'=> $this->getConf('server'))
83            );
84
85        } else {
86            // Anonymous bind
87            if(!@ldap_bind($this->con)) {
88                msg("LDAP: can not bind anonymously", -1);
89                $this->_debug('LDAP anonymous bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
90                return false;
91            }
92        }
93
94        // Try to bind to with the dn if we have one.
95        if(!empty($dn)) {
96            // User/Password bind
97            if(!@ldap_bind($this->con, $dn, $pass)) {
98                $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
99                $this->_debug('LDAP user dn bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
100                return false;
101            }
102            $this->bound = 1;
103            return true;
104        } else {
105            // See if we can find the user
106            $info = $this->getUserData($user, true);
107            if(empty($info['dn'])) {
108                return false;
109            } else {
110                $dn = $info['dn'];
111            }
112
113            // Try to bind with the dn provided
114            if(!@ldap_bind($this->con, $dn, $pass)) {
115                $this->_debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
116                $this->_debug('LDAP user bind: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
117                return false;
118            }
119            $this->bound = 1;
120            return true;
121        }
122    }
123
124    /**
125     * Return user info
126     *
127     * Returns info about the given user needs to contain
128     * at least these fields:
129     *
130     * name string  full name of the user
131     * mail string  email addres of the user
132     * grps array   list of groups the user is in
133     *
134     * This LDAP specific function returns the following
135     * addional fields:
136     *
137     * dn     string  distinguished name (DN)
138     * uid    string  Posix User ID
139     * inbind bool    for internal use - avoid loop in binding
140     *
141     * @author  Andreas Gohr <andi@splitbrain.org>
142     * @author  Trouble
143     * @author  Dan Allen <dan.j.allen@gmail.com>
144     * @author  <evaldas.auryla@pheur.org>
145     * @author  Stephane Chazelas <stephane.chazelas@emerson.com>
146     * @author  Steffen Schoch <schoch@dsb.net>
147     *
148     * @param   string $user
149     * @param   bool   $inbind authldap specific, true if in bind phase
150     * @return  array containing user data or false
151     */
152    public function getUserData($user, $inbind = false) {
153        global $conf;
154        if(!$this->_openLDAP()) return false;
155
156        // force superuser bind if wanted and not bound as superuser yet
157        if($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
158            // use superuser credentials
159            if(!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))) {
160                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
161                return false;
162            }
163            $this->bound = 2;
164        } elseif($this->bound == 0 && !$inbind) {
165            // in some cases getUserData is called outside the authentication workflow
166            // eg. for sending email notification on subscribed pages. This data might not
167            // be accessible anonymously, so we try to rebind the current user here
168            list($loginuser, $loginsticky, $loginpass) = auth_getCookie();
169            if($loginuser && $loginpass) {
170                $loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
171                $this->checkPass($loginuser, $loginpass);
172            }
173        }
174
175        $info['user']   = $user;
176        $info['server'] = $this->getConf('server');
177
178        //get info for given user
179        $base = $this->_makeFilter($this->getConf('usertree'), $info);
180        if($this->getConf('userfilter')) {
181            $filter = $this->_makeFilter($this->getConf('userfilter'), $info);
182        } else {
183            $filter = "(ObjectClass=*)";
184        }
185
186        $sr     = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('userscope'));
187        $result = @ldap_get_entries($this->con, $sr);
188        $this->_debug('LDAP user search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
189        $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__);
190
191        // Don't accept more or less than one response
192        if(!is_array($result) || $result['count'] != 1) {
193            return false; //user not found
194        }
195
196        $user_result = $result[0];
197        ldap_free_result($sr);
198
199        // general user info
200        $info['dn']   = $user_result['dn'];
201        $info['gid']  = $user_result['gidnumber'][0];
202        $info['mail'] = $user_result['mail'][0];
203        $info['name'] = $user_result['cn'][0];
204        $info['grps'] = array();
205
206        // overwrite if other attribs are specified.
207        if(is_array($this->getConf('mapping'))) {
208            foreach($this->getConf('mapping') as $localkey => $key) {
209                if(is_array($key)) {
210                    // use regexp to clean up user_result
211                    list($key, $regexp) = each($key);
212                    if($user_result[$key]) foreach($user_result[$key] as $grpkey => $grp) {
213                        if($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
214                            if($localkey == 'grps') {
215                                $info[$localkey][] = $match[1];
216                            } else {
217                                $info[$localkey] = $match[1];
218                            }
219                        }
220                    }
221                } else {
222                    $info[$localkey] = $user_result[$key][0];
223                }
224            }
225        }
226        $user_result = array_merge($info, $user_result);
227
228        //get groups for given user if grouptree is given
229        if($this->getConf('grouptree') || $this->getConf('groupfilter')) {
230            $base   = $this->_makeFilter($this->getConf('grouptree'), $user_result);
231            $filter = $this->_makeFilter($this->getConf('groupfilter'), $user_result);
232            $sr     = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('groupscope'), array($this->getConf('groupkey')));
233            $this->_debug('LDAP group search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
234            $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__);
235
236            if(!$sr) {
237                msg("LDAP: Reading group memberships failed", -1);
238                return false;
239            }
240            $result = ldap_get_entries($this->con, $sr);
241            ldap_free_result($sr);
242
243            if(is_array($result)) foreach($result as $grp) {
244                if(!empty($grp[$this->getConf('groupkey')])) {
245                    $group = $grp[$this->getConf('groupkey')];
246                    if(is_array($group)){
247                        $group = $group[0];
248                    } else {
249                        $this->_debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
250                    }
251                    if($group === '') continue;
252
253                    $this->_debug('LDAP usergroup: '.htmlspecialchars($group), 0, __LINE__, __FILE__);
254                    $info['grps'][] = $group;
255                }
256            }
257        }
258
259        // always add the default group to the list of groups
260        if(!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) {
261            $info['grps'][] = $conf['defaultgroup'];
262        }
263        return $info;
264    }
265
266    /**
267     * Definition of the function modifyUser in order to modify the password
268     */
269
270    function modifyUser($user,$changes){
271
272        // open the connection to the ldap
273        if(!$this->_openLDAP()){
274            msg('LDAP cannot connect: '. htmlspecialchars(ldap_error($this->con)));
275            return false;
276        }
277
278        // find the information about the user, in particular the "dn"
279        $info = $this->getUserData($user,true);
280        if(empty($info['dn'])) {
281            msg('LDAP cannot find your user dn: '. htmlspecialchars($info['dn']));
282            return false;
283        } else {
284            $dn = $info['dn'];
285        }
286
287        // find the new password and encrypt it whit SSHA
288        if(empty($changes['pass'])) {
289            msg('The new password is not allow because it\'s empty');
290            return false;
291        }
292
293        // find the old password of the user
294        list($loginuser,$loginsticky,$loginpass) = auth_getCookie();
295        if ($loginuser !== null) { // the user is currently logged in
296            $secret = auth_cookiesalt(!$sticky, true);
297            $pass   = auth_decrypt($loginpass, $secret);
298
299            // bind with the ldap
300            if(!@ldap_bind($this->con, $dn, $pass)){
301                msg('LDAP user bind failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
302                return false;
303            }
304        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
305            // we are changing the password on behalf of the user (eg: forgotten password)
306            // bind with the superuser ldap
307            if (!@ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'))){
308                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
309                return false;
310            }
311        }
312        else {
313            return false; // no otherway
314        }
315
316        // Generate the salted hashed password for LDAP
317        $phash = new PassHash();
318        $hash = $phash->hash_ssha($changes['pass']);
319
320        // change the password
321        if(!@ldap_mod_replace($this->con, $dn,array('userpassword' => $hash))){
322            msg('LDAP mod replace failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)));
323            return false;
324        }
325
326        return true;
327    }
328
329    /**
330     * Most values in LDAP are case-insensitive
331     *
332     * @return bool
333     */
334    public function isCaseSensitive() {
335        return false;
336    }
337
338    /**
339     * Bulk retrieval of user data
340     *
341     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
342     * @param   int   $start     index of first user to be returned
343     * @param   int   $limit     max number of users to be returned
344     * @param   array $filter  array of field/pattern pairs, null for no filter
345     * @return  array of userinfo (refer getUserData for internal userinfo details)
346     */
347    function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
348        if(!$this->_openLDAP()) return false;
349
350        if(is_null($this->users)) {
351            // Perform the search and grab all their details
352            if($this->getConf('userfilter')) {
353                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
354            } else {
355                $all_filter = "(ObjectClass=*)";
356            }
357            $sr          = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
358            $entries     = ldap_get_entries($this->con, $sr);
359            $users_array = array();
360            for($i = 0; $i < $entries["count"]; $i++) {
361                array_push($users_array, $entries[$i]["uid"][0]);
362            }
363            asort($users_array);
364            $result = $users_array;
365            if(!$result) return array();
366            $this->users = array_fill_keys($result, false);
367        }
368        $i     = 0;
369        $count = 0;
370        $this->_constructPattern($filter);
371        $result = array();
372
373        foreach($this->users as $user => &$info) {
374            if($i++ < $start) {
375                continue;
376            }
377            if($info === false) {
378                $info = $this->getUserData($user);
379            }
380            if($this->_filter($user, $info)) {
381                $result[$user] = $info;
382                if(($limit > 0) && (++$count >= $limit)) break;
383            }
384        }
385        return $result;
386    }
387
388    /**
389     * Make LDAP filter strings.
390     *
391     * Used by auth_getUserData to make the filter
392     * strings for grouptree and groupfilter
393     *
394     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
395     * @param   string $filter ldap search filter with placeholders
396     * @param   array  $placeholders placeholders to fill in
397     * @return  string
398     */
399    protected function _makeFilter($filter, $placeholders) {
400        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
401        //replace each match
402        foreach($matches[1] as $match) {
403            //take first element if array
404            if(is_array($placeholders[$match])) {
405                $value = $placeholders[$match][0];
406            } else {
407                $value = $placeholders[$match];
408            }
409            $value  = $this->_filterEscape($value);
410            $filter = str_replace('%{'.$match.'}', $value, $filter);
411        }
412        return $filter;
413    }
414
415    /**
416     * return true if $user + $info match $filter criteria, false otherwise
417     *
418     * @author Chris Smith <chris@jalakai.co.uk>
419     *
420     * @param  string $user the user's login name
421     * @param  array  $info the user's userinfo array
422     * @return bool
423     */
424    protected  function _filter($user, $info) {
425        foreach($this->_pattern as $item => $pattern) {
426            if($item == 'user') {
427                if(!preg_match($pattern, $user)) return false;
428            } else if($item == 'grps') {
429                if(!count(preg_grep($pattern, $info['grps']))) return false;
430            } else {
431                if(!preg_match($pattern, $info[$item])) return false;
432            }
433        }
434        return true;
435    }
436
437    /**
438     * Set the filter pattern
439     *
440     * @author Chris Smith <chris@jalakai.co.uk>
441     *
442     * @param $filter
443     * @return void
444     */
445    protected function _constructPattern($filter) {
446        $this->_pattern = array();
447        foreach($filter as $item => $pattern) {
448            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
449        }
450    }
451
452    /**
453     * Escape a string to be used in a LDAP filter
454     *
455     * Ported from Perl's Net::LDAP::Util escape_filter_value
456     *
457     * @author Andreas Gohr
458     * @param  string $string
459     * @return string
460     */
461    protected function _filterEscape($string) {
462        return preg_replace(
463            '/([\x00-\x1F\*\(\)\\\\])/e',
464            '"\\\\\".join("",unpack("H2","$1"))',
465            $string
466        );
467    }
468
469    /**
470     * Opens a connection to the configured LDAP server and sets the wanted
471     * option on the connection
472     *
473     * @author  Andreas Gohr <andi@splitbrain.org>
474     */
475    protected function _openLDAP() {
476        if($this->con) return true; // connection already established
477
478        $this->bound = 0;
479
480        $port    = $this->getConf('port');
481        $bound   = false;
482        $servers = explode(',', $this->getConf('server'));
483        foreach($servers as $server) {
484            $server    = trim($server);
485            $this->con = @ldap_connect($server, $port);
486            if(!$this->con) {
487                continue;
488            }
489
490            /*
491             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
492             * not actually connect but just initializes the connecting parameters. The actual
493             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
494             *
495             * So we should try to bind to server in order to check its availability.
496             */
497
498            //set protocol version and dependend options
499            if($this->getConf('version')) {
500                if(!@ldap_set_option(
501                    $this->con, LDAP_OPT_PROTOCOL_VERSION,
502                    $this->getConf('version')
503                )
504                ) {
505                    msg('Setting LDAP Protocol version '.$this->getConf('version').' failed', -1);
506                    $this->_debug('LDAP version set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
507                } else {
508                    //use TLS (needs version 3)
509                    if($this->getConf('starttls')) {
510                        if(!@ldap_start_tls($this->con)) {
511                            msg('Starting TLS failed', -1);
512                            $this->_debug('LDAP TLS set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
513                        }
514                    }
515                    // needs version 3
516                    if($this->getConf('referrals')) {
517                        if(!@ldap_set_option(
518                            $this->con, LDAP_OPT_REFERRALS,
519                            $this->getConf('referrals')
520                        )
521                        ) {
522                            msg('Setting LDAP referrals to off failed', -1);
523                            $this->_debug('LDAP referal set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
524                        }
525                    }
526                }
527            }
528
529            //set deref mode
530            if($this->getConf('deref')) {
531                if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
532                    msg('Setting LDAP Deref mode '.$this->getConf('deref').' failed', -1);
533                    $this->_debug('LDAP deref set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
534                }
535            }
536            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
537            if(defined('LDAP_OPT_NETWORK_TIMEOUT')) {
538                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
539            }
540
541            if($this->getConf('binddn') && $this->getConf('bindpw')) {
542                $bound = @ldap_bind($this->con, $this->getConf('binddn'), $this->getConf('bindpw'));
543                $this->bound = 2;
544            } else {
545                $bound = @ldap_bind($this->con);
546            }
547            if($bound) {
548                break;
549            }
550        }
551
552        if(!$bound) {
553            msg("LDAP: couldn't connect to LDAP server", -1);
554            return false;
555        }
556
557        $this->cando['getUsers'] = true;
558        return true;
559    }
560
561    /**
562     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
563     *
564     * @author Andreas Gohr <andi@splitbrain.org>
565     * @param resource $link_identifier
566     * @param string   $base_dn
567     * @param string   $filter
568     * @param string   $scope can be 'base', 'one' or 'sub'
569     * @param null     $attributes
570     * @param int      $attrsonly
571     * @param int      $sizelimit
572     * @param int      $timelimit
573     * @param int      $deref
574     * @return resource
575     */
576    protected function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null,
577                         $attrsonly = 0, $sizelimit = 0) {
578        if(is_null($attributes)) $attributes = array();
579
580        if($scope == 'base') {
581            return @ldap_read(
582                $link_identifier, $base_dn, $filter, $attributes,
583                $attrsonly, $sizelimit
584            );
585        } elseif($scope == 'one') {
586            return @ldap_list(
587                $link_identifier, $base_dn, $filter, $attributes,
588                $attrsonly, $sizelimit
589            );
590        } else {
591            return @ldap_search(
592                $link_identifier, $base_dn, $filter, $attributes,
593                $attrsonly, $sizelimit
594            );
595        }
596    }
597
598    /**
599     * Wrapper around msg() but outputs only when debug is enabled
600     *
601     * @param string $message
602     * @param int    $err
603     * @param int    $line
604     * @param string $file
605     * @return void
606     */
607    protected function _debug($message, $err, $line, $file) {
608        if(!$this->getConf('debug')) return;
609        msg($message, $err, $line, $file);
610    }
611
612}
613