xref: /dokuwiki/lib/plugins/authad/auth.php (revision 7910cbbbce7fd803f3ee4f458d5426eac51bfd89)
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    /**
334     * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
335     *
336     * @param array $filter
337     * @return string
338     */
339    protected function _constructSearchString($filter){
340        if (!$filter){
341            return '*';
342        }
343        $result = '*';
344        if (isset($filter['name'])) {
345            $result .= ')(displayname=*' . $filter['name'] . '*';
346            unset($filter['name']);
347        }
348
349        if (isset($filter['user'])) {
350            $result .= ')(samAccountName=*' . $filter['user'] . '*';
351            unset($filter['user']);
352        }
353
354        if (isset($filter['mail'])) {
355            $result .= ')(mail=*' . $filter['mail'] . '*';
356            unset($filter['mail']);
357        }
358        return $result;
359    }
360
361    /**
362     * Return a count of the number of user which meet $filter criteria
363     *
364     * @param array $filter  $filter array of field/pattern pairs, empty array for no filter
365     * @return int number of users
366     */
367    public function getUserCount($filter = array()) {
368        $adldap = $this->_adldap(null);
369        if(!$adldap) {
370            dbglog("authad/auth.php getUserCount(): _adldap not set.");
371            return -1;
372        }
373        if ($filter == array()) {
374            $result = $adldap->user()->all();
375        } else {
376            $searchString = $this->_constructSearchString($filter);
377            $result = $adldap->user()->all(false, $searchString);
378            if (isset($filter['grps'])) {
379                $this->users = array_fill_keys($result, false);
380                $usermanager = plugin_load("admin", "usermanager", false);
381                $usermanager->setLastdisabled(true);
382                if (!isset($this->_grpsusers[$this->_filterToString($filter)])){
383                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize());
384                } elseif (count($this->_grpsusers[$this->_filterToString($filter)]) < $usermanager->getStart() + 3*$usermanager->getPagesize()) {
385                    $this->_fillGroupUserArray($filter,$usermanager->getStart() + 3*$usermanager->getPagesize() - count($this->_grpsusers[$this->_filterToString($filter)]));
386                }
387                $result = $this->_grpsusers[$this->_filterToString($filter)];
388            } else {
389                $usermanager = plugin_load("admin", "usermanager", false);
390                $usermanager->setLastdisabled(false);
391            }
392
393        }
394
395        if (!$result) {
396            return 0;
397        }
398        return count($result);
399    }
400
401    /**
402     *
403     * create a unique string for each filter used with a group
404     *
405     * @param array $filter
406     * @return string
407     */
408    protected function _filterToString ($filter) {
409        $result = '';
410        if (isset($filter['user'])) {
411            $result .= 'user-' . $filter['user'];
412        }
413        if (isset($filter['name'])) {
414            $result .= 'name-' . $filter['name'];
415        }
416        if (isset($filter['mail'])) {
417            $result .= 'mail-' . $filter['mail'];
418        }
419        if (isset($filter['grps'])) {
420            $result .= 'grps-' . $filter['grps'];
421        }
422        return $result;
423    }
424
425    /**
426     * Create an array of $numberOfAdds users passing a certain $filter, including belonging
427     * to a certain group and save them to a object-wide array. If the array
428     * already exists try to add $numberOfAdds further users to it.
429     *
430     * @param array $filter
431     * @param int $numberOfAdds additional number of users requested
432     * @return int number of Users actually add to Array
433     */
434    protected function _fillGroupUserArray($filter, $numberOfAdds){
435        $this->_grpsusers[$this->_filterToString($filter)];
436        $i = 0;
437        $count = 0;
438        $this->_constructPattern($filter);
439        foreach ($this->users as $user => &$info) {
440            if($i++ < $this->_actualstart) {
441                continue;
442            }
443            if($info === false) {
444                $info = $this->getUserData($user);
445            }
446            if($this->_filter($user, $info)) {
447                $this->_grpsusers[$this->_filterToString($filter)][$user] = $info;
448                if(($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
449            }
450        }
451        $this->_actualstart = $i;
452        return $count;
453    }
454
455    /**
456     * Bulk retrieval of user data
457     *
458     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
459     *
460     * @param   int $start index of first user to be returned
461     * @param   int $limit max number of users to be returned
462     * @param   array $filter array of field/pattern pairs, null for no filter
463     * @return array userinfo (refer getUserData for internal userinfo details)
464     */
465    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
466        $adldap = $this->_adldap(null);
467        if(!$adldap) return false;
468
469        if(!$this->users) {
470            //get info for given user
471            $result = $adldap->user()->all(false, $this->_constructSearchString($filter));
472            if (!$result) return array();
473            $this->users = array_fill_keys($result, false);
474        }
475
476        $i     = 0;
477        $count = 0;
478        $result = array();
479
480        if (!isset($filter['grps'])) {
481            $usermanager = plugin_load("admin", "usermanager", false);
482            $usermanager->setLastdisabled(false);
483            $this->_constructPattern($filter);
484            foreach($this->users as $user => &$info) {
485                if($i++ < $start) {
486                    continue;
487                }
488                if($info === false) {
489                    $info = $this->getUserData($user);
490                }
491                $result[$user] = $info;
492                if(($limit > 0) && (++$count >= $limit)) break;
493            }
494        } else {
495            $usermanager = plugin_load("admin", "usermanager", false);
496            $usermanager->setLastdisabled(true);
497            if (!isset($this->_grpsusers[$this->_filterToString($filter)]) || count($this->_grpsusers[$this->_filterToString($filter)]) < ($start+$limit)) {
498                $this->_fillGroupUserArray($filter,$start+$limit - count($this->_grpsusers[$this->_filterToString($filter)]) +1);
499            }
500            if (!$this->_grpsusers[$this->_filterToString($filter)]) return false;
501            foreach($this->_grpsusers[$this->_filterToString($filter)] as $user => &$info) {
502                if($i++ < $start) {
503                    continue;
504                }
505                $result[$user] = $info;
506                if(($limit > 0) && (++$count >= $limit)) break;
507            }
508
509        }
510        return $result;
511    }
512
513    /**
514     * Modify user data
515     *
516     * @param   string $user      nick of the user to be changed
517     * @param   array  $changes   array of field/value pairs to be changed
518     * @return  bool
519     */
520    public function modifyUser($user, $changes) {
521        $return = true;
522        $adldap = $this->_adldap($this->_userDomain($user));
523        if(!$adldap) return false;
524
525        // password changing
526        if(isset($changes['pass'])) {
527            try {
528                $return = $adldap->user()->password($this->_userName($user),$changes['pass']);
529            } catch (adLDAPException $e) {
530                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
531                $return = false;
532            }
533            if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1);
534        }
535
536        // changing user data
537        $adchanges = array();
538        if(isset($changes['name'])) {
539            // get first and last name
540            $parts                     = explode(' ', $changes['name']);
541            $adchanges['surname']      = array_pop($parts);
542            $adchanges['firstname']    = join(' ', $parts);
543            $adchanges['display_name'] = $changes['name'];
544        }
545        if(isset($changes['mail'])) {
546            $adchanges['email'] = $changes['mail'];
547        }
548        if(count($adchanges)) {
549            try {
550                $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges);
551            } catch (adLDAPException $e) {
552                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
553                $return = false;
554            }
555        }
556
557        return $return;
558    }
559
560    /**
561     * Initialize the AdLDAP library and connect to the server
562     *
563     * When you pass null as domain, it will reuse any existing domain.
564     * Eg. the one of the logged in user. It falls back to the default
565     * domain if no current one is available.
566     *
567     * @param string|null $domain The AD domain to use
568     * @return adLDAP|bool true if a connection was established
569     */
570    protected function _adldap($domain) {
571        if(is_null($domain) && is_array($this->opts)) {
572            $domain = $this->opts['domain'];
573        }
574
575        $this->opts = $this->_loadServerConfig((string) $domain);
576        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
577
578        // connect
579        try {
580            $this->adldap[$domain] = new adLDAP($this->opts);
581            return $this->adldap[$domain];
582        } catch(adLDAPException $e) {
583            if($this->conf['debug']) {
584                msg('AD Auth: '.$e->getMessage(), -1);
585            }
586            $this->success         = false;
587            $this->adldap[$domain] = null;
588        }
589        return false;
590    }
591
592    /**
593     * Get the domain part from a user
594     *
595     * @param string $user
596     * @return string
597     */
598    public function _userDomain($user) {
599        list(, $domain) = explode('@', $user, 2);
600        return $domain;
601    }
602
603    /**
604     * Get the user part from a user
605     *
606     * @param string $user
607     * @return string
608     */
609    public function _userName($user) {
610        list($name) = explode('@', $user, 2);
611        return $name;
612    }
613
614    /**
615     * Fetch the configuration for the given AD domain
616     *
617     * @param string $domain current AD domain
618     * @return array
619     */
620    protected function _loadServerConfig($domain) {
621        // prepare adLDAP standard configuration
622        $opts = $this->conf;
623
624        $opts['domain'] = $domain;
625
626        // add possible domain specific configuration
627        if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) {
628            $opts[$key] = $val;
629        }
630
631        // handle multiple AD servers
632        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
633        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
634        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
635
636        // compatibility with old option name
637        if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username'];
638        if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password'];
639
640        // we can change the password if SSL is set
641        if($opts['use_ssl'] || $opts['use_tls']) {
642            $this->cando['modPass'] = true;
643        } else {
644            $this->cando['modPass'] = false;
645        }
646
647        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
648        if(empty($opts['admin_username'])) $opts['admin_username'] = null;
649        if(empty($opts['admin_password'])) $opts['admin_password'] = null;
650
651        // user listing needs admin priviledges
652        if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
653            $this->cando['getUsers'] = true;
654        } else {
655            $this->cando['getUsers'] = false;
656        }
657
658        return $opts;
659    }
660
661    /**
662     * Returns a list of configured domains
663     *
664     * The default domain has an empty string as key
665     *
666     * @return array associative array(key => domain)
667     */
668    public function _getConfiguredDomains() {
669        $domains = array();
670        if(empty($this->conf['account_suffix'])) return $domains; // not configured yet
671
672        // add default domain, using the name from account suffix
673        $domains[''] = ltrim($this->conf['account_suffix'], '@');
674
675        // find additional domains
676        foreach($this->conf as $key => $val) {
677            if(is_array($val) && isset($val['account_suffix'])) {
678                $domains[$key] = ltrim($val['account_suffix'], '@');
679            }
680        }
681        ksort($domains);
682
683        return $domains;
684    }
685
686    /**
687     * Check provided user and userinfo for matching patterns
688     *
689     * The patterns are set up with $this->_constructPattern()
690     *
691     * @author Chris Smith <chris@jalakai.co.uk>
692     *
693     * @param string $user
694     * @param array  $info
695     * @return bool
696     */
697    protected function _filter($user, $info) {
698        foreach($this->_pattern as $item => $pattern) {
699            if($item == 'user') {
700                if(!preg_match($pattern, $user)) return false;
701            } else if($item == 'grps') {
702                if(!count(preg_grep($pattern, $info['grps']))) return false;
703            } else {
704                if(!preg_match($pattern, $info[$item])) return false;
705            }
706        }
707        return true;
708    }
709
710    /**
711     * Create a pattern for $this->_filter()
712     *
713     * @author Chris Smith <chris@jalakai.co.uk>
714     *
715     * @param array $filter
716     */
717    protected function _constructPattern($filter) {
718        $this->_pattern = array();
719        foreach($filter as $item => $pattern) {
720            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
721        }
722    }
723}
724