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