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