xref: /dokuwiki/lib/plugins/authad/auth.php (revision 462e9e37f38d6de9ec19ad1476b64bac3b851fc1)
1<?php
2// must be run within Dokuwiki
3if(!defined('DOKU_INC')) die();
4
5require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
6
7/**
8 * Active Directory authentication backend for DokuWiki
9 *
10 * This makes authentication with a Active Directory server much easier
11 * than when using the normal LDAP backend by utilizing the adLDAP library
12 *
13 * Usage:
14 *   Set DokuWiki's local.protected.php auth setting to read
15 *
16 *   $conf['authtype']       = 'authad';
17 *
18 *   $conf['plugin']['authad']['account_suffix']     = '@my.domain.org';
19 *   $conf['plugin']['authad']['base_dn']            = 'DC=my,DC=domain,DC=org';
20 *   $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
21 *
22 *   //optional:
23 *   $conf['plugin']['authad']['sso']                = 1;
24 *   $conf['plugin']['authad']['admin_username']     = 'root';
25 *   $conf['plugin']['authad']['admin_password']     = 'pass';
26 *   $conf['plugin']['authad']['real_primarygroup']  = 1;
27 *   $conf['plugin']['authad']['use_ssl']            = 1;
28 *   $conf['plugin']['authad']['use_tls']            = 1;
29 *   $conf['plugin']['authad']['debug']              = 1;
30 *   // warn user about expiring password this many days in advance:
31 *   $conf['plugin']['authad']['expirywarn']         = 5;
32 *
33 *   // get additional information to the userinfo array
34 *   // add a list of comma separated ldap contact fields.
35 *   $conf['plugin']['authad']['additional'] = 'field1,field2';
36 *
37 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
38 * @author  James Van Lommel <jamesvl@gmail.com>
39 * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
40 * @author  Andreas Gohr <andi@splitbrain.org>
41 * @author  Jan Schumann <js@schumann-it.com>
42 */
43class auth_plugin_authad extends DokuWiki_Auth_Plugin {
44
45    /**
46     * @var array hold connection data for a specific AD domain
47     */
48    protected $opts = array();
49
50    /**
51     * @var array open connections for each AD domain, as adLDAP objects
52     */
53    protected $adldap = array();
54
55    /**
56     * @var bool message state
57     */
58    protected $msgshown = false;
59
60    /**
61     * @var array user listing cache
62     */
63    protected $users = array();
64
65    /**
66     * @var array filter patterns for listing users
67     */
68    protected $_pattern = array();
69
70    protected $_actualstart = 0;
71
72    protected $_grpsusers = array();
73
74    /**
75     * Constructor
76     */
77    public function __construct() {
78        global $INPUT;
79        parent::__construct();
80
81        // we load the config early to modify it a bit here
82        $this->loadConfig();
83
84        // additional information fields
85        if(isset($this->conf['additional'])) {
86            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
87            $this->conf['additional'] = explode(',', $this->conf['additional']);
88        } else $this->conf['additional'] = array();
89
90        // ldap extension is needed
91        if(!function_exists('ldap_connect')) {
92            if($this->conf['debug'])
93                msg("AD Auth: PHP LDAP extension not found.", -1);
94            $this->success = false;
95            return;
96        }
97
98        // Prepare SSO
99        if(!empty($_SERVER['REMOTE_USER'])) {
100
101            // make sure the right encoding is used
102            if($this->getConf('sso_charset')) {
103                $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
104            } elseif(!utf8_check($_SERVER['REMOTE_USER'])) {
105                $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
106            }
107
108            // trust the incoming user
109            if($this->conf['sso']) {
110                $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
111
112                // we need to simulate a login
113                if(empty($_COOKIE[DOKU_COOKIE])) {
114                    $INPUT->set('u', $_SERVER['REMOTE_USER']);
115                    $INPUT->set('p', 'sso_only');
116                }
117            }
118        }
119
120        // other can do's are changed in $this->_loadServerConfig() base on domain setup
121        $this->cando['modName'] = true;
122        $this->cando['modMail'] = true;
123        $this->cando['getUserCount'] = true;
124    }
125
126    /**
127     * Load domain config on capability check
128     *
129     * @param string $cap
130     * @return bool
131     */
132    public function canDo($cap) {
133        //capabilities depend on config, which may change depending on domain
134        $domain = $this->_userDomain($_SERVER['REMOTE_USER']);
135        $this->_loadServerConfig($domain);
136        return parent::canDo($cap);
137    }
138
139    /**
140     * Check user+password [required auth function]
141     *
142     * Checks if the given user exists and the given
143     * plaintext password is correct by trying to bind
144     * to the LDAP server
145     *
146     * @author  James Van Lommel <james@nosq.com>
147     * @param string $user
148     * @param string $pass
149     * @return  bool
150     */
151    public function checkPass($user, $pass) {
152        if($_SERVER['REMOTE_USER'] &&
153            $_SERVER['REMOTE_USER'] == $user &&
154            $this->conf['sso']
155        ) return true;
156
157        $adldap = $this->_adldap($this->_userDomain($user));
158        if(!$adldap) return false;
159
160        return $adldap->authenticate($this->_userName($user), $pass);
161    }
162
163    /**
164     * Return user info [required auth function]
165     *
166     * Returns info about the given user needs to contain
167     * at least these fields:
168     *
169     * name    string  full name of the user
170     * mail    string  email address of the user
171     * grps    array   list of groups the user is in
172     *
173     * This AD specific function returns the following
174     * addional fields:
175     *
176     * dn         string    distinguished name (DN)
177     * uid        string    samaccountname
178     * lastpwd    int       timestamp of the date when the password was set
179     * expires    true      if the password expires
180     * expiresin  int       seconds until the password expires
181     * any fields specified in the 'additional' config option
182     *
183     * @author  James Van Lommel <james@nosq.com>
184     * @param string $user
185     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
186     * @return array
187     */
188    public function getUserData($user, $requireGroups=true) {
189        global $conf;
190        global $lang;
191        global $ID;
192        $adldap = $this->_adldap($this->_userDomain($user));
193        if(!$adldap) return false;
194
195        if($user == '') return array();
196
197        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
198
199        // add additional fields to read
200        $fields = array_merge($fields, $this->conf['additional']);
201        $fields = array_unique($fields);
202        $fields = array_filter($fields);
203
204        //get info for given user
205        $result = $adldap->user()->info($this->_userName($user), $fields);
206        if($result == false){
207            return array();
208        }
209
210        //general user info
211        $info = array();
212        $info['name'] = $result[0]['displayname'][0];
213        $info['mail'] = $result[0]['mail'][0];
214        $info['uid']  = $result[0]['samaccountname'][0];
215        $info['dn']   = $result[0]['dn'];
216        //last password set (Windows counts from January 1st 1601)
217        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
218        //will it expire?
219        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
220
221        // additional information
222        foreach($this->conf['additional'] as $field) {
223            if(isset($result[0][strtolower($field)])) {
224                $info[$field] = $result[0][strtolower($field)][0];
225            }
226        }
227
228        // handle ActiveDirectory memberOf
229        $info['grps'] = $adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']);
230
231        if(is_array($info['grps'])) {
232            foreach($info['grps'] as $ndx => $group) {
233                $info['grps'][$ndx] = $this->cleanGroup($group);
234            }
235        }
236
237        // always add the default group to the list of groups
238        if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
239            $info['grps'][] = $conf['defaultgroup'];
240        }
241
242        // add the user's domain to the groups
243        $domain = $this->_userDomain($user);
244        if($domain && !in_array("domain-$domain", (array) $info['grps'])) {
245            $info['grps'][] = $this->cleanGroup("domain-$domain");
246        }
247
248        // check expiry time
249        if($info['expires'] && $this->conf['expirywarn']){
250            $expiry = $adldap->user()->passwordExpiry($user);
251            if(is_array($expiry)){
252                $info['expiresat'] = $expiry['expiryts'];
253                $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
254
255                // if this is the current user, warn him (once per request only)
256                if(($_SERVER['REMOTE_USER'] == $user) &&
257                    ($info['expiresin'] <= $this->conf['expirywarn']) &&
258                    !$this->msgshown
259                ) {
260                    $msg = sprintf($lang['authpwdexpire'], $info['expiresin']);
261                    if($this->canDo('modPass')) {
262                        $url = wl($ID, array('do'=> 'profile'));
263                        $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
264                    }
265                    msg($msg);
266                    $this->msgshown = true;
267                }
268            }
269        }
270
271        return $info;
272    }
273
274    /**
275     * Make AD group names usable by DokuWiki.
276     *
277     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
278     *
279     * @author  James Van Lommel (jamesvl@gmail.com)
280     * @param string $group
281     * @return string
282     */
283    public function cleanGroup($group) {
284        $group = str_replace('\\', '', $group);
285        $group = str_replace('#', '', $group);
286        $group = preg_replace('[\s]', '_', $group);
287        $group = utf8_strtolower(trim($group));
288        return $group;
289    }
290
291    /**
292     * Sanitize user names
293     *
294     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
295     *
296     * @author Andreas Gohr <gohr@cosmocode.de>
297     * @param string $user
298     * @return string
299     */
300    public function cleanUser($user) {
301        $domain = '';
302
303        // get NTLM or Kerberos domain part
304        list($dom, $user) = explode('\\', $user, 2);
305        if(!$user) $user = $dom;
306        if($dom) $domain = $dom;
307        list($user, $dom) = explode('@', $user, 2);
308        if($dom) $domain = $dom;
309
310        // clean up both
311        $domain = utf8_strtolower(trim($domain));
312        $user   = utf8_strtolower(trim($user));
313
314        // is this a known, valid domain? if not discard
315        if(!is_array($this->conf[$domain])) {
316            $domain = '';
317        }
318
319        // reattach domain
320        if($domain) $user = "$user@$domain";
321        return $user;
322    }
323
324    /**
325     * Most values in LDAP are case-insensitive
326     *
327     * @return bool
328     */
329    public function isCaseSensitive() {
330        return false;
331    }
332
333    protected function _constructSearchString($filter){
334        if (!$filter){
335            return '*';
336        }
337        $result = '*';
338        if (isset($filter['name'])) {
339            $result .= ')(displayname=*' . $filter['name'] . '*';
340            unset($filter['name']);
341        }
342        if (isset($filter['user'])) {
343            $result .= ')(samAccountName=*' . $filter['user'] . '*';
344            unset($filter['user']);
345        }
346
347        if (isset($filter['mail'])) {
348            $result .= ')(mail=*' . $filter['mail'] . '*';
349            unset($filter['mail']);
350        }
351        dbglog($result);
352        return $result;
353    }
354
355    /**
356     * @param array $filter
357     * @return int
358     */
359    public function getUserCount($filter = array()) {
360        if ($filter == array()) {
361            $adldap = $this->_adldap(null);
362            if(!$adldap) {
363                dbglog("authad/auth.php getUserCount(): _adldap not set.");
364                return -1;
365            }
366            $result = $adldap->user()->all();
367            $start = 0;
368        } else {/*
369            dbglog('_startcache: ' . $this->_startcache);
370            $usermanager = plugin_load("admin", "usermanager", false);
371            if ($this->_startcache < $usermanager->getStart()) {
372                $start = $usermanager->getStart();
373                $this->_startcache = $start;
374            } else {
375                $start = $this->_startcache;
376            }
377            $pagesize = $usermanager->getPagesize();
378            $result = $this->retrieveUsers($start, 3*$pagesize,$filter,false);*/
379            $adldap = $this->_adldap(null);
380            if(!$adldap) {
381                dbglog("authad/auth.php getUserCount(): _adldap not set.");
382                return -1;
383            }
384            dbglog($filter);
385            $searchString = $this->_constructSearchString($filter);
386            $result = $adldap->user()->all(false, $searchString);
387            if (isset($filter['grps'])) {
388                $this->users = array_fill_keys($result, false);
389                $usermanager = plugin_load("admin", "usermanager", false);
390                $usermanager->setLastdisabled(true);
391                if (!isset($this->_grpsusers[$this->_filterToString($filter)])){
392                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize());
393                } elseif (count($this->_grpsusers[$this->_filterToString($filter)]) < getStart() + 3*$usermanager->getPagesize()) {
394                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize() - count($this->_grpsusers[$this->_filterToString($filter)]));
395                }
396                $result = $this->_grpsusers[$this->_filterToString($filter)];
397            } else {
398                $usermanager = plugin_load("admin", "usermanager", false);
399                $usermanager->setLastdisabled(false);
400            }
401
402        }
403
404        if (!$result) {
405            dbglog("authad/auth.php: getting all users failed.");
406            return -1;
407        }
408        return count($result);
409    }
410
411    protected function _filterToString ($filter) {
412        $result = '';
413        if (isset($filter['user'])) {
414            $result .= 'user-' . $filter['user'];
415        }
416        if (isset($filter['name'])) {
417            $result .= 'name-' . $filter['name'];
418        }
419        if (isset($filter['mail'])) {
420            $result .= 'mail-' . $filter['mail'];
421        }
422        if (isset($filter['grps'])) {
423            $result .= 'grps-' . $filter['grps'];
424        }
425        return $result;
426    }
427
428    protected function _fillGroupUserArray($filter, $numberOfAdds){
429        $this->_grpsusers[$this->_filterToString($filter)];
430        $i = 0;
431        $count = 0;
432        $this->_constructPattern($filter);
433        foreach ($this->users as $user => &$info) {
434            if($i++ < $this->_actualstart) {
435                continue;
436            }
437            if($info === false) {
438                $info = $this->getUserData($user);
439            }
440            if($this->_filter($user, $info)) {
441                $this->_grpsusers[$this->_filterToString($filter)][$user] = $info;
442                if(($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
443            }
444        }
445        $this->_actualstart = $i;
446        return $count;
447    }
448
449    /**
450     * Bulk retrieval of user data
451     *
452     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
453     *
454     * @param   int $start index of first user to be returned
455     * @param   int $limit max number of users to be returned
456     * @param   array $filter array of field/pattern pairs, null for no filter
457     * @return array userinfo (refer getUserData for internal userinfo details)
458     */
459    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
460        dbglog("start: " . $start . "; limit: " . $limit);
461        $adldap = $this->_adldap(null);
462        if(!$adldap) return false;
463
464        if(!$this->users) {
465            //get info for given user
466            $result = $adldap->user()->all(false, $this->_constructSearchString($filter));
467            if (!$result) return array();
468            $this->users = array_fill_keys($result, false);
469        }
470
471        $i     = 0;
472        $count = 0;
473        $this->_constructPattern($filter);
474        $result = array();
475
476        if (!isset($filter['grps'])) {
477            $usermanager = plugin_load("admin", "usermanager", false);
478            $usermanager->setLastdisabled(false);
479            foreach($this->users as $user => &$info) {
480                if($i++ < $start) {
481                    continue;
482                }
483                if($info === false) {
484                    $info = $this->getUserData($user);
485                }
486                if($this->_filter($user, $info)) {
487                    $result[$user] = $info;
488                    if(($limit > 0) && (++$count >= $limit)) break;
489                }
490            }
491        } else {
492            $usermanager = plugin_load("admin", "usermanager", false);
493            $usermanager->setLastdisabled(true);
494            if (!isset($this->_grpsusers[$this->_filterToString($filter)]) || count($this->_grpsusers[$this->_filterToString($filter)]) < ($start+$limit)) {
495                $this->_fillGroupUserArray($filter,$start+$limit - count($this->_grpsusers[$this->_filterToString($filter)]) +1);
496            }
497            foreach($this->_grpsusers[$this->_filterToString($filter)] as $user => &$info) {
498                dbglog($this->_grpsusers[$this->_filterToString($filter)]);
499                if($i++ < $start) {
500                    continue;
501                }
502                $result[$user] = $info;
503                if(($limit > 0) && (++$count >= $limit)) break;
504            }
505
506        }
507        return $result;
508    }
509
510    /**
511     * Modify user data
512     *
513     * @param   string $user      nick of the user to be changed
514     * @param   array  $changes   array of field/value pairs to be changed
515     * @return  bool
516     */
517    public function modifyUser($user, $changes) {
518        $return = true;
519        $adldap = $this->_adldap($this->_userDomain($user));
520        if(!$adldap) return false;
521
522        // password changing
523        if(isset($changes['pass'])) {
524            try {
525                $return = $adldap->user()->password($this->_userName($user),$changes['pass']);
526            } catch (adLDAPException $e) {
527                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
528                $return = false;
529            }
530            if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1);
531        }
532
533        // changing user data
534        $adchanges = array();
535        if(isset($changes['name'])) {
536            // get first and last name
537            $parts                     = explode(' ', $changes['name']);
538            $adchanges['surname']      = array_pop($parts);
539            $adchanges['firstname']    = join(' ', $parts);
540            $adchanges['display_name'] = $changes['name'];
541        }
542        if(isset($changes['mail'])) {
543            $adchanges['email'] = $changes['mail'];
544        }
545        if(count($adchanges)) {
546            try {
547                $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges);
548            } catch (adLDAPException $e) {
549                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
550                $return = false;
551            }
552        }
553
554        return $return;
555    }
556
557    /**
558     * Initialize the AdLDAP library and connect to the server
559     *
560     * When you pass null as domain, it will reuse any existing domain.
561     * Eg. the one of the logged in user. It falls back to the default
562     * domain if no current one is available.
563     *
564     * @param string|null $domain The AD domain to use
565     * @return adLDAP|bool true if a connection was established
566     */
567    protected function _adldap($domain) {
568        if(is_null($domain) && is_array($this->opts)) {
569            $domain = $this->opts['domain'];
570        }
571
572        $this->opts = $this->_loadServerConfig((string) $domain);
573        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
574
575        // connect
576        try {
577            $this->adldap[$domain] = new adLDAP($this->opts);
578            return $this->adldap[$domain];
579        } catch(adLDAPException $e) {
580            if($this->conf['debug']) {
581                msg('AD Auth: '.$e->getMessage(), -1);
582            }
583            $this->success         = false;
584            $this->adldap[$domain] = null;
585        }
586        return false;
587    }
588
589    /**
590     * Get the domain part from a user
591     *
592     * @param string $user
593     * @return string
594     */
595    public function _userDomain($user) {
596        list(, $domain) = explode('@', $user, 2);
597        return $domain;
598    }
599
600    /**
601     * Get the user part from a user
602     *
603     * @param string $user
604     * @return string
605     */
606    public function _userName($user) {
607        list($name) = explode('@', $user, 2);
608        return $name;
609    }
610
611    /**
612     * Fetch the configuration for the given AD domain
613     *
614     * @param string $domain current AD domain
615     * @return array
616     */
617    protected function _loadServerConfig($domain) {
618        // prepare adLDAP standard configuration
619        $opts = $this->conf;
620
621        $opts['domain'] = $domain;
622
623        // add possible domain specific configuration
624        if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) {
625            $opts[$key] = $val;
626        }
627
628        // handle multiple AD servers
629        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
630        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
631        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
632
633        // compatibility with old option name
634        if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username'];
635        if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password'];
636
637        // we can change the password if SSL is set
638        if($opts['use_ssl'] || $opts['use_tls']) {
639            $this->cando['modPass'] = true;
640        } else {
641            $this->cando['modPass'] = false;
642        }
643
644        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
645        if(empty($opts['admin_username'])) $opts['admin_username'] = null;
646        if(empty($opts['admin_password'])) $opts['admin_password'] = null;
647
648        // user listing needs admin priviledges
649        if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
650            $this->cando['getUsers'] = true;
651        } else {
652            $this->cando['getUsers'] = false;
653        }
654
655        return $opts;
656    }
657
658    /**
659     * Returns a list of configured domains
660     *
661     * The default domain has an empty string as key
662     *
663     * @return array associative array(key => domain)
664     */
665    public function _getConfiguredDomains() {
666        $domains = array();
667        if(empty($this->conf['account_suffix'])) return $domains; // not configured yet
668
669        // add default domain, using the name from account suffix
670        $domains[''] = ltrim($this->conf['account_suffix'], '@');
671
672        // find additional domains
673        foreach($this->conf as $key => $val) {
674            if(is_array($val) && isset($val['account_suffix'])) {
675                $domains[$key] = ltrim($val['account_suffix'], '@');
676            }
677        }
678        ksort($domains);
679
680        return $domains;
681    }
682
683    /**
684     * Check provided user and userinfo for matching patterns
685     *
686     * The patterns are set up with $this->_constructPattern()
687     *
688     * @author Chris Smith <chris@jalakai.co.uk>
689     *
690     * @param string $user
691     * @param array  $info
692     * @return bool
693     */
694    protected function _filter($user, $info) {
695        foreach($this->_pattern as $item => $pattern) {
696            if($item == 'user') {
697                if(!preg_match($pattern, $user)) return false;
698            } else if($item == 'grps') {
699                if(!count(preg_grep($pattern, $info['grps']))) return false;
700            } else {
701                if(!preg_match($pattern, $info[$item])) return false;
702            }
703        }
704        return true;
705    }
706
707    /**
708     * Create a pattern for $this->_filter()
709     *
710     * @author Chris Smith <chris@jalakai.co.uk>
711     *
712     * @param array $filter
713     */
714    protected function _constructPattern($filter) {
715        $this->_pattern = array();
716        foreach($filter as $item => $pattern) {
717            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
718        }
719    }
720}
721