Replace direct access to $_SERVER with $INPUT->server->…
[dokuwiki.git] / lib / plugins / authad / auth.php
blobb5447e8d960714ede358d377fc1d01a1a193aadc
1 <?php
2 use dokuwiki\Utf8\Sort;
3 use dokuwiki\Logger;
5 /**
6 * Active Directory authentication backend for DokuWiki
8 * This makes authentication with a Active Directory server much easier
9 * than when using the normal LDAP backend by utilizing the adLDAP library
11 * Usage:
12 * Set DokuWiki's local.protected.php auth setting to read
14 * $conf['authtype'] = 'authad';
16 * $conf['plugin']['authad']['account_suffix'] = '@my.domain.org';
17 * $conf['plugin']['authad']['base_dn'] = 'DC=my,DC=domain,DC=org';
18 * $conf['plugin']['authad']['domain_controllers'] = 'srv1.domain.org,srv2.domain.org';
20 * //optional:
21 * $conf['plugin']['authad']['sso'] = 1;
22 * $conf['plugin']['authad']['admin_username'] = 'root';
23 * $conf['plugin']['authad']['admin_password'] = 'pass';
24 * $conf['plugin']['authad']['real_primarygroup'] = 1;
25 * $conf['plugin']['authad']['use_ssl'] = 1;
26 * $conf['plugin']['authad']['use_tls'] = 1;
27 * $conf['plugin']['authad']['debug'] = 1;
28 * // warn user about expiring password this many days in advance:
29 * $conf['plugin']['authad']['expirywarn'] = 5;
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';
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>
41 class auth_plugin_authad extends DokuWiki_Auth_Plugin
44 /**
45 * @var array hold connection data for a specific AD domain
47 protected $opts = array();
49 /**
50 * @var array open connections for each AD domain, as adLDAP objects
52 protected $adldap = array();
54 /**
55 * @var bool message state
57 protected $msgshown = false;
59 /**
60 * @var array user listing cache
62 protected $users = array();
64 /**
65 * @var array filter patterns for listing users
67 protected $pattern = array();
69 protected $grpsusers = array();
71 /**
72 * Constructor
74 public function __construct()
76 global $INPUT;
77 parent::__construct();
79 require_once(DOKU_PLUGIN.'authad/adLDAP/adLDAP.php');
80 require_once(DOKU_PLUGIN.'authad/adLDAP/classes/adLDAPUtils.php');
82 // we load the config early to modify it a bit here
83 $this->loadConfig();
85 // additional information fields
86 if (isset($this->conf['additional'])) {
87 $this->conf['additional'] = str_replace(' ', '', $this->conf['additional']);
88 $this->conf['additional'] = explode(',', $this->conf['additional']);
89 } else $this->conf['additional'] = array();
91 // ldap extension is needed
92 if (!function_exists('ldap_connect')) {
93 if ($this->conf['debug'])
94 msg("AD Auth: PHP LDAP extension not found.", -1);
95 $this->success = false;
96 return;
99 // Prepare SSO
100 if (!empty($INPUT->server->str('REMOTE_USER'))) {
101 // make sure the right encoding is used
102 if ($this->getConf('sso_charset')) {
103 $INPUT->server->set('REMOTE_USER', iconv($this->getConf('sso_charset'), 'UTF-8', $INPUT->server->str('REMOTE_USER')));
104 } elseif (!\dokuwiki\Utf8\Clean::isUtf8($INPUT->server->str('REMOTE_USER'))) {
105 $INPUT->server->set('REMOTE_USER', utf8_encode($INPUT->server->str('REMOTE_USER')));
108 // trust the incoming user
109 if ($this->conf['sso']) {
110 $INPUT->server->set('REMOTE_USER', $this->cleanUser($INPUT->server->str('REMOTE_USER')));
112 // we need to simulate a login
113 if (empty($_COOKIE[DOKU_COOKIE])) {
114 $INPUT->set('u', $INPUT->server->str('REMOTE_USER'));
115 $INPUT->set('p', 'sso_only');
120 // other can do's are changed in $this->_loadServerConfig() base on domain setup
121 $this->cando['modName'] = (bool)$this->conf['update_name'];
122 $this->cando['modMail'] = (bool)$this->conf['update_mail'];
123 $this->cando['getUserCount'] = true;
127 * Load domain config on capability check
129 * @param string $cap
130 * @return bool
132 public function canDo($cap)
134 global $INPUT;
135 //capabilities depend on config, which may change depending on domain
136 $domain = $this->getUserDomain($INPUT->server->str('REMOTE_USER'));
137 $this->loadServerConfig($domain);
138 return parent::canDo($cap);
142 * Check user+password [required auth function]
144 * Checks if the given user exists and the given
145 * plaintext password is correct by trying to bind
146 * to the LDAP server
148 * @author James Van Lommel <james@nosq.com>
149 * @param string $user
150 * @param string $pass
151 * @return bool
153 public function checkPass($user, $pass)
155 global $INPUT;
156 if ($INPUT->server->str('REMOTE_USER') == $user &&
157 $this->conf['sso']
158 ) return true;
160 $adldap = $this->initAdLdap($this->getUserDomain($user));
161 if (!$adldap) return false;
163 try {
164 return $adldap->authenticate($this->getUserName($user), $pass);
165 } catch (adLDAPException $e) {
166 // shouldn't really happen
167 return false;
172 * Return user info [required auth function]
174 * Returns info about the given user needs to contain
175 * at least these fields:
177 * name string full name of the user
178 * mail string email address of the user
179 * grps array list of groups the user is in
181 * This AD specific function returns the following
182 * addional fields:
184 * dn string distinguished name (DN)
185 * uid string samaccountname
186 * lastpwd int timestamp of the date when the password was set
187 * expires true if the password expires
188 * expiresin int seconds until the password expires
189 * any fields specified in the 'additional' config option
191 * @author James Van Lommel <james@nosq.com>
192 * @param string $user
193 * @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
194 * @return array
196 public function getUserData($user, $requireGroups = true)
198 global $conf;
199 global $lang;
200 global $ID;
201 global $INPUT;
202 $adldap = $this->initAdLdap($this->getUserDomain($user));
203 if (!$adldap) return array();
205 if ($user == '') return array();
207 $fields = array('mail', 'displayname', 'samaccountname', 'lastpwd', 'pwdlastset', 'useraccountcontrol');
209 // add additional fields to read
210 $fields = array_merge($fields, $this->conf['additional']);
211 $fields = array_unique($fields);
212 $fields = array_filter($fields);
214 //get info for given user
215 $result = $adldap->user()->info($this->getUserName($user), $fields);
216 if ($result == false) {
217 return array();
220 //general user info
221 $info = array();
222 $info['name'] = $result[0]['displayname'][0];
223 $info['mail'] = $result[0]['mail'][0];
224 $info['uid'] = $result[0]['samaccountname'][0];
225 $info['dn'] = $result[0]['dn'];
226 //last password set (Windows counts from January 1st 1601)
227 $info['lastpwd'] = $result[0]['pwdlastset'][0] / 10000000 - 11644473600;
228 //will it expire?
229 $info['expires'] = !($result[0]['useraccountcontrol'][0] & 0x10000); //ADS_UF_DONT_EXPIRE_PASSWD
231 // additional information
232 foreach ($this->conf['additional'] as $field) {
233 if (isset($result[0][strtolower($field)])) {
234 $info[$field] = $result[0][strtolower($field)][0];
238 // handle ActiveDirectory memberOf
239 $info['grps'] = $adldap->user()->groups($this->getUserName($user), (bool) $this->opts['recursive_groups']);
241 if (is_array($info['grps'])) {
242 foreach ($info['grps'] as $ndx => $group) {
243 $info['grps'][$ndx] = $this->cleanGroup($group);
247 // always add the default group to the list of groups
248 if (!is_array($info['grps']) || !in_array($conf['defaultgroup'], $info['grps'])) {
249 $info['grps'][] = $conf['defaultgroup'];
252 // add the user's domain to the groups
253 $domain = $this->getUserDomain($user);
254 if ($domain && !in_array("domain-$domain", (array) $info['grps'])) {
255 $info['grps'][] = $this->cleanGroup("domain-$domain");
258 // check expiry time
259 if ($info['expires'] && $this->conf['expirywarn']) {
260 try {
261 $expiry = $adldap->user()->passwordExpiry($user);
262 if (is_array($expiry)) {
263 $info['expiresat'] = $expiry['expiryts'];
264 $info['expiresin'] = round(($info['expiresat'] - time())/(24*60*60));
266 // if this is the current user, warn him (once per request only)
267 if (($INPUT->server->str('REMOTE_USER') == $user) &&
268 ($info['expiresin'] <= $this->conf['expirywarn']) &&
269 !$this->msgshown
271 $msg = sprintf($this->getLang('authpwdexpire'), $info['expiresin']);
272 if ($this->canDo('modPass')) {
273 $url = wl($ID, array('do'=> 'profile'));
274 $msg .= ' <a href="'.$url.'">'.$lang['btn_profile'].'</a>';
276 msg($msg);
277 $this->msgshown = true;
280 } catch (adLDAPException $e) {
281 // ignore. should usually not happen
285 return $info;
289 * Make AD group names usable by DokuWiki.
291 * Removes backslashes ('\'), pound signs ('#'), and converts spaces to underscores.
293 * @author James Van Lommel (jamesvl@gmail.com)
294 * @param string $group
295 * @return string
297 public function cleanGroup($group)
299 $group = str_replace('\\', '', $group);
300 $group = str_replace('#', '', $group);
301 $group = preg_replace('[\s]', '_', $group);
302 $group = \dokuwiki\Utf8\PhpString::strtolower(trim($group));
303 return $group;
307 * Sanitize user names
309 * Normalizes domain parts, does not modify the user name itself (unlike cleanGroup)
311 * @author Andreas Gohr <gohr@cosmocode.de>
312 * @param string $user
313 * @return string
315 public function cleanUser($user)
317 $domain = '';
319 // get NTLM or Kerberos domain part
320 list($dom, $user) = array_pad(explode('\\', $user, 2), 2, '');
321 if (!$user) $user = $dom;
322 if ($dom) $domain = $dom;
323 list($user, $dom) = array_pad(explode('@', $user, 2), 2, '');
324 if ($dom) $domain = $dom;
326 // clean up both
327 $domain = \dokuwiki\Utf8\PhpString::strtolower(trim($domain));
328 $user = \dokuwiki\Utf8\PhpString::strtolower(trim($user));
330 // is this a known, valid domain or do we work without account suffix? if not discard
331 if ((!isset($this->conf[$domain]) || !is_array($this->conf[$domain])) &&
332 $this->conf['account_suffix'] !== '') {
333 $domain = '';
336 // reattach domain
337 if ($domain) $user = "$user@$domain";
338 return $user;
342 * Most values in LDAP are case-insensitive
344 * @return bool
346 public function isCaseSensitive()
348 return false;
352 * Create a Search-String useable by adLDAPUsers::all($includeDescription = false, $search = "*", $sorted = true)
354 * @param array $filter
355 * @return string
357 protected function constructSearchString($filter)
359 if (!$filter) {
360 return '*';
362 $adldapUtils = new adLDAPUtils($this->initAdLdap(null));
363 $result = '*';
364 if (isset($filter['name'])) {
365 $result .= ')(displayname=*' . $adldapUtils->ldapSlashes($filter['name']) . '*';
366 unset($filter['name']);
369 if (isset($filter['user'])) {
370 $result .= ')(samAccountName=*' . $adldapUtils->ldapSlashes($filter['user']) . '*';
371 unset($filter['user']);
374 if (isset($filter['mail'])) {
375 $result .= ')(mail=*' . $adldapUtils->ldapSlashes($filter['mail']) . '*';
376 unset($filter['mail']);
378 return $result;
382 * Return a count of the number of user which meet $filter criteria
384 * @param array $filter $filter array of field/pattern pairs, empty array for no filter
385 * @return int number of users
387 public function getUserCount($filter = array())
389 $adldap = $this->initAdLdap(null);
390 if (!$adldap) {
391 Logger::debug("authad/auth.php getUserCount(): _adldap not set.");
392 return -1;
394 if ($filter == array()) {
395 $result = $adldap->user()->all();
396 } else {
397 $searchString = $this->constructSearchString($filter);
398 $result = $adldap->user()->all(false, $searchString);
399 if (isset($filter['grps'])) {
400 $this->users = array_fill_keys($result, false);
401 /** @var admin_plugin_usermanager $usermanager */
402 $usermanager = plugin_load("admin", "usermanager", false);
403 $usermanager->setLastdisabled(true);
404 if (!isset($this->grpsusers[$this->filterToString($filter)])) {
405 $this->fillGroupUserArray($filter, $usermanager->getStart() + 3*$usermanager->getPagesize());
406 } elseif (count($this->grpsusers[$this->filterToString($filter)]) <
407 $usermanager->getStart() + 3*$usermanager->getPagesize()
409 $this->fillGroupUserArray(
410 $filter,
411 $usermanager->getStart() +
412 3*$usermanager->getPagesize() -
413 count($this->grpsusers[$this->filterToString($filter)])
416 $result = $this->grpsusers[$this->filterToString($filter)];
417 } else {
418 /** @var admin_plugin_usermanager $usermanager */
419 $usermanager = plugin_load("admin", "usermanager", false);
420 $usermanager->setLastdisabled(false);
424 if (!$result) {
425 return 0;
427 return count($result);
432 * create a unique string for each filter used with a group
434 * @param array $filter
435 * @return string
437 protected function filterToString($filter)
439 $result = '';
440 if (isset($filter['user'])) {
441 $result .= 'user-' . $filter['user'];
443 if (isset($filter['name'])) {
444 $result .= 'name-' . $filter['name'];
446 if (isset($filter['mail'])) {
447 $result .= 'mail-' . $filter['mail'];
449 if (isset($filter['grps'])) {
450 $result .= 'grps-' . $filter['grps'];
452 return $result;
456 * Create an array of $numberOfAdds users passing a certain $filter, including belonging
457 * to a certain group and save them to a object-wide array. If the array
458 * already exists try to add $numberOfAdds further users to it.
460 * @param array $filter
461 * @param int $numberOfAdds additional number of users requested
462 * @return int number of Users actually add to Array
464 protected function fillGroupUserArray($filter, $numberOfAdds)
466 if (isset($this->grpsusers[$this->filterToString($filter)])) {
467 $actualstart = count($this->grpsusers[$this->filterToString($filter)]);
468 } else {
469 $this->grpsusers[$this->filterToString($filter)] = [];
470 $actualstart = 0;
473 $i=0;
474 $count = 0;
475 $this->constructPattern($filter);
476 foreach ($this->users as $user => &$info) {
477 if ($i++ < $actualstart) {
478 continue;
480 if ($info === false) {
481 $info = $this->getUserData($user);
483 if ($this->filter($user, $info)) {
484 $this->grpsusers[$this->filterToString($filter)][$user] = $info;
485 if (($numberOfAdds > 0) && (++$count >= $numberOfAdds)) break;
488 return $count;
492 * Bulk retrieval of user data
494 * @author Dominik Eckelmann <dokuwiki@cosmocode.de>
496 * @param int $start index of first user to be returned
497 * @param int $limit max number of users to be returned
498 * @param array $filter array of field/pattern pairs, null for no filter
499 * @return array userinfo (refer getUserData for internal userinfo details)
501 public function retrieveUsers($start = 0, $limit = 0, $filter = array())
503 $adldap = $this->initAdLdap(null);
504 if (!$adldap) return array();
506 //if (!$this->users) {
507 //get info for given user
508 $result = $adldap->user()->all(false, $this->constructSearchString($filter));
509 if (!$result) return array();
510 $this->users = array_fill_keys($result, false);
513 $i = 0;
514 $count = 0;
515 $result = array();
517 if (!isset($filter['grps'])) {
518 /** @var admin_plugin_usermanager $usermanager */
519 $usermanager = plugin_load("admin", "usermanager", false);
520 $usermanager->setLastdisabled(false);
521 $this->constructPattern($filter);
522 foreach ($this->users as $user => &$info) {
523 if ($i++ < $start) {
524 continue;
526 if ($info === false) {
527 $info = $this->getUserData($user);
529 $result[$user] = $info;
530 if (($limit > 0) && (++$count >= $limit)) break;
532 } else {
533 /** @var admin_plugin_usermanager $usermanager */
534 $usermanager = plugin_load("admin", "usermanager", false);
535 $usermanager->setLastdisabled(true);
536 if (!isset($this->grpsusers[$this->filterToString($filter)]) ||
537 count($this->grpsusers[$this->filterToString($filter)]) < ($start+$limit)
539 if(!isset($this->grpsusers[$this->filterToString($filter)])) {
540 $this->grpsusers[$this->filterToString($filter)] = [];
543 $this->fillGroupUserArray(
544 $filter,
545 $start+$limit - count($this->grpsusers[$this->filterToString($filter)]) +1
548 if (!$this->grpsusers[$this->filterToString($filter)]) return array();
549 foreach ($this->grpsusers[$this->filterToString($filter)] as $user => &$info) {
550 if ($i++ < $start) {
551 continue;
553 $result[$user] = $info;
554 if (($limit > 0) && (++$count >= $limit)) break;
557 return $result;
561 * Modify user data
563 * @param string $user nick of the user to be changed
564 * @param array $changes array of field/value pairs to be changed
565 * @return bool
567 public function modifyUser($user, $changes)
569 $return = true;
570 $adldap = $this->initAdLdap($this->getUserDomain($user));
571 if (!$adldap) {
572 msg($this->getLang('connectfail'), -1);
573 return false;
576 // password changing
577 if (isset($changes['pass'])) {
578 try {
579 $return = $adldap->user()->password($this->getUserName($user), $changes['pass']);
580 } catch (adLDAPException $e) {
581 if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
582 $return = false;
584 if (!$return) msg($this->getLang('passchangefail'), -1);
587 // changing user data
588 $adchanges = array();
589 if (isset($changes['name'])) {
590 // get first and last name
591 $parts = explode(' ', $changes['name']);
592 $adchanges['surname'] = array_pop($parts);
593 $adchanges['firstname'] = join(' ', $parts);
594 $adchanges['display_name'] = $changes['name'];
596 if (isset($changes['mail'])) {
597 $adchanges['email'] = $changes['mail'];
599 if (count($adchanges)) {
600 try {
601 $return = $return & $adldap->user()->modify($this->getUserName($user), $adchanges);
602 } catch (adLDAPException $e) {
603 if ($this->conf['debug']) msg('AD Auth: '.$e->getMessage(), -1);
604 $return = false;
606 if (!$return) msg($this->getLang('userchangefail'), -1);
609 return $return;
613 * Initialize the AdLDAP library and connect to the server
615 * When you pass null as domain, it will reuse any existing domain.
616 * Eg. the one of the logged in user. It falls back to the default
617 * domain if no current one is available.
619 * @param string|null $domain The AD domain to use
620 * @return adLDAP|bool true if a connection was established
622 protected function initAdLdap($domain)
624 if (is_null($domain) && is_array($this->opts)) {
625 $domain = $this->opts['domain'];
628 $this->opts = $this->loadServerConfig((string) $domain);
629 if (isset($this->adldap[$domain])) return $this->adldap[$domain];
631 // connect
632 try {
633 $this->adldap[$domain] = new adLDAP($this->opts);
634 return $this->adldap[$domain];
635 } catch (Exception $e) {
636 if ($this->conf['debug']) {
637 msg('AD Auth: '.$e->getMessage(), -1);
639 $this->success = false;
640 $this->adldap[$domain] = null;
642 return false;
646 * Get the domain part from a user
648 * @param string $user
649 * @return string
651 public function getUserDomain($user)
653 list(, $domain) = array_pad(explode('@', $user, 2), 2, '');
654 return $domain;
658 * Get the user part from a user
660 * When an account suffix is set, we strip the domain part from the user
662 * @param string $user
663 * @return string
665 public function getUserName($user)
667 if ($this->conf['account_suffix'] !== '') {
668 list($user) = explode('@', $user, 2);
670 return $user;
674 * Fetch the configuration for the given AD domain
676 * @param string $domain current AD domain
677 * @return array
679 protected function loadServerConfig($domain)
681 // prepare adLDAP standard configuration
682 $opts = $this->conf;
684 $opts['domain'] = $domain;
686 // add possible domain specific configuration
687 if ($domain && is_array($this->conf[$domain])) foreach ($this->conf[$domain] as $key => $val) {
688 $opts[$key] = $val;
691 // handle multiple AD servers
692 $opts['domain_controllers'] = explode(',', $opts['domain_controllers']);
693 $opts['domain_controllers'] = array_map('trim', $opts['domain_controllers']);
694 $opts['domain_controllers'] = array_filter($opts['domain_controllers']);
696 // compatibility with old option name
697 if (empty($opts['admin_username']) && !empty($opts['ad_username'])) {
698 $opts['admin_username'] = $opts['ad_username'];
700 if (empty($opts['admin_password']) && !empty($opts['ad_password'])) {
701 $opts['admin_password'] = $opts['ad_password'];
703 $opts['admin_password'] = conf_decodeString($opts['admin_password']); // deobfuscate
705 // we can change the password if SSL is set
706 if ($opts['update_pass'] && ($opts['use_ssl'] || $opts['use_tls'])) {
707 $this->cando['modPass'] = true;
708 } else {
709 $this->cando['modPass'] = false;
712 // adLDAP expects empty user/pass as NULL, we're less strict FS#2781
713 if (empty($opts['admin_username'])) $opts['admin_username'] = null;
714 if (empty($opts['admin_password'])) $opts['admin_password'] = null;
716 // user listing needs admin priviledges
717 if (!empty($opts['admin_username']) && !empty($opts['admin_password'])) {
718 $this->cando['getUsers'] = true;
719 } else {
720 $this->cando['getUsers'] = false;
723 return $opts;
727 * Returns a list of configured domains
729 * The default domain has an empty string as key
731 * @return array associative array(key => domain)
733 public function getConfiguredDomains()
735 $domains = array();
736 if (empty($this->conf['account_suffix'])) return $domains; // not configured yet
738 // add default domain, using the name from account suffix
739 $domains[''] = ltrim($this->conf['account_suffix'], '@');
741 // find additional domains
742 foreach ($this->conf as $key => $val) {
743 if (is_array($val) && isset($val['account_suffix'])) {
744 $domains[$key] = ltrim($val['account_suffix'], '@');
747 Sort::ksort($domains);
749 return $domains;
753 * Check provided user and userinfo for matching patterns
755 * The patterns are set up with $this->_constructPattern()
757 * @author Chris Smith <chris@jalakai.co.uk>
759 * @param string $user
760 * @param array $info
761 * @return bool
763 protected function filter($user, $info)
765 foreach ($this->pattern as $item => $pattern) {
766 if ($item == 'user') {
767 if (!preg_match($pattern, $user)) return false;
768 } elseif ($item == 'grps') {
769 if (!count(preg_grep($pattern, $info['grps']))) return false;
770 } else {
771 if (!preg_match($pattern, $info[$item])) return false;
774 return true;
778 * Create a pattern for $this->_filter()
780 * @author Chris Smith <chris@jalakai.co.uk>
782 * @param array $filter
784 protected function constructPattern($filter)
786 $this->pattern = array();
787 foreach ($filter as $item => $pattern) {
788 $this->pattern[$item] = '/'.str_replace('/', '\/', $pattern).'/i'; // allow regex characters