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