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