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