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