xref: /dokuwiki/lib/plugins/authldap/auth.php (revision 4b3d1701df2b99bcd239b0ab8e55217f523ea8df)
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: '.htmlspecialchars(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: '.htmlspecialchars(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: '.htmlspecialchars(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: '.htmlspecialchars(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: '.htmlspecialchars(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: '.htmlspecialchars($info['user']), 0, __LINE__, __FILE__);
184
185        $info['server'] = $this->getConf('server');
186		$this->_debug('LDAP Server: '.htmlspecialchars($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: '.htmlspecialchars($filter), 0, __LINE__, __FILE__);
198
199        $this->_debug('LDAP user search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
200        $this->_debug('LDAP search at: '.htmlspecialchars($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: '.htmlspecialchars(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('LDAP search returned '.htmlspecialchars($result['count']).' results while it should return 1!', -1, __LINE__, __FILE__);
215			//for($i = 0; $i < $result["count"]; $i++) {
216				//$this->_debug('result: '.htmlspecialchars(print_r($result[$i])), 0, __LINE__, __FILE__);
217			//}
218			return false;
219		}
220
221
222		$this->_debug('LDAP search found single result !', 0, __LINE__, __FILE__);
223
224        $user_result = $result[0];
225        ldap_free_result($sr);
226
227        // general user info
228        $info['dn']   = $user_result['dn'];
229        $info['gid']  = $user_result['gidnumber'][0];
230        $info['mail'] = $user_result['mail'][0];
231        $info['name'] = $user_result['cn'][0];
232        $info['grps'] = array();
233
234        // overwrite if other attribs are specified.
235        if(is_array($this->getConf('mapping'))) {
236            foreach($this->getConf('mapping') as $localkey => $key) {
237                if(is_array($key)) {
238                    // use regexp to clean up user_result
239                    // $key = array($key=>$regexp), only handles the first key-value
240                    $regexp = current($key);
241                    $key = key($key);
242                    if($user_result[$key]) foreach($user_result[$key] as $grpkey => $grp) {
243                        if($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
244                            if($localkey == 'grps') {
245                                $info[$localkey][] = $match[1];
246                            } else {
247                                $info[$localkey] = $match[1];
248                            }
249                        }
250                    }
251                } else {
252                    $info[$localkey] = $user_result[$key][0];
253                }
254            }
255        }
256        $user_result = array_merge($info, $user_result);
257
258        //get groups for given user if grouptree is given
259        if($this->getConf('grouptree') || $this->getConf('groupfilter')) {
260            $base   = $this->_makeFilter($this->getConf('grouptree'), $user_result);
261            $filter = $this->_makeFilter($this->getConf('groupfilter'), $user_result);
262            $sr     = $this->_ldapsearch($this->con, $base, $filter, $this->getConf('groupscope'), array($this->getConf('groupkey')));
263            $this->_debug('LDAP group search: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
264            $this->_debug('LDAP search at: '.htmlspecialchars($base.' '.$filter), 0, __LINE__, __FILE__);
265
266            if(!$sr) {
267                msg("LDAP: Reading group memberships failed", -1);
268                return false;
269            }
270            $result = ldap_get_entries($this->con, $sr);
271            ldap_free_result($sr);
272
273            if(is_array($result)) foreach($result as $grp) {
274                if(!empty($grp[$this->getConf('groupkey')])) {
275                    $group = $grp[$this->getConf('groupkey')];
276                    if(is_array($group)){
277                        $group = $group[0];
278                    } else {
279                        $this->_debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
280                    }
281                    if($group === '') continue;
282
283                    $this->_debug('LDAP usergroup: '.htmlspecialchars($group), 0, __LINE__, __FILE__);
284                    $info['grps'][] = $group;
285                }
286            }
287        }
288
289        // always add the default group to the list of groups
290        if(!$info['grps'] or !in_array($conf['defaultgroup'], $info['grps'])) {
291            $info['grps'][] = $conf['defaultgroup'];
292        }
293        return $info;
294    }
295
296    /**
297     * Definition of the function modifyUser in order to modify the password
298     *
299     * @param   string $user    nick of the user to be changed
300     * @param   array  $changes array of field/value pairs to be changed (password will be clear text)
301     * @return  bool   true on success, false on error
302     */
303
304    function modifyUser($user,$changes){
305
306        // open the connection to the ldap
307        if(!$this->_openLDAP()){
308            $this->_debug('LDAP cannot connect: '. htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
309            return false;
310        }
311
312        // find the information about the user, in particular the "dn"
313        $info = $this->getUserData($user,true);
314        if(empty($info['dn'])) {
315            $this->_debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__);
316            return false;
317        }
318        $dn = $info['dn'];
319
320        // find the old password of the user
321        list($loginuser,$loginsticky,$loginpass) = auth_getCookie();
322        if ($loginuser !== null) { // the user is currently logged in
323            $secret = auth_cookiesalt(!$loginsticky, true);
324            $pass   = auth_decrypt($loginpass, $secret);
325
326            // bind with the ldap
327            if(!@ldap_bind($this->con, $dn, $pass)){
328                $this->_debug('LDAP user bind failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
329                return false;
330            }
331        } elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
332            // we are changing the password on behalf of the user (eg: forgotten password)
333            // bind with the superuser ldap
334            if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))){
335                $this->_debug('LDAP bind as superuser: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
336                return false;
337            }
338        }
339        else {
340            return false; // no otherway
341        }
342
343        // Generate the salted hashed password for LDAP
344        $phash = new PassHash();
345        $hash = $phash->hash_ssha($changes['pass']);
346
347        // change the password
348        if(!@ldap_mod_replace($this->con, $dn,array('userpassword' => $hash))){
349            $this->_debug('LDAP mod replace failed: '. htmlspecialchars($dn) .': '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
350            return false;
351        }
352
353        return true;
354    }
355
356    /**
357     * Most values in LDAP are case-insensitive
358     *
359     * @return bool
360     */
361    public function isCaseSensitive() {
362        return false;
363    }
364
365    /**
366     * Bulk retrieval of user data
367     *
368     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
369     * @param   int   $start     index of first user to be returned
370     * @param   int   $limit     max number of users to be returned
371     * @param   array $filter  array of field/pattern pairs, null for no filter
372     * @return  array of userinfo (refer getUserData for internal userinfo details)
373     */
374    function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
375        if(!$this->_openLDAP()) return false;
376
377        if(is_null($this->users)) {
378            // Perform the search and grab all their details
379            if($this->getConf('userfilter')) {
380                $all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
381            } else {
382                $all_filter = "(ObjectClass=*)";
383            }
384            $sr          = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
385            $entries     = ldap_get_entries($this->con, $sr);
386            $users_array = array();
387            $userkey     = $this->getConf('userkey');
388            for($i = 0; $i < $entries["count"]; $i++) {
389                array_push($users_array, $entries[$i][$userkey][0]);
390            }
391            asort($users_array);
392            $result = $users_array;
393            if(!$result) return array();
394            $this->users = array_fill_keys($result, false);
395        }
396        $i     = 0;
397        $count = 0;
398        $this->_constructPattern($filter);
399        $result = array();
400
401        foreach($this->users as $user => &$info) {
402            if($i++ < $start) {
403                continue;
404            }
405            if($info === false) {
406                $info = $this->getUserData($user);
407            }
408            if($this->_filter($user, $info)) {
409                $result[$user] = $info;
410                if(($limit > 0) && (++$count >= $limit)) break;
411            }
412        }
413        return $result;
414    }
415
416    /**
417     * Make LDAP filter strings.
418     *
419     * Used by auth_getUserData to make the filter
420     * strings for grouptree and groupfilter
421     *
422     * @author  Troels Liebe Bentsen <tlb@rapanden.dk>
423     * @param   string $filter ldap search filter with placeholders
424     * @param   array  $placeholders placeholders to fill in
425     * @return  string
426     */
427    protected function _makeFilter($filter, $placeholders) {
428        preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
429        //replace each match
430        foreach($matches[1] as $match) {
431            //take first element if array
432            if(is_array($placeholders[$match])) {
433                $value = $placeholders[$match][0];
434            } else {
435                $value = $placeholders[$match];
436            }
437            $value  = $this->_filterEscape($value);
438            $filter = str_replace('%{'.$match.'}', $value, $filter);
439        }
440        return $filter;
441    }
442
443    /**
444     * return true if $user + $info match $filter criteria, false otherwise
445     *
446     * @author Chris Smith <chris@jalakai.co.uk>
447     *
448     * @param  string $user the user's login name
449     * @param  array  $info the user's userinfo array
450     * @return bool
451     */
452    protected  function _filter($user, $info) {
453        foreach($this->_pattern as $item => $pattern) {
454            if($item == 'user') {
455                if(!preg_match($pattern, $user)) return false;
456            } else if($item == 'grps') {
457                if(!count(preg_grep($pattern, $info['grps']))) return false;
458            } else {
459                if(!preg_match($pattern, $info[$item])) return false;
460            }
461        }
462        return true;
463    }
464
465    /**
466     * Set the filter pattern
467     *
468     * @author Chris Smith <chris@jalakai.co.uk>
469     *
470     * @param $filter
471     * @return void
472     */
473    protected function _constructPattern($filter) {
474        $this->_pattern = array();
475        foreach($filter as $item => $pattern) {
476            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
477        }
478    }
479
480    /**
481     * Escape a string to be used in a LDAP filter
482     *
483     * Ported from Perl's Net::LDAP::Util escape_filter_value
484     *
485     * @author Andreas Gohr
486     * @param  string $string
487     * @return string
488     */
489    protected function _filterEscape($string) {
490        // see https://github.com/adldap/adLDAP/issues/22
491        return preg_replace_callback(
492            '/([\x00-\x1F\*\(\)\\\\])/',
493            function ($matches) {
494                return "\\".join("", unpack("H2", $matches[1]));
495            },
496            $string
497        );
498    }
499
500    /**
501     * Opens a connection to the configured LDAP server and sets the wanted
502     * option on the connection
503     *
504     * @author  Andreas Gohr <andi@splitbrain.org>
505     */
506    protected function _openLDAP() {
507        if($this->con) return true; // connection already established
508
509        if($this->getConf('debug')) {
510            ldap_set_option(NULL, LDAP_OPT_DEBUG_LEVEL, 7);
511        }
512
513        $this->bound = 0;
514
515        $port    = $this->getConf('port');
516        $bound   = false;
517        $servers = explode(',', $this->getConf('server'));
518        foreach($servers as $server) {
519            $server    = trim($server);
520            $this->con = @ldap_connect($server, $port);
521            if(!$this->con) {
522                continue;
523            }
524
525            /*
526             * When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
527             * not actually connect but just initializes the connecting parameters. The actual
528             * connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
529             *
530             * So we should try to bind to server in order to check its availability.
531             */
532
533            //set protocol version and dependend options
534            if($this->getConf('version')) {
535                if(!@ldap_set_option(
536                    $this->con, LDAP_OPT_PROTOCOL_VERSION,
537                    $this->getConf('version')
538                )
539                ) {
540                    msg('Setting LDAP Protocol version '.$this->getConf('version').' failed', -1);
541                    $this->_debug('LDAP version set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
542                } else {
543                    //use TLS (needs version 3)
544                    if($this->getConf('starttls')) {
545                        if(!@ldap_start_tls($this->con)) {
546                            msg('Starting TLS failed', -1);
547                            $this->_debug('LDAP TLS set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
548                        }
549                    }
550                    // needs version 3
551                    if($this->getConf('referrals') > -1) {
552                        if(!@ldap_set_option(
553                            $this->con, LDAP_OPT_REFERRALS,
554                            $this->getConf('referrals')
555                        )
556                        ) {
557                            msg('Setting LDAP referrals failed', -1);
558                            $this->_debug('LDAP referal set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
559                        }
560                    }
561                }
562            }
563
564            //set deref mode
565            if($this->getConf('deref')) {
566                if(!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
567                    msg('Setting LDAP Deref mode '.$this->getConf('deref').' failed', -1);
568                    $this->_debug('LDAP deref set: '.htmlspecialchars(ldap_error($this->con)), 0, __LINE__, __FILE__);
569                }
570            }
571            /* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
572            if(defined('LDAP_OPT_NETWORK_TIMEOUT')) {
573                ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
574            }
575
576            if($this->getConf('binddn') && $this->getConf('bindpw')) {
577                $bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
578                $this->bound = 2;
579            } else {
580                $bound = @ldap_bind($this->con);
581            }
582            if($bound) {
583                break;
584            }
585        }
586
587        if(!$bound) {
588            msg("LDAP: couldn't connect to LDAP server", -1);
589            $this->_debug(ldap_error($this->con), 0, __LINE__, __FILE__);
590            return false;
591        }
592
593        $this->cando['getUsers'] = true;
594        return true;
595    }
596
597    /**
598     * Wraps around ldap_search, ldap_list or ldap_read depending on $scope
599     *
600     * @author Andreas Gohr <andi@splitbrain.org>
601     * @param resource   $link_identifier
602     * @param string     $base_dn
603     * @param string     $filter
604     * @param string     $scope can be 'base', 'one' or 'sub'
605     * @param null|array $attributes
606     * @param int        $attrsonly
607     * @param int        $sizelimit
608     * @return resource
609     */
610    protected function _ldapsearch($link_identifier, $base_dn, $filter, $scope = 'sub', $attributes = null,
611                         $attrsonly = 0, $sizelimit = 0) {
612        if(is_null($attributes)) $attributes = array();
613
614        if($scope == 'base') {
615            return @ldap_read(
616                $link_identifier, $base_dn, $filter, $attributes,
617                $attrsonly, $sizelimit
618            );
619        } elseif($scope == 'one') {
620            return @ldap_list(
621                $link_identifier, $base_dn, $filter, $attributes,
622                $attrsonly, $sizelimit
623            );
624        } else {
625            return @ldap_search(
626                $link_identifier, $base_dn, $filter, $attributes,
627                $attrsonly, $sizelimit
628            );
629        }
630    }
631
632    /**
633     * Wrapper around msg() but outputs only when debug is enabled
634     *
635     * @param string $message
636     * @param int    $err
637     * @param int    $line
638     * @param string $file
639     * @return void
640     */
641    protected function _debug($message, $err, $line, $file) {
642        if(!$this->getConf('debug')) return;
643        msg($message, $err, $line, $file);
644    }
645
646}
647