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