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