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