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