xref: /dokuwiki/lib/plugins/authad/auth.php (revision 42ea7f447f39fbc2f79eaaec31f8c10ede59c5d0)
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     * @param   int   $start     index of first user to be returned
333     * @param   int   $limit     max number of users to be returned
334     * @param   array $filter    array of field/pattern pairs, null for no filter
335     * @return  array userinfo (refer getUserData for internal userinfo details)
336     */
337    public function retrieveUsers($start = 0, $limit = 0, $filter = array()) {
338        $adldap = $this->_adldap(null);
339        if(!$adldap) return false;
340
341        if(!$this->users) {
342            //get info for given user
343            $result = $adldap->user()->all();
344            if (!$result) return array();
345            $this->users = array_fill_keys($result, false);
346        }
347
348        $i     = 0;
349        $count = 0;
350        $this->_constructPattern($filter);
351        $result = array();
352
353        foreach($this->users as $user => &$info) {
354            if($i++ < $start) {
355                continue;
356            }
357            if($info === false) {
358                $info = $this->getUserData($user);
359            }
360            if($this->_filter($user, $info)) {
361                $result[$user] = $info;
362                if(($limit > 0) && (++$count >= $limit)) break;
363            }
364        }
365        return $result;
366    }
367
368    /**
369     * Modify user data
370     *
371     * @param   string $user      nick of the user to be changed
372     * @param   array  $changes   array of field/value pairs to be changed
373     * @return  bool
374     */
375    public function modifyUser($user, $changes) {
376        $return = true;
377        $adldap = $this->_adldap($this->_userDomain($user));
378        if(!$adldap) return false;
379
380        // password changing
381        if(isset($changes['pass'])) {
382            try {
383                $return = $adldap->user()->password($this->_userName($user),$changes['pass']);
384            } catch (adLDAPException $e) {
385                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
386                $return = false;
387            }
388            if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1);
389        }
390
391        // changing user data
392        $adchanges = array();
393        if(isset($changes['name'])) {
394            // get first and last name
395            $parts                     = explode(' ', $changes['name']);
396            $adchanges['surname']      = array_pop($parts);
397            $adchanges['firstname']    = join(' ', $parts);
398            $adchanges['display_name'] = $changes['name'];
399        }
400        if(isset($changes['mail'])) {
401            $adchanges['email'] = $changes['mail'];
402        }
403        if(count($adchanges)) {
404            try {
405                $return = $return & $adldap->user()->modify($this->_userName($user),$adchanges);
406            } catch (adLDAPException $e) {
407                if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
408                $return = false;
409            }
410        }
411
412        return $return;
413    }
414
415    /**
416     * Initialize the AdLDAP library and connect to the server
417     *
418     * When you pass null as domain, it will reuse any existing domain.
419     * Eg. the one of the logged in user. It falls back to the default
420     * domain if no current one is available.
421     *
422     * @param string|null $domain The AD domain to use
423     * @return adLDAP|bool true if a connection was established
424     */
425    protected function _adldap($domain) {
426        if(is_null($domain) && is_array($this->opts)) {
427            $domain = $this->opts['domain'];
428        }
429
430        $this->opts = $this->_loadServerConfig((string) $domain);
431        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
432
433        // connect
434        try {
435            $this->adldap[$domain] = new adLDAP($this->opts);
436            return $this->adldap[$domain];
437        } catch(adLDAPException $e) {
438            if($this->conf['debug']) {
439                msg('AD Auth: '.$e->getMessage(), -1);
440            }
441            $this->success         = false;
442            $this->adldap[$domain] = null;
443        }
444        return false;
445    }
446
447    /**
448     * Get the domain part from a user
449     *
450     * @param $user
451     * @return string
452     */
453    public function _userDomain($user) {
454        list(, $domain) = explode('@', $user, 2);
455        return $domain;
456    }
457
458    /**
459     * Get the user part from a user
460     *
461     * @param $user
462     * @return string
463     */
464    public function _userName($user) {
465        list($name) = explode('@', $user, 2);
466        return $name;
467    }
468
469    /**
470     * Fetch the configuration for the given AD domain
471     *
472     * @param string $domain current AD domain
473     * @return array
474     */
475    protected function _loadServerConfig($domain) {
476        // prepare adLDAP standard configuration
477        $opts = $this->conf;
478
479        $opts['domain'] = $domain;
480
481        // add possible domain specific configuration
482        if($domain && is_array($this->conf[$domain])) foreach($this->conf[$domain] as $key => $val) {
483            $opts[$key] = $val;
484        }
485
486        // handle multiple AD servers
487        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
488        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
489        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
490
491        // compatibility with old option name
492        if(empty($opts['admin_username']) && !empty($opts['ad_username'])) $opts['admin_username'] = $opts['ad_username'];
493        if(empty($opts['admin_password']) && !empty($opts['ad_password'])) $opts['admin_password'] = $opts['ad_password'];
494
495        // we can change the password if SSL is set
496        if($opts['use_ssl'] || $opts['use_tls']) {
497            $this->cando['modPass'] = true;
498        } else {
499            $this->cando['modPass'] = false;
500        }
501
502        // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
503        if(empty($opts['admin_username'])) $opts['admin_username'] = null;
504        if(empty($opts['admin_password'])) $opts['admin_password'] = null;
505
506        // user listing needs admin priviledges
507        if(!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
508            $this->cando['getUsers'] = true;
509        } else {
510            $this->cando['getUsers'] = false;
511        }
512
513        return $opts;
514    }
515
516    /**
517     * Returns a list of configured domains
518     *
519     * The default domain has an empty string as key
520     *
521     * @return array associative array(key => domain)
522     */
523    public function _getConfiguredDomains() {
524        $domains = array();
525        if(empty($this->conf['account_suffix'])) return $domains; // not configured yet
526
527        // add default domain, using the name from account suffix
528        $domains[''] = ltrim($this->conf['account_suffix'], '@');
529
530        // find additional domains
531        foreach($this->conf as $key => $val) {
532            if(is_array($val) && isset($val['account_suffix'])) {
533                $domains[$key] = ltrim($val['account_suffix'], '@');
534            }
535        }
536        ksort($domains);
537
538        return $domains;
539    }
540
541    /**
542     * Check provided user and userinfo for matching patterns
543     *
544     * The patterns are set up with $this->_constructPattern()
545     *
546     * @author Chris Smith <chris@jalakai.co.uk>
547     * @param string $user
548     * @param array  $info
549     * @return bool
550     */
551    protected function _filter($user, $info) {
552        foreach($this->_pattern as $item => $pattern) {
553            if($item == 'user') {
554                if(!preg_match($pattern, $user)) return false;
555            } else if($item == 'grps') {
556                if(!count(preg_grep($pattern, $info['grps']))) return false;
557            } else {
558                if(!preg_match($pattern, $info[$item])) return false;
559            }
560        }
561        return true;
562    }
563
564    /**
565     * Create a pattern for $this->_filter()
566     *
567     * @author Chris Smith <chris@jalakai.co.uk>
568     * @param array $filter
569     */
570    protected function _constructPattern($filter) {
571        $this->_pattern = array();
572        foreach($filter as $item => $pattern) {
573            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
574        }
575    }
576}
577