xref: /dokuwiki/lib/plugins/authad/auth.php (revision 25f80763dd71190679289de2b8d29f28021aedb1)
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    /**
71     * Constructor
72     */
73    public function __construct() {
74        global $INPUT;
75        parent::__construct();
76
77        // we load the config early to modify it a bit here
78        $this->loadConfig();
79
80        // additional information fields
81        if(isset($this->conf['additional'])) {
82            $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
83            $this->conf['additional'] = explode(',', $this->conf['additional']);
84        } else $this->conf['additional'] = array();
85
86        // ldap extension is needed
87        if(!function_exists('ldap_connect')) {
88            if($this->conf['debug'])
89                msg("AD Auth: PHP LDAP extension not found.", -1);
90            $this->success = false;
91            return;
92        }
93
94        // Prepare SSO
95        if(!empty($_SERVER['REMOTE_USER'])) {
96
97            // make sure the right encoding is used
98            if($this->getConf('sso_charset')) {
99                $_SERVER['REMOTE_USER'] = iconv($this->getConf('sso_charset'), 'UTF-8', $_SERVER['REMOTE_USER']);
100            } elseif(!utf8_check($_SERVER['REMOTE_USER'])) {
101                $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
102            }
103
104            // trust the incoming user
105            if($this->conf['sso']) {
106                $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
107
108                // we need to simulate a login
109                if(empty($_COOKIE[DOKU_COOKIE])) {
110                    $INPUT->set('u', $_SERVER['REMOTE_USER']);
111                    $INPUT->set('p', 'sso_only');
112                }
113            }
114        }
115
116        // other can do's are changed in $this->_loadServerConfig() base on domain setup
117        $this->cando['modName'] = true;
118        $this->cando['modMail'] = true;
119        $this->cando['getUserCount'] = true;
120    }
121
122    /**
123     * Load domain config on capability check
124     *
125     * @param string $cap
126     * @return bool
127     */
128    public function canDo($cap) {
129        //capabilities depend on config, which may change depending on domain
130        $domain = $this->_userDomain($_SERVER['REMOTE_USER']);
131        $this->_loadServerConfig($domain);
132        return parent::canDo($cap);
133    }
134
135    /**
136     * Check user+password [required auth function]
137     *
138     * Checks if the given user exists and the given
139     * plaintext password is correct by trying to bind
140     * to the LDAP server
141     *
142     * @author  James Van Lommel <james@nosq.com>
143     * @param string $user
144     * @param string $pass
145     * @return  bool
146     */
147    public function checkPass($user, $pass) {
148        if($_SERVER['REMOTE_USER'] &&
149            $_SERVER['REMOTE_USER'] == $user &&
150            $this->conf['sso']
151        ) return true;
152
153        $adldap = $this->_adldap($this->_userDomain($user));
154        if(!$adldap) return false;
155
156        return $adldap->authenticate($this->_userName($user), $pass);
157    }
158
159    /**
160     * Return user info [required auth function]
161     *
162     * Returns info about the given user needs to contain
163     * at least these fields:
164     *
165     * name    string  full name of the user
166     * mail    string  email address of the user
167     * grps    array   list of groups the user is in
168     *
169     * This AD specific function returns the following
170     * addional fields:
171     *
172     * dn         string    distinguished name (DN)
173     * uid        string    samaccountname
174     * lastpwd    int       timestamp of the date when the password was set
175     * expires    true      if the password expires
176     * expiresin  int       seconds until the password expires
177     * any fields specified in the 'additional' config option
178     *
179     * @author  James Van Lommel <james@nosq.com>
180     * @param string $user
181     * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
182     * @return array
183     */
184    public function getUserData($user, $requireGroups=true) {
185        global $conf;
186        global $lang;
187        global $ID;
188        $adldap = $this->_adldap($this->_userDomain($user));
189        if(!$adldap) return false;
190
191        if($user == '') return array();
192
193        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
194
195        // add additional fields to read
196        $fields = array_merge($fields, $this->conf['additional']);
197        $fields = array_unique($fields);
198        $fields = array_filter($fields);
199
200        //get info for given user
201        $result = $adldap->user()->info($this->_userName($user), $fields);
202        if($result == false){
203            return array();
204        }
205
206        //general user info
207        $info = array();
208        $info['name'] = $result[0]['displayname'][0];
209        $info['mail'] = $result[0]['mail'][0];
210        $info['uid']  = $result[0]['samaccountname'][0];
211        $info['dn']   = $result[0]['dn'];
212        //last password set (Windows counts from January 1st 1601)
213        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
214        //will it expire?
215        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
216
217        // additional information
218        foreach($this->conf['additional'] as $field) {
219            if(isset($result[0][strtolower($field)])) {
220                $info[$field] = $result[0][strtolower($field)][0];
221            }
222        }
223
224        // handle ActiveDirectory memberOf
225        $info['grps'] = $adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']);
226
227        if(is_array($info['grps'])) {
228            foreach($info['grps'] as $ndx => $group) {
229                $info['grps'][$ndx] = $this->cleanGroup($group);
230            }
231        }
232
233        // always add the default group to the list of groups
234        if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
235            $info['grps'][] = $conf['defaultgroup'];
236        }
237
238        // add the user's domain to the groups
239        $domain = $this->_userDomain($user);
240        if($domain && !in_array("domain-$domain", (array) $info['grps'])) {
241            $info['grps'][] = $this->cleanGroup("domain-$domain");
242        }
243
244        // check expiry time
245        if($info['expires'] && $this->conf['expirywarn']){
246            $expiry = $adldap->user()->passwordExpiry($user);
247            if(is_array($expiry)){
248                $info['expiresat'] = $expiry['expiryts'];
249                $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
250
251                // if this is the current user, warn him (once per request only)
252                if(($_SERVER['REMOTE_USER'] == $user) &&
253                    ($info['expiresin'] <= $this->conf['expirywarn']) &&
254                    !$this->msgshown
255                ) {
256                    $msg = sprintf($lang['authpwdexpire'], $info['expiresin']);
257                    if($this->canDo('modPass')) {
258                        $url = wl($ID, array('do'=> 'profile'));
259                        $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
260                    }
261                    msg($msg);
262                    $this->msgshown = true;
263                }
264            }
265        }
266
267        return $info;
268    }
269
270    /**
271     * Make AD group names usable by DokuWiki.
272     *
273     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
274     *
275     * @author  James Van Lommel (jamesvl@gmail.com)
276     * @param string $group
277     * @return string
278     */
279    public function cleanGroup($group) {
280        $group = str_replace('\\', '', $group);
281        $group = str_replace('#', '', $group);
282        $group = preg_replace('[\s]', '_', $group);
283        $group = utf8_strtolower(trim($group));
284        return $group;
285    }
286
287    /**
288     * Sanitize user names
289     *
290     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
291     *
292     * @author Andreas Gohr <gohr@cosmocode.de>
293     * @param string $user
294     * @return string
295     */
296    public function cleanUser($user) {
297        $domain = '';
298
299        // get NTLM or Kerberos domain part
300        list($dom, $user) = explode('\\', $user, 2);
301        if(!$user) $user = $dom;
302        if($dom) $domain = $dom;
303        list($user, $dom) = explode('@', $user, 2);
304        if($dom) $domain = $dom;
305
306        // clean up both
307        $domain = utf8_strtolower(trim($domain));
308        $user   = utf8_strtolower(trim($user));
309
310        // is this a known, valid domain? if not discard
311        if(!is_array($this->conf[$domain])) {
312            $domain = '';
313        }
314
315        // reattach domain
316        if($domain) $user = "$user@$domain";
317        return $user;
318    }
319
320    /**
321     * Most values in LDAP are case-insensitive
322     *
323     * @return bool
324     */
325    public function isCaseSensitive() {
326        return false;
327    }
328
329    /**
330     * @param array $filter
331     * @return int
332     */
333    public function getUserCount($filter = array()) {
334
335        $adldap = $this->_adldap(null);
336        if(!$adldap) {
337            dbglog("authad/auth.php: _adldap not set.");
338            return -1;
339        }
340
341        $result = $adldap->user()->all();
342        if (!$result) {
343            dbglog("authad/auth.php: getting all users failed.");
344            return -1;
345        }
346        return count($result);
347    }
348
349    /**
350     * Bulk retrieval of user data
351     *
352     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
353     *
354     * @param   int   $start     index of first user to be returned
355     * @param   int   $limit     max number of users to be returned
356     * @param   array $filter    array of field/pattern pairs, null for no filter
357     * @return  array userinfo (refer getUserData for internal userinfo details)
358     */
359    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
360        $adldap = $this->_adldap(null);
361        if(!$adldap) return false;
362
363        if(!$this->users) {
364            //get info for given user
365            $result = $adldap->user()->all();
366            if (!$result) return array();
367            $this->users = array_fill_keys($result, false);
368        }
369
370        $i     = 0;
371        $count = 0;
372        $this->_constructPattern($filter);
373        $result = array();
374
375        foreach($this->users as $user => &$info) {
376            if($i++ < $start) {
377                continue;
378            }
379            if($info === false) {
380                $info = $this->getUserData($user);
381            }
382            if($this->_filter($user, $info)) {
383                $result[$user] = $info;
384                if(($limit > 0) && (++$count >= $limit)) break;
385            }
386        }
387        return $result;
388    }
389
390    /**
391     * Modify user data
392     *
393     * @param   string $user      nick of the user to be changed
394     * @param   array  $changes   array of field/value pairs to be changed
395     * @return  bool
396     */
397    public function modifyUser($user, $changes) {
398        $return = true;
399        $adldap = $this->_adldap($this->_userDomain($user));
400        if(!$adldap) return false;
401
402        // password changing
403        if(isset($changes['pass'])) {
404            try {
405                $return = $adldap->user()->password($this->_userName($user),$changes['pass']);
406            } catch (adLDAPException $e) {
407                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
408                $return = false;
409            }
410            if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1);
411        }
412
413        // changing user data
414        $adchanges = array();
415        if(isset($changes['name'])) {
416            // get first and last name
417            $parts                     = explode(' ', $changes['name']);
418            $adchanges['surname']      = array_pop($parts);
419            $adchanges['firstname']    = join(' ', $parts);
420            $adchanges['display_name'] = $changes['name'];
421        }
422        if(isset($changes['mail'])) {
423            $adchanges['email'] = $changes['mail'];
424        }
425        if(count($adchanges)) {
426            try {
427                $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges);
428            } catch (adLDAPException $e) {
429                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
430                $return = false;
431            }
432        }
433
434        return $return;
435    }
436
437    /**
438     * Initialize the AdLDAP library and connect to the server
439     *
440     * When you pass null as domain, it will reuse any existing domain.
441     * Eg. the one of the logged in user. It falls back to the default
442     * domain if no current one is available.
443     *
444     * @param string|null $domain The AD domain to use
445     * @return adLDAP|bool true if a connection was established
446     */
447    protected function _adldap($domain) {
448        if(is_null($domain) && is_array($this->opts)) {
449            $domain = $this->opts['domain'];
450        }
451
452        $this->opts = $this->_loadServerConfig((string) $domain);
453        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
454
455        // connect
456        try {
457            $this->adldap[$domain] = new adLDAP($this->opts);
458            return $this->adldap[$domain];
459        } catch(adLDAPException $e) {
460            if($this->conf['debug']) {
461                msg('AD Auth: '.$e->getMessage(), -1);
462            }
463            $this->success         = false;
464            $this->adldap[$domain] = null;
465        }
466        return false;
467    }
468
469    /**
470     * Get the domain part from a user
471     *
472     * @param string $user
473     * @return string
474     */
475    public function _userDomain($user) {
476        list(, $domain) = explode('@', $user, 2);
477        return $domain;
478    }
479
480    /**
481     * Get the user part from a user
482     *
483     * @param string $user
484     * @return string
485     */
486    public function _userName($user) {
487        list($name) = explode('@', $user, 2);
488        return $name;
489    }
490
491    /**
492     * Fetch the configuration for the given AD domain
493     *
494     * @param string $domain current AD domain
495     * @return array
496     */
497    protected function _loadServerConfig($domain) {
498        // prepare adLDAP standard configuration
499        $opts = $this->conf;
500
501        $opts['domain'] = $domain;
502
503        // add possible domain specific configuration
504        if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) {
505            $opts[$key] = $val;
506        }
507
508        // handle multiple AD servers
509        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
510        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
511        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
512
513        // compatibility with old option name
514        if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username'];
515        if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password'];
516
517        // we can change the password if SSL is set
518        if($opts['use_ssl'] || $opts['use_tls']) {
519            $this->cando['modPass'] = true;
520        } else {
521            $this->cando['modPass'] = false;
522        }
523
524        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
525        if(empty($opts['admin_username'])) $opts['admin_username'] = null;
526        if(empty($opts['admin_password'])) $opts['admin_password'] = null;
527
528        // user listing needs admin priviledges
529        if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
530            $this->cando['getUsers'] = true;
531        } else {
532            $this->cando['getUsers'] = false;
533        }
534
535        return $opts;
536    }
537
538    /**
539     * Returns a list of configured domains
540     *
541     * The default domain has an empty string as key
542     *
543     * @return array associative array(key => domain)
544     */
545    public function _getConfiguredDomains() {
546        $domains = array();
547        if(empty($this->conf['account_suffix'])) return $domains; // not configured yet
548
549        // add default domain, using the name from account suffix
550        $domains[''] = ltrim($this->conf['account_suffix'], '@');
551
552        // find additional domains
553        foreach($this->conf as $key => $val) {
554            if(is_array($val) && isset($val['account_suffix'])) {
555                $domains[$key] = ltrim($val['account_suffix'], '@');
556            }
557        }
558        ksort($domains);
559
560        return $domains;
561    }
562
563    /**
564     * Check provided user and userinfo for matching patterns
565     *
566     * The patterns are set up with $this->_constructPattern()
567     *
568     * @author Chris Smith <chris@jalakai.co.uk>
569     *
570     * @param string $user
571     * @param array  $info
572     * @return bool
573     */
574    protected function _filter($user, $info) {
575        foreach($this->_pattern as $item => $pattern) {
576            if($item == 'user') {
577                if(!preg_match($pattern, $user)) return false;
578            } else if($item == 'grps') {
579                if(!count(preg_grep($pattern, $info['grps']))) return false;
580            } else {
581                if(!preg_match($pattern, $info[$item])) return false;
582            }
583        }
584        return true;
585    }
586
587    /**
588     * Create a pattern for $this->_filter()
589     *
590     * @author Chris Smith <chris@jalakai.co.uk>
591     *
592     * @param array $filter
593     */
594    protected function _constructPattern($filter) {
595        $this->_pattern = array();
596        foreach($filter as $item => $pattern) {
597            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
598        }
599    }
600}
601