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