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