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