xref: /dokuwiki/lib/plugins/authad/auth.php (revision 454d868b911059adb8889a2d6afefa016d6a21f5)
1<?php
2// must be run within Dokuwiki
3if(!defined('DOKU_INC')) die();
4
5require_once(DOKU_INC.'inc/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['useacl']         = 1;
17 *   $conf['disableactions'] = 'register';
18 *   $conf['autopasswd']     = 0;
19 *   $conf['authtype']       = 'authad';
20 *   $conf['passcrypt']      = 'ssha';
21 *
22 *   $conf['auth']['ad']['account_suffix']     = '
23 *
24 * @my.domain.org';
25 *   $conf['auth']['ad']['base_dn']            = 'DC=my,DC=domain,DC=org';
26 *   $conf['auth']['ad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
27 *
28 *   //optional:
29 *   $conf['auth']['ad']['sso']                = 1;
30 *   $conf['auth']['ad']['ad_username']        = 'root';
31 *   $conf['auth']['ad']['ad_password']        = 'pass';
32 *   $conf['auth']['ad']['real_primarygroup']  = 1;
33 *   $conf['auth']['ad']['use_ssl']            = 1;
34 *   $conf['auth']['ad']['use_tls']            = 1;
35 *   $conf['auth']['ad']['debug']              = 1;
36 *   // warn user about expiring password this many days in advance:
37 *   $conf['auth']['ad']['expirywarn']         = 5;
38 *
39 *   // get additional information to the userinfo array
40 *   // add a list of comma separated ldap contact fields.
41 *   $conf['plugin']['authad']['additional'] = 'field1,field2';
42 *
43 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
44 * @author  James Van Lommel <jamesvl@gmail.com>
45 * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
46 * @author  Andreas Gohr <andi@splitbrain.org>
47 * @author  Jan Schumann <js@schumann-it.com>
48 */
49
50require_once(DOKU_INC.'inc/adLDAP/adLDAP.php');
51
52class auth_plugin_authad extends DokuWiki_Auth_Plugin {
53    /**
54     * @var array copy of the auth backend configuration
55     */
56    protected $cnf = array();
57    /**
58     * @var array hold connection data for a specific AD domain
59     */
60    protected $opts = array();
61    /**
62     * @var array open connections for each AD domain, as adLDAP objects
63     */
64    protected $adldap = array();
65
66    /**
67     * @var bool message state
68     */
69    protected $msgshown = false;
70
71    /**
72     * @var array user listing cache
73     */
74    protected $users = array();
75
76    /**
77     * @var array filter patterns for listing users
78     */
79    protected $_pattern = array();
80
81    /**
82     * Constructor
83     */
84    public function __construct() {
85        parent::__construct();
86
87        global $conf;
88        $this->cnf = $conf['auth']['ad'];
89
90        // additional information fields
91        if(isset($this->cnf['additional'])) {
92            $this->cnf['additional'] = str_replace(' ', '', $this->cnf['additional']);
93            $this->cnf['additional'] = explode(',', $this->cnf['additional']);
94        } else $this->cnf['additional'] = array();
95
96        // ldap extension is needed
97        if(!function_exists('ldap_connect')) {
98            if($this->cnf['debug'])
99                msg("AD Auth: PHP LDAP extension not found.", -1);
100            $this->success = false;
101            return;
102        }
103
104        // Prepare SSO
105        if(!utf8_check($_SERVER['REMOTE_USER'])) {
106            $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
107        }
108        if($_SERVER['REMOTE_USER'] && $this->cnf['sso']) {
109            $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
110
111            // we need to simulate a login
112            if(empty($_COOKIE[DOKU_COOKIE])) {
113                $_REQUEST['u'] = $_SERVER['REMOTE_USER'];
114                $_REQUEST['p'] = 'sso_only';
115            }
116        }
117
118        // other can do's are changed in $this->_loadServerConfig() base on domain setup
119        $this->cando['modName'] = true;
120        $this->cando['modMail'] = true;
121    }
122
123    /**
124     * Check user+password [required auth function]
125     *
126     * Checks if the given user exists and the given
127     * plaintext password is correct by trying to bind
128     * to the LDAP server
129     *
130     * @author  James Van Lommel <james@nosq.com>
131     * @param string $user
132     * @param string $pass
133     * @return  bool
134     */
135    public function checkPass($user, $pass) {
136        if($_SERVER['REMOTE_USER'] &&
137            $_SERVER['REMOTE_USER'] == $user &&
138            $this->cnf['sso']
139        ) return true;
140
141        $adldap = $this->_adldap($this->_userDomain($user));
142        if(!$adldap) return false;
143
144        return $adldap->authenticate($this->_userName($user), $pass);
145    }
146
147    /**
148     * Return user info [required auth function]
149     *
150     * Returns info about the given user needs to contain
151     * at least these fields:
152     *
153     * name    string  full name of the user
154     * mail    string  email address of the user
155     * grps    array   list of groups the user is in
156     *
157     * This AD specific function returns the following
158     * addional fields:
159     *
160     * dn         string    distinguished name (DN)
161     * uid        string    samaccountname
162     * lastpwd    int       timestamp of the date when the password was set
163     * expires    true      if the password expires
164     * expiresin  int       seconds until the password expires
165     * any fields specified in the 'additional' config option
166     *
167     * @author  James Van Lommel <james@nosq.com>
168     * @param string $user
169     * @return array
170     */
171    public function getUserData($user) {
172        global $conf;
173        global $lang;
174        global $ID;
175        $adldap = $this->_adldap($this->_userDomain($user));
176        if(!$adldap) return false;
177
178        if($user == '') return array();
179
180        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
181
182        // add additional fields to read
183        $fields = array_merge($fields, $this->cnf['additional']);
184        $fields = array_unique($fields);
185
186        //get info for given user
187        $result = $this->adldap->user()->info($this->_userName($user), $fields);
188        if($result == false){
189            return array();
190        }
191
192        //general user info
193        $info['name'] = $result[0]['displayname'][0];
194        $info['mail'] = $result[0]['mail'][0];
195        $info['uid']  = $result[0]['samaccountname'][0];
196        $info['dn']   = $result[0]['dn'];
197        //last password set (Windows counts from January 1st 1601)
198        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
199        //will it expire?
200        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
201
202        // additional information
203        foreach($this->cnf['additional'] as $field) {
204            if(isset($result[0][strtolower($field)])) {
205                $info[$field] = $result[0][strtolower($field)][0];
206            }
207        }
208
209        // handle ActiveDirectory memberOf
210        $info['grps'] = $this->adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']);
211
212        if(is_array($info['grps'])) {
213            foreach($info['grps'] as $ndx => $group) {
214                $info['grps'][$ndx] = $this->cleanGroup($group);
215            }
216        }
217
218        // always add the default group to the list of groups
219        if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
220            $info['grps'][] = $conf['defaultgroup'];
221        }
222
223        // add the user's domain to the groups
224        $domain = $this->_userDomain($user);
225        if($domain && !in_array("domain-$domain", (array) $info['grps'])) {
226            $info['grps'][] = $this->cleanGroup("domain-$domain");
227        }
228
229        // check expiry time
230        if($info['expires'] && $this->cnf['expirywarn']){
231            $timeleft = $this->adldap->user()->passwordExpiry($user); // returns unixtime
232            $timeleft = round($timeleft/(24*60*60));
233            $info['expiresin'] = $timeleft;
234
235            // if this is the current user, warn him (once per request only)
236            if(($_SERVER['REMOTE_USER'] == $user) &&
237                ($timeleft <= $this->cnf['expirywarn']) &&
238                !$this->msgshown
239            ) {
240                $msg = sprintf($lang['authpwdexpire'], $timeleft);
241                if($this->canDo('modPass')) {
242                    $url = wl($ID, array('do'=> 'profile'));
243                    $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
244                }
245                msg($msg);
246                $this->msgshown = true;
247            }
248        }
249
250        return $info;
251    }
252
253    /**
254     * Make AD group names usable by DokuWiki.
255     *
256     * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
257     *
258     * @author  James Van Lommel (jamesvl@gmail.com)
259     * @param string $group
260     * @return string
261     */
262    public function cleanGroup($group) {
263        $group = str_replace('\\', '', $group);
264        $group = str_replace('#', '', $group);
265        $group = preg_replace('[\s]', '_', $group);
266        $group = utf8_strtolower(trim($group));
267        return $group;
268    }
269
270    /**
271     * Sanitize user names
272     *
273     * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
274     *
275     * @author Andreas Gohr <gohr@cosmocode.de>
276     * @param string $user
277     * @return string
278     */
279    public function cleanUser($user) {
280        $domain = '';
281
282        // get NTLM or Kerberos domain part
283        list($dom, $user) = explode('\\', $user, 2);
284        if(!$user) $user = $dom;
285        if($dom) $domain = $dom;
286        list($user, $dom) = explode('@', $user, 2);
287        if($dom) $domain = $dom;
288
289        // clean up both
290        $domain = utf8_strtolower(trim($domain));
291        $user   = utf8_strtolower(trim($user));
292
293        // is this a known, valid domain? if not discard
294        if(!is_array($this->cnf[$domain])) {
295            $domain = '';
296        }
297
298        // reattach domain
299        if($domain) $user = "$user@$domain";
300        return $user;
301    }
302
303    /**
304     * Most values in LDAP are case-insensitive
305     *
306     * @return bool
307     */
308    public function isCaseSensitive() {
309        return false;
310    }
311
312    /**
313     * Bulk retrieval of user data
314     *
315     * @author  Dominik Eckelmann <dokuwiki@cosmocode.de>
316     * @param   int   $start     index of first user to be returned
317     * @param   int   $limit     max number of users to be returned
318     * @param   array $filter    array of field/pattern pairs, null for no filter
319     * @return  array userinfo (refer getUserData for internal userinfo details)
320     */
321    public function retrieveUsers($start = 0, $limit = -1, $filter = array()) {
322        $adldap = $this->_adldap(null);
323        if(!$adldap) return false;
324
325        if($this->users === null) {
326            //get info for given user
327            $result = $this->adldap->user()->all();
328            if (!$result) return array();
329            $this->users = array_fill_keys($result, false);
330        }
331
332        $i     = 0;
333        $count = 0;
334        $this->_constructPattern($filter);
335        $result = array();
336
337        foreach($this->users as $user => &$info) {
338            if($i++ < $start) {
339                continue;
340            }
341            if($info === false) {
342                $info = $this->getUserData($user);
343            }
344            if($this->_filter($user, $info)) {
345                $result[$user] = $info;
346                if(($limit >= 0) && (++$count >= $limit)) break;
347            }
348        }
349        return $result;
350    }
351
352    /**
353     * Modify user data
354     *
355     * @param   string $user      nick of the user to be changed
356     * @param   array  $changes   array of field/value pairs to be changed
357     * @return  bool
358     */
359    public function modifyUser($user, $changes) {
360        $return = true;
361        $adldap = $this->_adldap($this->_userDomain($user));
362        if(!$adldap) return false;
363
364        // password changing
365        if(isset($changes['pass'])) {
366            try {
367                $return = $this->adldap->user()->password($this->_userName($user),$changes['pass']);
368            } catch (adLDAPException $e) {
369                if ($this->cnf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
370                $return = false;
371            }
372            if(!$return) msg('AD Auth: failed to change the password. Maybe the password policy was not met?', -1);
373        }
374
375        // changing user data
376        $adchanges = array();
377        if(isset($changes['name'])) {
378            // get first and last name
379            $parts                     = explode(' ', $changes['name']);
380            $adchanges['surname']      = array_pop($parts);
381            $adchanges['firstname']    = join(' ', $parts);
382            $adchanges['display_name'] = $changes['name'];
383        }
384        if(isset($changes['mail'])) {
385            $adchanges['email'] = $changes['mail'];
386        }
387        if(count($adchanges)) {
388            try {
389                $return = $return & $this->adldap->user()->modify($this->_userName($user),$adchanges);
390            } catch (adLDAPException $e) {
391                if ($this->cnf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
392                $return = false;
393            }
394        }
395
396        return $return;
397    }
398
399    /**
400     * Initialize the AdLDAP library and connect to the server
401     *
402     * When you pass null as domain, it will reuse any existing domain.
403     * Eg. the one of the logged in user. It falls back to the default
404     * domain if no current one is available.
405     *
406     * @param string|null $domain The AD domain to use
407     * @return adLDAP|bool true if a connection was established
408     */
409    protected function _adldap($domain) {
410        if(is_null($domain) && is_array($this->opts)) {
411            $domain = $this->opts['domain'];
412        }
413
414        $this->opts = $this->_loadServerConfig((string) $domain);
415        if(isset($this->adldap[$domain])) return $this->adldap[$domain];
416
417        // connect
418        try {
419            $this->adldap[$domain] = new adLDAP($this->opts);
420            return $this->adldap[$domain];
421        } catch(adLDAPException $e) {
422            if($this->cnf['debug']) {
423                msg('AD Auth: '.$e->getMessage(), -1);
424            }
425            $this->success         = false;
426            $this->adldap[$domain] = null;
427        }
428        return false;
429    }
430
431    /**
432     * Get the domain part from a user
433     *
434     * @param $user
435     * @return string
436     */
437    public function _userDomain($user) {
438        list(, $domain) = explode('@', $user, 2);
439        return $domain;
440    }
441
442    /**
443     * Get the user part from a user
444     *
445     * @param $user
446     * @return string
447     */
448    public function _userName($user) {
449        list($name) = explode('@', $user, 2);
450        return $name;
451    }
452
453    /**
454     * Fetch the configuration for the given AD domain
455     *
456     * @param string $domain current AD domain
457     * @return array
458     */
459    protected function _loadServerConfig($domain) {
460        // prepare adLDAP standard configuration
461        $opts = $this->cnf;
462
463        $opts['domain'] = $domain;
464
465        // add possible domain specific configuration
466        if($domain && is_array($this->cnf[$domain])) foreach($this->cnf[$domain] as $key => $val) {
467            $opts[$key] = $val;
468        }
469
470        // handle multiple AD servers
471        $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
472        $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
473        $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
474
475        // we can change the password if SSL is set
476        if($opts['use_ssl'] || $opts['use_tls']) {
477            $this->cando['modPass'] = true;
478        } else {
479            $this->cando['modPass'] = false;
480        }
481
482        if(isset($opts['ad_username']) && isset($opts['ad_password'])) {
483            $this->cando['getUsers'] = true;
484        } else {
485            $this->cando['getUsers'] = true;
486        }
487
488        return $opts;
489    }
490
491    /**
492     * Check provided user and userinfo for matching patterns
493     *
494     * The patterns are set up with $this->_constructPattern()
495     *
496     * @author Chris Smith <chris@jalakai.co.uk>
497     * @param string $user
498     * @param array  $info
499     * @return bool
500     */
501    protected function _filter($user, $info) {
502        foreach($this->_pattern as $item => $pattern) {
503            if($item == 'user') {
504                if(!preg_match($pattern, $user)) return false;
505            } else if($item == 'grps') {
506                if(!count(preg_grep($pattern, $info['grps']))) return false;
507            } else {
508                if(!preg_match($pattern, $info[$item])) return false;
509            }
510        }
511        return true;
512    }
513
514    /**
515     * Create a pattern for $this->_filter()
516     *
517     * @author Chris Smith <chris@jalakai.co.uk>
518     * @param array $filter
519     */
520    protected function _constructPattern($filter) {
521        $this->_pattern = array();
522        foreach($filter as $item => $pattern) {
523            $this->_pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters
524        }
525    }
526}
527