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