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