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