xref: /dokuwiki/lib/plugins/authad/auth.php (revision 76ce1169a0c8cbb18423b1581800b9aa1050ccd5)
1<?php
2// must be run within Dokuwiki
3if(!defined('DOKU_INC')) die();
4
5/**
6 * Active Directory authentication backend for DokuWiki
7 *
8 * This makes authentication with a Active Directory server much easier
9 * than when using the normal LDAP backend by utilizing the adLDAP library
10 *
11 * Usage:
12 *   Set DokuWiki's local.protected.php auth setting to read
13 *
14 *   $conf['authtype']       = 'authad';
15 *
16 *   $conf['auth']['ad']['account_suffix']     = '@my.domain.org';
17 *   $conf['auth']['ad']['base_dn']            = 'DC=my,DC=domain,DC=org';
18 *   $conf['auth']['ad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
19 *
20 *   //optional:
21 *   $conf['auth']['ad']['sso']                = 1;
22 *   $conf['auth']['ad']['ad_username']        = 'root';
23 *   $conf['auth']['ad']['ad_password']        = 'pass';
24 *   $conf['auth']['ad']['real_primarygroup']  = 1;
25 *   $conf['auth']['ad']['use_ssl']            = 1;
26 *   $conf['auth']['ad']['use_tls']            = 1;
27 *   $conf['auth']['ad']['debug']              = 1;
28 *   // warn user about expiring password this many days in advance:
29 *   $conf['auth']['ad']['expirywarn']         = 5;
30 *
31 *   // get additional information to the userinfo array
32 *   // add a list of comma separated ldap contact fields.
33 *   $conf['plugin']['authad']['additional'] = 'field1,field2';
34 *
35 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
36 * @author  James Van Lommel <jamesvl@gmail.com>
37 * @link    http://www.nosq.com/blog/2005/08/ldap-activedirectory-and-dokuwiki/
38 * @author  Andreas Gohr <andi@splitbrain.org>
39 * @author  Jan Schumann <js@schumann-it.com>
40 */
41
42require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
43
44class auth_plugin_authad extends DokuWiki_Auth_Plugin {
45    /**
46     * @var array copy of the auth backend configuration
47     */
48    protected $cnf = array();
49    /**
50     * @var array hold connection data for a specific AD domain
51     */
52    protected $opts = array();
53    /**
54     * @var array open connections for each AD domain, as adLDAP objects
55     */
56    protected $adldap = array();
57
58    /**
59     * @var bool message state
60     */
61    protected $msgshown = false;
62
63    /**
64     * @var array user listing cache
65     */
66    protected $users = array();
67
68    /**
69     * @var array filter patterns for listing users
70     */
71    protected $_pattern = array();
72
73    /**
74     * Constructor
75     */
76    public function __construct() {
77        parent::__construct();
78
79        global $conf;
80        $this->cnf = $conf['auth']['ad'];
81
82        // additional information fields
83        if(isset($this->cnf['additional'])) {
84            $this->cnf['additional'] = str_replace(' ', '', $this->cnf['additional']);
85            $this->cnf['additional'] = explode(',', $this->cnf['additional']);
86        } else $this->cnf['additional'] = array();
87
88        // ldap extension is needed
89        if(!function_exists('ldap_connect')) {
90            if($this->cnf['debug'])
91                msg("AD Auth: PHP LDAP extension not found.", -1);
92            $this->success = false;
93            return;
94        }
95
96        // Prepare SSO
97        if(!utf8_check($_SERVER['REMOTE_USER'])) {
98            $_SERVER['REMOTE_USER'] = utf8_encode($_SERVER['REMOTE_USER']);
99        }
100        if($_SERVER['REMOTE_USER'] && $this->cnf['sso']) {
101            $_SERVER['REMOTE_USER'] = $this->cleanUser($_SERVER['REMOTE_USER']);
102
103            // we need to simulate a login
104            if(empty($_COOKIE[DOKU_COOKIE])) {
105                $_REQUEST['u'] = $_SERVER['REMOTE_USER'];
106                $_REQUEST['p'] = 'sso_only';
107            }
108        }
109
110        // other can do's are changed in $this->_loadServerConfig() base on domain setup
111        $this->cando['modName'] = true;
112        $this->cando['modMail'] = true;
113    }
114
115    /**
116     * Check user+password [required auth function]
117     *
118     * Checks if the given user exists and the given
119     * plaintext password is correct by trying to bind
120     * to the LDAP server
121     *
122     * @author  James Van Lommel <james@nosq.com>
123     * @param string $user
124     * @param string $pass
125     * @return  bool
126     */
127    public function checkPass($user, $pass) {
128        if($_SERVER['REMOTE_USER'] &&
129            $_SERVER['REMOTE_USER'] == $user &&
130            $this->cnf['sso']
131        ) return true;
132
133        $adldap = $this->_adldap($this->_userDomain($user));
134        if(!$adldap) return false;
135
136        return $adldap->authenticate($this->_userName($user), $pass);
137    }
138
139    /**
140     * Return user info [required auth function]
141     *
142     * Returns info about the given user needs to contain
143     * at least these fields:
144     *
145     * name    string  full name of the user
146     * mail    string  email address of the user
147     * grps    array   list of groups the user is in
148     *
149     * This AD specific function returns the following
150     * addional fields:
151     *
152     * dn         string    distinguished name (DN)
153     * uid        string    samaccountname
154     * lastpwd    int       timestamp of the date when the password was set
155     * expires    true      if the password expires
156     * expiresin  int       seconds until the password expires
157     * any fields specified in the 'additional' config option
158     *
159     * @author  James Van Lommel <james@nosq.com>
160     * @param string $user
161     * @return array
162     */
163    public function getUserData($user) {
164        global $conf;
165        global $lang;
166        global $ID;
167        $adldap = $this->_adldap($this->_userDomain($user));
168        if(!$adldap) return false;
169
170        if($user == '') return array();
171
172        $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
173
174        // add additional fields to read
175        $fields = array_merge($fields, $this->cnf['additional']);
176        $fields = array_unique($fields);
177
178        //get info for given user
179        $result = $this->adldap->user()->info($this->_userName($user), $fields);
180        if($result == false){
181            return array();
182        }
183
184        //general user info
185        $info['name'] = $result[0]['displayname'][0];
186        $info['mail'] = $result[0]['mail'][0];
187        $info['uid']  = $result[0]['samaccountname'][0];
188        $info['dn']   = $result[0]['dn'];
189        //last password set (Windows counts from January 1st 1601)
190        $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
191        //will it expire?
192        $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
193
194        // additional information
195        foreach($this->cnf['additional'] as $field) {
196            if(isset($result[0][strtolower($field)])) {
197                $info[$field] = $result[0][strtolower($field)][0];
198            }
199        }
200
201        // handle ActiveDirectory memberOf
202        $info['grps'] = $this->adldap->user()->groups($this->_userName($user),(bool) $this->opts['recursive_groups']);
203
204        if(is_array($info['grps'])) {
205            foreach($info['grps'] as $ndx => $group) {
206                $info['grps'][$ndx] = $this->cleanGroup($group);
207            }
208        }
209
210        // always add the default group to the list of groups
211        if(!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
212            $info['grps'][] = $conf['defaultgroup'];
213        }
214
215        // add the user's domain to the groups
216        $domain = $this->_userDomain($user);
217        if($domain && !in_array("domain-$domain", (array) $info['grps'])) {
218            $info['grps'][] = $this->cleanGroup("domain-$domain");
219        }
220
221        // check expiry time
222        if($info['expires'] && $this->cnf['expirywarn']){
223            $timeleft = $this->adldap->user()->passwordExpiry($user); // returns unixtime
224            $timeleft = round($timeleft/(24*60*60));
225            $info['expiresin'] = $timeleft;
226
227            // if this is the current user, warn him (once per request only)
228            if(($_SERVER['REMOTE_USER'] == $user) &&
229                ($timeleft <= $this->cnf['expirywarn']) &&
230                !$this->msgshown
231            ) {
232                $msg = sprintf($lang['authpwdexpire'], $timeleft);
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        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->cnf[$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 = $this->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 = $this->adldap->user()->password($this->_userName($user),$changes['pass']);
360            } catch (adLDAPException $e) {
361                if ($this->cnf['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 & $this->adldap->user()->modify($this->_userName($user),$adchanges);
382            } catch (adLDAPException $e) {
383                if ($this->cnf['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->cnf['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->cnf;
454
455        $opts['domain'] = $domain;
456
457        // add possible domain specific configuration
458        if($domain && is_array($this->cnf[$domain])) foreach($this->cnf[$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['ad_username']) && isset($opts['ad_password'])) {
475            $this->cando['getUsers'] = true;
476        } else {
477            $this->cando['getUsers'] = true;
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