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