1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703
|
<?php
use dokuwiki\Extension\AuthPlugin;
use dokuwiki\PassHash;
use dokuwiki\Utf8\Sort;
/**
* LDAP authentication backend
*
* @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
* @author Andreas Gohr <andi@splitbrain.org>
* @author Chris Smith <chris@jalakaic.co.uk>
* @author Jan Schumann <js@schumann-it.com>
*/
class auth_plugin_authldap extends AuthPlugin
{
/* @var resource $con holds the LDAP connection */
protected $con;
/* @var int $bound What type of connection does already exist? */
protected $bound = 0; // 0: anonymous, 1: user, 2: superuser
/* @var array $users User data cache */
protected $users;
/* @var array $pattern User filter pattern */
protected $pattern;
/**
* Constructor
*/
public function __construct()
{
parent::__construct();
// ldap extension is needed
if (!function_exists('ldap_connect')) {
$this->debug("LDAP err: PHP LDAP extension not found.", -1, __LINE__, __FILE__);
$this->success = false;
return;
}
// Add the capabilities to change the password
$this->cando['modPass'] = $this->getConf('modPass');
}
/**
* Check user+password
*
* Checks if the given user exists and the given
* plaintext password is correct by trying to bind
* to the LDAP server
*
* @param string $user
* @param string $pass
* @return bool
* @author Andreas Gohr <andi@splitbrain.org>
*/
public function checkPass($user, $pass)
{
// reject empty password
if (empty($pass)) return false;
if (!$this->openLDAP()) return false;
// indirect user bind
if ($this->getConf('binddn') && $this->getConf('bindpw')) {
// use superuser credentials
if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
$this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return false;
}
$this->bound = 2;
} elseif (
$this->getConf('binddn') &&
$this->getConf('usertree') &&
$this->getConf('userfilter')
) {
// special bind string
$dn = $this->makeFilter(
$this->getConf('binddn'),
['user' => $user, 'server' => $this->getConf('server')]
);
} elseif (strpos($this->getConf('usertree'), '%{user}')) {
// direct user bind
$dn = $this->makeFilter(
$this->getConf('usertree'),
['user' => $user, 'server' => $this->getConf('server')]
);
} elseif (!@ldap_bind($this->con)) {
// Anonymous bind
msg("LDAP: can not bind anonymously", -1);
$this->debug('LDAP anonymous bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return false;
}
// Try to bind to with the dn if we have one.
if (!empty($dn)) {
// User/Password bind
if (!@ldap_bind($this->con, $dn, $pass)) {
$this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
$this->debug('LDAP user dn bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return false;
}
$this->bound = 1;
return true;
} else {
// See if we can find the user
$info = $this->fetchUserData($user, true);
if (empty($info['dn'])) {
return false;
} else {
$dn = $info['dn'];
}
// Try to bind with the dn provided
if (!@ldap_bind($this->con, $dn, $pass)) {
$this->debug("LDAP: bind with $dn failed", -1, __LINE__, __FILE__);
$this->debug('LDAP user bind: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return false;
}
$this->bound = 1;
return true;
}
}
/**
* Return user info
*
* Returns info about the given user needs to contain
* at least these fields:
*
* name string full name of the user
* mail string email addres of the user
* grps array list of groups the user is in
*
* This LDAP specific function returns the following
* addional fields:
*
* dn string distinguished name (DN)
* uid string Posix User ID
* inbind bool for internal use - avoid loop in binding
*
* @param string $user
* @param bool $requireGroups (optional) - ignored, groups are always supplied by this plugin
* @return array containing user data or false
* @author <evaldas.auryla@pheur.org>
* @author Stephane Chazelas <stephane.chazelas@emerson.com>
* @author Steffen Schoch <schoch@dsb.net>
*
* @author Andreas Gohr <andi@splitbrain.org>
* @author Trouble
* @author Dan Allen <dan.j.allen@gmail.com>
*/
public function getUserData($user, $requireGroups = true)
{
return $this->fetchUserData($user);
}
/**
* @param string $user
* @param bool $inbind authldap specific, true if in bind phase
* @return array containing user data or false
*/
protected function fetchUserData($user, $inbind = false)
{
global $conf;
if (!$this->openLDAP()) return [];
// force superuser bind if wanted and not bound as superuser yet
if ($this->getConf('binddn') && $this->getConf('bindpw') && $this->bound < 2) {
// use superuser credentials
if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
$this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return [];
}
$this->bound = 2;
} elseif ($this->bound == 0 && !$inbind) {
// in some cases getUserData is called outside the authentication workflow
// eg. for sending email notification on subscribed pages. This data might not
// be accessible anonymously, so we try to rebind the current user here
[$loginuser, $loginsticky, $loginpass] = auth_getCookie();
if ($loginuser && $loginpass) {
$loginpass = auth_decrypt($loginpass, auth_cookiesalt(!$loginsticky, true));
$this->checkPass($loginuser, $loginpass);
}
}
$info = [];
$info['user'] = $user;
$this->debug('LDAP user to find: ' . hsc($info['user']), 0, __LINE__, __FILE__);
$info['server'] = $this->getConf('server');
$this->debug('LDAP Server: ' . hsc($info['server']), 0, __LINE__, __FILE__);
//get info for given user
$base = $this->makeFilter($this->getConf('usertree'), $info);
if ($this->getConf('userfilter')) {
$filter = $this->makeFilter($this->getConf('userfilter'), $info);
} else {
$filter = "(ObjectClass=*)";
}
$this->debug('LDAP Filter: ' . hsc($filter), 0, __LINE__, __FILE__);
$this->debug('LDAP user search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
$this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
$sr = $this->ldapSearch($this->con, $base, $filter, $this->getConf('userscope'), $this->getConf('attributes'));
if ($sr === false) {
$this->debug('User ldap_search failed. Check configuration.', 0, __LINE__, __FILE__);
return false;
}
$result = @ldap_get_entries($this->con, $sr);
// if result is not an array
if (!is_array($result)) {
// no objects found
$this->debug('LDAP search returned non-array result: ' . hsc(print($result)), -1, __LINE__, __FILE__);
return [];
}
// Don't accept more or less than one response
if ($result['count'] != 1) {
$this->debug(
'LDAP search returned ' . hsc($result['count']) . ' results while it should return 1!',
-1,
__LINE__,
__FILE__
);
//for($i = 0; $i < $result["count"]; $i++) {
//$this->_debug('result: '.hsc(print_r($result[$i])), 0, __LINE__, __FILE__);
//}
return [];
}
$this->debug('LDAP search found single result !', 0, __LINE__, __FILE__);
$user_result = $result[0];
ldap_free_result($sr);
// general user info
$info['dn'] = $user_result['dn'];
$info['gid'] = $user_result['gidnumber'][0] ?? null;
$info['mail'] = $user_result['mail'][0];
$info['name'] = $user_result['cn'][0];
$info['grps'] = [];
// overwrite if other attribs are specified.
if (is_array($this->getConf('mapping'))) {
foreach ($this->getConf('mapping') as $localkey => $key) {
if (is_array($key)) {
// use regexp to clean up user_result
// $key = array($key=>$regexp), only handles the first key-value
$regexp = current($key);
$key = key($key);
if ($user_result[$key]) foreach ($user_result[$key] as $grpkey => $grp) {
if ($grpkey !== 'count' && preg_match($regexp, $grp, $match)) {
if ($localkey == 'grps') {
$info[$localkey][] = $match[1];
} else {
$info[$localkey] = $match[1];
}
}
}
} else {
$info[$localkey] = $user_result[$key][0];
}
}
}
$user_result = array_merge($info, $user_result);
//get groups for given user if grouptree is given
if ($this->getConf('grouptree') || $this->getConf('groupfilter')) {
$base = $this->makeFilter($this->getConf('grouptree'), $user_result);
$filter = $this->makeFilter($this->getConf('groupfilter'), $user_result);
$sr = $this->ldapSearch(
$this->con,
$base,
$filter,
$this->getConf('groupscope'),
[$this->getConf('groupkey')]
);
$this->debug('LDAP group search: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
$this->debug('LDAP search at: ' . hsc($base . ' ' . $filter), 0, __LINE__, __FILE__);
if (!$sr) {
msg("LDAP: Reading group memberships failed", -1);
return [];
}
$result = ldap_get_entries($this->con, $sr);
ldap_free_result($sr);
if (is_array($result)) foreach ($result as $grp) {
if (!empty($grp[$this->getConf('groupkey')])) {
$group = $grp[$this->getConf('groupkey')];
if (is_array($group)) {
$group = $group[0];
} else {
$this->debug('groupkey did not return a detailled result', 0, __LINE__, __FILE__);
}
if ($group === '') continue;
$this->debug('LDAP usergroup: ' . hsc($group), 0, __LINE__, __FILE__);
$info['grps'][] = $group;
}
}
}
// always add the default group to the list of groups
if (!$info['grps'] || !in_array($conf['defaultgroup'], $info['grps'])) {
$info['grps'][] = $conf['defaultgroup'];
}
return $info;
}
/**
* Definition of the function modifyUser in order to modify the password
*
* @param string $user nick of the user to be changed
* @param array $changes array of field/value pairs to be changed (password will be clear text)
* @return bool true on success, false on error
*/
public function modifyUser($user, $changes)
{
// open the connection to the ldap
if (!$this->openLDAP()) {
$this->debug('LDAP cannot connect: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return false;
}
// find the information about the user, in particular the "dn"
$info = $this->getUserData($user, true);
if (empty($info['dn'])) {
$this->debug('LDAP cannot find your user dn', 0, __LINE__, __FILE__);
return false;
}
$dn = $info['dn'];
// find the old password of the user
[$loginuser, $loginsticky, $loginpass] = auth_getCookie();
if ($loginuser !== null) { // the user is currently logged in
$secret = auth_cookiesalt(!$loginsticky, true);
$pass = auth_decrypt($loginpass, $secret);
// bind with the ldap
if (!@ldap_bind($this->con, $dn, $pass)) {
$this->debug(
'LDAP user bind failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
0,
__LINE__,
__FILE__
);
return false;
}
} elseif ($this->getConf('binddn') && $this->getConf('bindpw')) {
// we are changing the password on behalf of the user (eg: forgotten password)
// bind with the superuser ldap
if (!@ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')))) {
$this->debug('LDAP bind as superuser: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
return false;
}
} else {
return false; // no otherway
}
// Generate the salted hashed password for LDAP
$phash = new PassHash();
$hash = $phash->hash_ssha($changes['pass']);
// change the password
if (!@ldap_mod_replace($this->con, $dn, ['userpassword' => $hash])) {
$this->debug(
'LDAP mod replace failed: ' . hsc($dn) . ': ' . hsc(ldap_error($this->con)),
0,
__LINE__,
__FILE__
);
return false;
}
return true;
}
/**
* Most values in LDAP are case-insensitive
*
* @return bool
*/
public function isCaseSensitive()
{
return false;
}
/**
* Bulk retrieval of user data
*
* @param int $start index of first user to be returned
* @param int $limit max number of users to be returned
* @param array $filter array of field/pattern pairs, null for no filter
* @return array of userinfo (refer getUserData for internal userinfo details)
* @author Dominik Eckelmann <dokuwiki@cosmocode.de>
*/
public function retrieveUsers($start = 0, $limit = 0, $filter = [])
{
if (!$this->openLDAP()) return [];
if (is_null($this->users)) {
// Perform the search and grab all their details
if ($this->getConf('userfilter')) {
$all_filter = str_replace('%{user}', '*', $this->getConf('userfilter'));
} else {
$all_filter = "(ObjectClass=*)";
}
$sr = ldap_search($this->con, $this->getConf('usertree'), $all_filter);
$entries = ldap_get_entries($this->con, $sr);
$users_array = [];
$userkey = $this->getConf('userkey');
for ($i = 0; $i < $entries["count"]; $i++) {
$users_array[] = $entries[$i][$userkey][0];
}
Sort::asort($users_array);
$result = $users_array;
if (!$result) return [];
$this->users = array_fill_keys($result, false);
}
$i = 0;
$count = 0;
$this->constructPattern($filter);
$result = [];
foreach ($this->users as $user => &$info) {
if ($i++ < $start) {
continue;
}
if ($info === false) {
$info = $this->getUserData($user);
}
if ($this->filter($user, $info)) {
$result[$user] = $info;
if (($limit > 0) && (++$count >= $limit)) break;
}
}
return $result;
}
/**
* Make LDAP filter strings.
*
* Used by auth_getUserData to make the filter
* strings for grouptree and groupfilter
*
* @param string $filter ldap search filter with placeholders
* @param array $placeholders placeholders to fill in
* @return string
* @author Troels Liebe Bentsen <tlb@rapanden.dk>
*/
protected function makeFilter($filter, $placeholders)
{
preg_match_all("/%{([^}]+)/", $filter, $matches, PREG_PATTERN_ORDER);
//replace each match
foreach ($matches[1] as $match) {
//take first element if array
if (is_array($placeholders[$match])) {
$value = $placeholders[$match][0];
} else {
$value = $placeholders[$match];
}
$value = $this->filterEscape($value);
$filter = str_replace('%{' . $match . '}', $value, $filter);
}
return $filter;
}
/**
* return true if $user + $info match $filter criteria, false otherwise
*
* @param string $user the user's login name
* @param array $info the user's userinfo array
* @return bool
* @author Chris Smith <chris@jalakai.co.uk>
*
*/
protected function filter($user, $info)
{
foreach ($this->pattern as $item => $pattern) {
if ($item == 'user') {
if (!preg_match($pattern, $user)) return false;
} elseif ($item == 'grps') {
if (!count(preg_grep($pattern, $info['grps']))) return false;
} elseif (!preg_match($pattern, $info[$item])) {
return false;
}
}
return true;
}
/**
* Set the filter pattern
*
* @param $filter
* @return void
* @author Chris Smith <chris@jalakai.co.uk>
*
*/
protected function constructPattern($filter)
{
$this->pattern = [];
foreach ($filter as $item => $pattern) {
$this->pattern[$item] = '/' . str_replace('/', '\/', $pattern) . '/i'; // allow regex characters
}
}
/**
* Escape a string to be used in a LDAP filter
*
* Ported from Perl's Net::LDAP::Util escape_filter_value
*
* @param string $string
* @return string
* @author Andreas Gohr
*/
protected function filterEscape($string)
{
// see https://github.com/adldap/adLDAP/issues/22
return preg_replace_callback(
'/([\x00-\x1F\*\(\)\\\\])/',
static fn($matches) => "\\" . implode("", unpack("H2", $matches[1])),
$string
);
}
/**
* Opens a connection to the configured LDAP server and sets the wanted
* option on the connection
*
* @author Andreas Gohr <andi@splitbrain.org>
*/
protected function openLDAP()
{
if ($this->con) return true; // connection already established
if ($this->getConf('debug')) {
ldap_set_option(null, LDAP_OPT_DEBUG_LEVEL, 7);
}
$this->bound = 0;
$port = $this->getConf('port');
$bound = false;
$servers = explode(',', $this->getConf('server'));
foreach ($servers as $server) {
$server = trim($server);
$this->con = @ldap_connect($server, $port);
if (!$this->con) {
continue;
}
/*
* When OpenLDAP 2.x.x is used, ldap_connect() will always return a resource as it does
* not actually connect but just initializes the connecting parameters. The actual
* connect happens with the next calls to ldap_* funcs, usually with ldap_bind().
*
* So we should try to bind to server in order to check its availability.
*/
//set protocol version and dependend options
if ($this->getConf('version')) {
if (
!@ldap_set_option(
$this->con,
LDAP_OPT_PROTOCOL_VERSION,
$this->getConf('version')
)
) {
msg('Setting LDAP Protocol version ' . $this->getConf('version') . ' failed', -1);
$this->debug('LDAP version set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
} else {
//use TLS (needs version 3)
if ($this->getConf('starttls')) {
if (!@ldap_start_tls($this->con)) {
msg('Starting TLS failed', -1);
$this->debug('LDAP TLS set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
}
}
// needs version 3
if ($this->getConf('referrals') > -1) {
if (
!@ldap_set_option(
$this->con,
LDAP_OPT_REFERRALS,
$this->getConf('referrals')
)
) {
msg('Setting LDAP referrals failed', -1);
$this->debug('LDAP referal set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
}
}
}
}
//set deref mode
if ($this->getConf('deref')) {
if (!@ldap_set_option($this->con, LDAP_OPT_DEREF, $this->getConf('deref'))) {
msg('Setting LDAP Deref mode ' . $this->getConf('deref') . ' failed', -1);
$this->debug('LDAP deref set: ' . hsc(ldap_error($this->con)), 0, __LINE__, __FILE__);
}
}
/* As of PHP 5.3.0 we can set timeout to speedup skipping of invalid servers */
if (defined('LDAP_OPT_NETWORK_TIMEOUT')) {
ldap_set_option($this->con, LDAP_OPT_NETWORK_TIMEOUT, 1);
}
if ($this->getConf('binddn') && $this->getConf('bindpw')) {
$bound = @ldap_bind($this->con, $this->getConf('binddn'), conf_decodeString($this->getConf('bindpw')));
$this->bound = 2;
} else {
$bound = @ldap_bind($this->con);
}
if ($bound) {
break;
}
}
if (!$bound) {
msg("LDAP: couldn't connect to LDAP server", -1);
$this->debug(ldap_error($this->con), 0, __LINE__, __FILE__);
return false;
}
$this->cando['getUsers'] = true;
return true;
}
/**
* Wraps around ldap_search, ldap_list or ldap_read depending on $scope
*
* @param resource $link_identifier
* @param string $base_dn
* @param string $filter
* @param string $scope can be 'base', 'one' or 'sub'
* @param null|array $attributes
* @param int $attrsonly
* @param int $sizelimit
* @return resource
* @author Andreas Gohr <andi@splitbrain.org>
*/
protected function ldapSearch(
$link_identifier,
$base_dn,
$filter,
$scope = 'sub',
$attributes = null,
$attrsonly = 0,
$sizelimit = 0
) {
if (is_null($attributes)) $attributes = [];
if ($scope == 'base') {
return @ldap_read(
$link_identifier,
$base_dn,
$filter,
$attributes,
$attrsonly,
$sizelimit
);
} elseif ($scope == 'one') {
return @ldap_list(
$link_identifier,
$base_dn,
$filter,
$attributes,
$attrsonly,
$sizelimit
);
} else {
return @ldap_search(
$link_identifier,
$base_dn,
$filter,
$attributes,
$attrsonly,
$sizelimit
);
}
}
/**
* Wrapper around msg() but outputs only when debug is enabled
*
* @param string $message
* @param int $err
* @param int $line
* @param string $file
* @return void
*/
protected function debug($message, $err, $line, $file)
{
if (!$this->getConf('debug')) return;
msg($message, $err, $line, $file);
}
}
|