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