| 1 |
<?php |
| 2 |
/* |
| 3 |
|
| 4 |
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) |
| 5 |
Copyright (C) 2003 - 2006 Tilo Lutz |
| 6 |
2009 - 2026 Roland Gruber |
| 7 |
|
| 8 |
This program is free software; you can redistribute it and/or modify |
| 9 |
it under the terms of the GNU General Public License as published by |
| 10 |
the Free Software Foundation; either version 2 of the License, or |
| 11 |
(at your option) any later version. |
| 12 |
|
| 13 |
This program is distributed in the hope that it will be useful, |
| 14 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 15 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 16 |
GNU General Public License for more details. |
| 17 |
|
| 18 |
You should have received a copy of the GNU General Public License |
| 19 |
along with this program; if not, write to the Free Software |
| 20 |
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 21 |
|
| 22 |
*/ |
| 23 |
|
| 24 |
/** |
| 25 |
* This provides several helper function for the account modules. |
| 26 |
* |
| 27 |
* @author Tilo Lutz |
| 28 |
* @author Roland Gruber |
| 29 |
* |
| 30 |
* @package lib |
| 31 |
*/ |
| 32 |
|
| 33 |
use LAM\PLUGINS\EXTRA_INVALID_CREDENTIALS\ExtraInvalidCredentials; |
| 34 |
use LAM\PLUGINS\SMS\SmsService; |
| 35 |
use LAM\TYPES\TypeManager; |
| 36 |
use LDAP\Connection; |
| 37 |
use Random\Randomizer; |
| 38 |
|
| 39 |
/** |
| 40 |
* Adapted version of preg_split that returns an empty array instead of false on error. |
| 41 |
* @see preg_split() |
| 42 |
* |
| 43 |
* @param string $pattern search pattern |
| 44 |
* @param string $input input string |
| 45 |
* @param int $limit result limit |
| 46 |
* @param int $flags flags |
| 47 |
* @return string[] result |
| 48 |
*/ |
| 49 |
function lam_preg_split(string $pattern, string $input, int $limit = -1, int $flags = 0): array { |
| 50 |
$result = preg_split($pattern, $input, $limit, $flags); |
| 51 |
if ($result === false) { |
| 52 |
return []; |
| 53 |
} |
| 54 |
return $result; |
| 55 |
} |
| 56 |
|
| 57 |
/** |
| 58 |
* This function will return all values from $array without values of $values. |
| 59 |
* |
| 60 |
* @template T |
| 61 |
* @param T[] $values list of values which should be removed |
| 62 |
* @param T[]|null $array list of original values |
| 63 |
* @return T[] list of remaining values |
| 64 |
*/ |
| 65 |
function array_delete($values, $array) { |
| 66 |
// Loop for every entry and check if it should be removed |
| 67 |
if (is_array($array)) { |
| 68 |
$return = []; |
| 69 |
foreach ($array as $array_value) { |
| 70 |
if (!@in_array($array_value, $values)) { |
| 71 |
$return[] = $array_value; |
| 72 |
} |
| 73 |
} |
| 74 |
return $return; |
| 75 |
} |
| 76 |
return []; |
| 77 |
} |
| 78 |
|
| 79 |
/** |
| 80 |
* Flattens the values of a multidimensional array. |
| 81 |
* Only unique values are returned. |
| 82 |
* |
| 83 |
* @param mixed[] $array multidimensional array |
| 84 |
* @return mixed[] flat array |
| 85 |
*/ |
| 86 |
function flattenArray(array $array): array { |
| 87 |
$result = []; |
| 88 |
foreach ($array as $element) { |
| 89 |
if (is_array($element)) { |
| 90 |
$result = array_merge($result, flattenArray($element)); |
| 91 |
} |
| 92 |
else { |
| 93 |
$result[] = $element; |
| 94 |
} |
| 95 |
} |
| 96 |
return array_values(array_unique($result)); |
| 97 |
} |
| 98 |
|
| 99 |
/** |
| 100 |
* Checks if a string exists in an array, ignoring case. |
| 101 |
* |
| 102 |
* @param string|null $needle search string |
| 103 |
* @param string[]|null $haystack array |
| 104 |
* @return bool needle contained in haystack |
| 105 |
*/ |
| 106 |
function in_array_ignore_case(?string $needle, ?array $haystack): bool { |
| 107 |
if (!is_array($haystack)) { |
| 108 |
return false; |
| 109 |
} |
| 110 |
if (!is_string($needle)) { |
| 111 |
return false; |
| 112 |
} |
| 113 |
foreach ($haystack as $element) { |
| 114 |
if (0 === strcasecmp($needle, $element)) { |
| 115 |
return true; |
| 116 |
} |
| 117 |
} |
| 118 |
return false; |
| 119 |
} |
| 120 |
|
| 121 |
/** |
| 122 |
* Checks if two arrays have the same content. |
| 123 |
* |
| 124 |
* @template T |
| 125 |
* @param T[] $array1 array 1 |
| 126 |
* @param T[] $array2 array 2 |
| 127 |
* @return bool same content |
| 128 |
*/ |
| 129 |
function areArrayContentsEqual(array $array1, array $array2): bool { |
| 130 |
$intersect = array_intersect($array1, $array2); |
| 131 |
return ((count($array1) === count($array2)) && (count($intersect) === count($array1))); |
| 132 |
} |
| 133 |
|
| 134 |
/** |
| 135 |
* Sorts an array in natural order by its keys. |
| 136 |
* |
| 137 |
* @template T |
| 138 |
* @param T[] $toSort array to sort |
| 139 |
* @return T[] sorted array |
| 140 |
*/ |
| 141 |
function natCaseKeySort(array $toSort): array { |
| 142 |
$keys = array_keys($toSort); |
| 143 |
natcasesort($keys); |
| 144 |
$newElements = []; |
| 145 |
foreach ($keys as $key) { |
| 146 |
$newElements[$key] = $toSort[$key]; |
| 147 |
} |
| 148 |
return $newElements; |
| 149 |
} |
| 150 |
|
| 151 |
/** |
| 152 |
* Generates the NT hash of a password. |
| 153 |
* |
| 154 |
* @param string $password password original password |
| 155 |
* @return string password hash |
| 156 |
*/ |
| 157 |
function ntPassword(string $password): string { |
| 158 |
return strtoupper(hash('md4', convertUtf8ToUtf16Le($password))); |
| 159 |
} |
| 160 |
|
| 161 |
/** |
| 162 |
* Returns the hash value of a plain text password. |
| 163 |
* |
| 164 |
* @param string|null $password the password string |
| 165 |
* @param boolean $enabled marks the hash as enabled/disabled (e.g. by prefixing "!") |
| 166 |
* @param string $hashType password hash type (CRYPT, CRYPT-SHA512, SHA, SSHA, MD5, SMD5, PLAIN, K5KEY) |
| 167 |
* @return string the password hash |
| 168 |
* |
| 169 |
* @see getSupportedHashTypes() |
| 170 |
*/ |
| 171 |
function pwd_hash(?string $password, bool $enabled = true, string $hashType = 'SSHA'): string { |
| 172 |
// check for empty password |
| 173 |
if (($password === null) || ($password === "")) { |
| 174 |
return ""; |
| 175 |
} |
| 176 |
switch ($hashType) { |
| 177 |
case 'CRYPT': |
| 178 |
$hash = "{CRYPT}" . crypt($password, generateSalt(2)); |
| 179 |
break; |
| 180 |
case 'CRYPT-SHA512': |
| 181 |
$hash = "{CRYPT}" . crypt($password, '$6$' . generateSalt(16)); |
| 182 |
break; |
| 183 |
case 'PBKDF2-SHA512': |
| 184 |
$iterations = 200000; |
| 185 |
$salt = openssl_random_pseudo_bytes(16); |
| 186 |
$hashBinary = openssl_pbkdf2($password, $salt, 64, $iterations, 'sha512'); |
| 187 |
$hash = "{PBKDF2-SHA512}{$iterations}" . '$' . base64_encode($salt) . '$' . base64_encode($hashBinary); |
| 188 |
break; |
| 189 |
case 'MD5': |
| 190 |
$hash = "{MD5}" . base64_encode(hex2bin(md5($password))); |
| 191 |
break; |
| 192 |
case 'SMD5': |
| 193 |
$salt = generateSalt(4); |
| 194 |
$hash = "{SMD5}" . base64_encode(hex2bin(md5($password . $salt)) . $salt); |
| 195 |
break; |
| 196 |
case 'SHA': |
| 197 |
$hash = "{SHA}" . base64_encode(hex2bin(sha1($password))); |
| 198 |
break; |
| 199 |
case 'PLAIN': |
| 200 |
$hash = $password; |
| 201 |
break; |
| 202 |
case 'K5KEY': |
| 203 |
$hash = '{K5KEY}'; |
| 204 |
break; |
| 205 |
case 'ARGON2ID': |
| 206 |
$threads = max(4, PASSWORD_ARGON2_DEFAULT_THREADS); |
| 207 |
$hash = "{ARGON2}" . password_hash($password, PASSWORD_ARGON2ID, ['threads' => $threads]); |
| 208 |
break; |
| 209 |
case 'SSHA': |
| 210 |
default: // use SSHA if the setting is invalid |
| 211 |
$salt = generateSalt(4); |
| 212 |
$hash = "{SSHA}" . base64_encode(hex2bin(sha1($password . $salt)) . $salt); |
| 213 |
break; |
| 214 |
} |
| 215 |
// enable/disable password |
| 216 |
if (!$enabled) { |
| 217 |
return pwd_disable($hash); |
| 218 |
} |
| 219 |
return $hash; |
| 220 |
} |
| 221 |
|
| 222 |
/** |
| 223 |
* Returns the hash type of the given password hash. |
| 224 |
* This will return PLAIN if no supported hash type was found. |
| 225 |
* |
| 226 |
* @param string|null $hash password hash |
| 227 |
* @return string type (e.g. SSHA) |
| 228 |
*/ |
| 229 |
function getHashType(?string $hash): string { |
| 230 |
if (empty($hash)) { |
| 231 |
return 'PLAIN'; |
| 232 |
} |
| 233 |
$matches = []; |
| 234 |
if (!preg_match('/\\{([A-Z0-9-]+)\\}.+/', $hash, $matches)) { |
| 235 |
return 'PLAIN'; |
| 236 |
} |
| 237 |
$type = $matches[1]; |
| 238 |
if ($type === 'ARGON2') { |
| 239 |
return 'ARGON2ID'; |
| 240 |
} |
| 241 |
if (in_array($type, getSupportedHashTypes())) { |
| 242 |
return $type; |
| 243 |
} |
| 244 |
return 'PLAIN'; |
| 245 |
} |
| 246 |
|
| 247 |
/** |
| 248 |
* Returns the list of supported hash types (e.g. SSHA). |
| 249 |
* |
| 250 |
* @return string[] hash types |
| 251 |
*/ |
| 252 |
function getSupportedHashTypes(): array { |
| 253 |
return ['CRYPT', 'CRYPT-SHA512', 'SHA', 'SSHA', 'MD5', 'SMD5', 'PLAIN', 'SASL', 'K5KEY', 'LDAP_EXOP', 'ARGON2ID', 'PBKDF2-SHA512']; |
| 254 |
} |
| 255 |
|
| 256 |
/** |
| 257 |
* Calculates a password salt of the given length. |
| 258 |
* |
| 259 |
* @param int $len salt length |
| 260 |
* @return string the salt string |
| 261 |
* |
| 262 |
*/ |
| 263 |
function generateSalt($len): string { |
| 264 |
$chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890./'; |
| 265 |
$salt = ''; |
| 266 |
for ($i = 0; $i < $len; $i++) { |
| 267 |
$pos = abs(getRandomNumber() % strlen($chars)); |
| 268 |
$salt .= $chars[$pos]; |
| 269 |
} |
| 270 |
return $salt; |
| 271 |
} |
| 272 |
|
| 273 |
/** |
| 274 |
* Marks an password hash as enabled and returns the new hash string |
| 275 |
* |
| 276 |
* @param string $hash hash value to enable |
| 277 |
* @return string enabled password hash |
| 278 |
*/ |
| 279 |
function pwd_enable($hash) { |
| 280 |
// check if password is disabled (old wrong LAM method) |
| 281 |
if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) { |
| 282 |
return substr($hash, 1, strlen($hash)); |
| 283 |
} |
| 284 |
elseif (str_starts_with($hash, "{")) { |
| 285 |
$pos = strpos($hash, "}"); |
| 286 |
if ((substr($hash, $pos + 1, 1) === "!") || (substr($hash, $pos + 1, 1) === "*")) { |
| 287 |
// enable hash |
| 288 |
return substr($hash, 0, $pos + 1) . substr($hash, $pos + 2, strlen($hash)); |
| 289 |
} |
| 290 |
else { |
| 291 |
return $hash; // not disabled |
| 292 |
} |
| 293 |
} |
| 294 |
else { |
| 295 |
return $hash; // password is plain text |
| 296 |
} |
| 297 |
} |
| 298 |
|
| 299 |
/** |
| 300 |
* Marks an password hash as disabled and returns the new hash string |
| 301 |
* |
| 302 |
* @param string $hash hash value to disable |
| 303 |
* @return string disabled hash value |
| 304 |
*/ |
| 305 |
function pwd_disable($hash) { |
| 306 |
// check if password is disabled (old wrong LAM method) |
| 307 |
if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) { |
| 308 |
return $hash; |
| 309 |
} |
| 310 |
elseif (str_starts_with($hash, "{")) { |
| 311 |
$pos = strpos($hash, "}"); |
| 312 |
if ((substr($hash, $pos + 1, 1) === "!") || (substr($hash, $pos + 1, 1) === "*")) { |
| 313 |
// hash already disabled |
| 314 |
return $hash; |
| 315 |
} |
| 316 |
else { |
| 317 |
return substr($hash, 0, $pos + 1) . "!" . substr($hash, $pos + 1, strlen($hash)); // not disabled |
| 318 |
} |
| 319 |
} |
| 320 |
else { |
| 321 |
return $hash; // password is plain text |
| 322 |
} |
| 323 |
} |
| 324 |
|
| 325 |
/** |
| 326 |
* Checks if a Unix password can be locked. |
| 327 |
* This checks if the password is not plain text but e.g. contains {SSHA}. |
| 328 |
* |
| 329 |
* @param String $password password value |
| 330 |
* @return boolean can be locked |
| 331 |
*/ |
| 332 |
function pwd_is_lockable($password) { |
| 333 |
if (($password == null) || (strlen($password) < 5)) { |
| 334 |
return false; |
| 335 |
} |
| 336 |
// SASL is not lockable |
| 337 |
if (str_starts_with($password, '{SASL}')) { |
| 338 |
return false; |
| 339 |
} |
| 340 |
return ((str_starts_with($password, "{")) || (substr($password, 1, 1) === "{")) && (strpos($password, "}") > 3); |
| 341 |
} |
| 342 |
|
| 343 |
/** |
| 344 |
* Checks if a password hash is enabled/disabled |
| 345 |
* |
| 346 |
* @param string $hash password hash to check |
| 347 |
* @return boolean true if the password is marked as enabled |
| 348 |
*/ |
| 349 |
function pwd_is_enabled($hash) { |
| 350 |
// disabled passwords have a "!" or "*" at the beginning (old wrong LAM method) |
| 351 |
if ((str_starts_with($hash, "!{")) || (str_starts_with($hash, "*{"))) { |
| 352 |
return false; |
| 353 |
} |
| 354 |
if (str_starts_with($hash, "{")) { |
| 355 |
$pos = strrpos($hash, "}"); |
| 356 |
// check if hash starts with "!" or "*" |
| 357 |
return ((substr($hash, $pos + 1, 1) !== "!") && (substr($hash, $pos + 1, 1) !== "*")); |
| 358 |
} |
| 359 |
else { |
| 360 |
return true; |
| 361 |
} |
| 362 |
} |
| 363 |
|
| 364 |
/** |
| 365 |
* Generates a random password with 14 digits by default. |
| 366 |
* |
| 367 |
* @param int $length length of password (defaults to 14) |
| 368 |
* @param bool $checkStrength check if the password matches the policy |
| 369 |
* @return String password |
| 370 |
*/ |
| 371 |
function generateRandomPassword($length = 14, bool $checkStrength = true): string { |
| 372 |
$cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); |
| 373 |
$minLength = $cfg->passwordMinLength; |
| 374 |
$length = max($length, $minLength); |
| 375 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinLength())) { |
| 376 |
$length = max($length, $_SESSION['config']->getPwdPolicyMinLength()); |
| 377 |
} |
| 378 |
$listAll = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.-_'; |
| 379 |
$allLength = strlen($listAll); |
| 380 |
$listLower = 'abcdefghijklmnopqrstuvwxyz'; |
| 381 |
$lowerLength = strlen($listLower); |
| 382 |
$minLower = $cfg->passwordMinLower; |
| 383 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getpwdPolicyMinLowercase())) { |
| 384 |
$minLower = intval($_SESSION['config']->getpwdPolicyMinLowercase()); |
| 385 |
} |
| 386 |
$listUpper = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 387 |
$upperLength = strlen($listUpper); |
| 388 |
$minUpper = $cfg->passwordMinUpper; |
| 389 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinUppercase())) { |
| 390 |
$minUpper = $_SESSION['config']->getPwdPolicyMinUppercase(); |
| 391 |
} |
| 392 |
$listNumeric = '0123456789'; |
| 393 |
$numericLength = strlen($listNumeric); |
| 394 |
$minNumeric = $cfg->passwordMinNumeric; |
| 395 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinNumeric())) { |
| 396 |
$minNumeric = $_SESSION['config']->getPwdPolicyMinNumeric(); |
| 397 |
} |
| 398 |
$listSymbol = '.-_'; |
| 399 |
$symbolLength = strlen($listSymbol); |
| 400 |
$minSymbols = $cfg->passwordMinSymbol; |
| 401 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinSymbolic())) { |
| 402 |
$minSymbols = $_SESSION['config']->getPwdPolicyMinSymbolic(); |
| 403 |
} |
| 404 |
for ($x = 0; $x < 10000; $x++) { |
| 405 |
$password = ''; |
| 406 |
for ($i = 0; $i < $minLower; $i++) { |
| 407 |
$rand = abs(getRandomNumber() % $lowerLength); |
| 408 |
$password .= $listLower[$rand]; |
| 409 |
} |
| 410 |
for ($i = 0; $i < $minUpper; $i++) { |
| 411 |
$rand = abs(getRandomNumber() % $upperLength); |
| 412 |
$password .= $listUpper[$rand]; |
| 413 |
} |
| 414 |
for ($i = 0; $i < $minNumeric; $i++) { |
| 415 |
$rand = abs(getRandomNumber() % $numericLength); |
| 416 |
$password .= $listNumeric[$rand]; |
| 417 |
} |
| 418 |
for ($i = 0; $i < $minSymbols; $i++) { |
| 419 |
$rand = abs(getRandomNumber() % $symbolLength); |
| 420 |
$password .= $listSymbol[$rand]; |
| 421 |
} |
| 422 |
for ($i = 0; $i < $length; $i++) { |
| 423 |
$rand = abs(getRandomNumber() % $allLength); |
| 424 |
$password .= $listAll[$rand]; |
| 425 |
} |
| 426 |
if (!$checkStrength || checkPasswordStrength($password, null, [])->isValid()) { |
| 427 |
break; |
| 428 |
} |
| 429 |
} |
| 430 |
$randomizer = new Randomizer(new Random\Engine\Secure()); |
| 431 |
return $randomizer->shuffleBytes($password); |
| 432 |
} |
| 433 |
|
| 434 |
/** |
| 435 |
* Generates a random text with 20 letters by default. |
| 436 |
* |
| 437 |
* @param int $length length of password (defaults to 20) |
| 438 |
* @return string text |
| 439 |
*/ |
| 440 |
function generateRandomText($length = 20): string { |
| 441 |
$list = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 442 |
$text = ''; |
| 443 |
for ($i = 0; $i < $length; $i++) { |
| 444 |
$rand = abs(getRandomNumber() % 62); |
| 445 |
$text .= $list[$rand]; |
| 446 |
} |
| 447 |
return $text; |
| 448 |
} |
| 449 |
|
| 450 |
/** |
| 451 |
* Checks if the given password matches the crypto hash. |
| 452 |
* |
| 453 |
* @param string $type type hash type (must be one of getSupportedHashTypes()) |
| 454 |
* @param string $hash password hash value |
| 455 |
* @param string $password plain text password to check |
| 456 |
* @return bool hash matches |
| 457 |
* @see getSupportedHashTypes() |
| 458 |
*/ |
| 459 |
function checkPasswordHash($type, $hash, $password) { |
| 460 |
switch ($type) { |
| 461 |
case 'SSHA': |
| 462 |
$bin = base64_decode($hash); |
| 463 |
$salt = substr($bin, 20); |
| 464 |
$pwdHash = base64_encode(hex2bin(sha1($password . $salt)) . $salt); |
| 465 |
return (strcmp($hash, $pwdHash) === 0); |
| 466 |
case 'SHA': |
| 467 |
return (strcmp($hash, base64_encode(hex2bin(sha1($password)))) === 0); |
| 468 |
case 'SMD5': |
| 469 |
$bin = base64_decode($hash); |
| 470 |
$salt = substr($bin, 16); |
| 471 |
$pwdHash = base64_encode(hex2bin(md5($password . $salt)) . $salt); |
| 472 |
return (strcmp($hash, $pwdHash) === 0); |
| 473 |
case 'MD5': |
| 474 |
return (strcmp($hash, base64_encode(hex2bin(md5($password)))) === 0); |
| 475 |
case 'CRYPT': |
| 476 |
$parts = explode('$', $hash); |
| 477 |
if (count($parts) === 1) { |
| 478 |
$salt = substr($hash, 0, 2); |
| 479 |
$pwdHash = crypt($password, $salt); |
| 480 |
return (strcmp($hash, $pwdHash) === 0); |
| 481 |
} |
| 482 |
if (count($parts) === 4) { |
| 483 |
$version = $parts[1]; |
| 484 |
$salt = $parts[2]; |
| 485 |
$pwdHash = crypt($password, '$' . $version . '$' . $salt); |
| 486 |
return (strcmp($hash, $pwdHash) === 0); |
| 487 |
} |
| 488 |
elseif (count($parts) === 5) { |
| 489 |
$version = $parts[1]; |
| 490 |
$rounds = $parts[2]; |
| 491 |
$salt = $parts[3]; |
| 492 |
$pwdHash = crypt($password, '$' . $version . '$' . $rounds . '$' . $salt); |
| 493 |
return (strcmp($hash, $pwdHash) === 0); |
| 494 |
} |
| 495 |
return false; |
| 496 |
case 'ARGON2ID': |
| 497 |
return password_verify($password, $hash); |
| 498 |
case 'PLAIN': |
| 499 |
return $password === $hash; |
| 500 |
default: |
| 501 |
return false; |
| 502 |
} |
| 503 |
} |
| 504 |
|
| 505 |
/** |
| 506 |
* Returns the number of character classes in a password. |
| 507 |
* |
| 508 |
* @param string|null $password password |
| 509 |
* @return int number of classes |
| 510 |
*/ |
| 511 |
function getNumberOfCharacterClasses($password): int { |
| 512 |
if (($password === null) || ($password === '')) { |
| 513 |
return 0; |
| 514 |
} |
| 515 |
$classesCount = 0; |
| 516 |
if (preg_match('/[a-z]/', $password)) { |
| 517 |
$classesCount++; |
| 518 |
} |
| 519 |
if (preg_match('/[A-Z]/', $password)) { |
| 520 |
$classesCount++; |
| 521 |
} |
| 522 |
if (preg_match('/\d/', $password)) { |
| 523 |
$classesCount++; |
| 524 |
} |
| 525 |
if (preg_match('/[^a-z0-9]/i', $password)) { |
| 526 |
$classesCount++; |
| 527 |
} |
| 528 |
return $classesCount; |
| 529 |
} |
| 530 |
|
| 531 |
/** |
| 532 |
* Returns an array with all Samba 3 domain entries under the given suffix |
| 533 |
* |
| 534 |
* @param Connection|null $server LDAP handle (if null then $_SESSION['ldap']->server() is used) |
| 535 |
* @param string|null $suffix LDAP suffix to search (if null then $_SESSION['config']->get_Suffix('smbDomain') is used) |
| 536 |
* @return samba3domain[] list of samba3domain objects |
| 537 |
*/ |
| 538 |
function search_domains(?Connection $server = null, ?string $suffix = null): array { |
| 539 |
if ($suffix == null) { |
| 540 |
$suffix = $_SESSION['config']->get_Suffix('smbDomain'); |
| 541 |
} |
| 542 |
$ret = []; |
| 543 |
$attr = ["DN", "sambaDomainName", "sambaSID", "sambaNextRid", "sambaNextGroupRid", |
| 544 |
"sambaNextUserRid", "sambaAlgorithmicRidBase", 'sambaMinPwdAge', 'sambaMaxPwdAge', |
| 545 |
'sambaPwdHistoryLength' |
| 546 |
]; |
| 547 |
if ($server === null) { |
| 548 |
$server = $_SESSION['ldap']->server(); |
| 549 |
} |
| 550 |
$filter = '(objectclass=sambaDomain)'; |
| 551 |
$units = searchLDAPPaged($server, $suffix, $filter, $attr, 0, 0); |
| 552 |
// extract attributes |
| 553 |
for ($i = 0; $i < count($units); $i++) { |
| 554 |
$ret[$i] = new samba3domain(); |
| 555 |
$ret[$i]->dn = $units[$i]['dn']; |
| 556 |
$ret[$i]->name = $units[$i]['sambadomainname'][0]; |
| 557 |
$ret[$i]->SID = $units[$i]['sambasid'][0]; |
| 558 |
if (isset($units[$i]['sambanextrid'][0])) { |
| 559 |
$ret[$i]->nextRID = intval($units[$i]['sambanextrid'][0]); |
| 560 |
} |
| 561 |
if (isset($units[$i]['sambanextgrouprid'][0])) { |
| 562 |
$ret[$i]->nextGroupRID = intval($units[$i]['sambanextgrouprid'][0]); |
| 563 |
} |
| 564 |
if (isset($units[$i]['sambanextuserrid'][0])) { |
| 565 |
$ret[$i]->nextUserRID = intval($units[$i]['sambanextuserrid'][0]); |
| 566 |
} |
| 567 |
if (isset($units[$i]['sambaalgorithmicridbase'][0])) { |
| 568 |
$ret[$i]->RIDbase = intval($units[$i]['sambaalgorithmicridbase'][0]); |
| 569 |
} |
| 570 |
if (isset($units[$i]['sambaminpwdage'][0])) { |
| 571 |
$ret[$i]->minPwdAge = intval($units[$i]['sambaminpwdage'][0]); |
| 572 |
} |
| 573 |
if (isset($units[$i]['sambamaxpwdage'][0])) { |
| 574 |
$ret[$i]->maxPwdAge = intval($units[$i]['sambamaxpwdage'][0]); |
| 575 |
} |
| 576 |
if (isset($units[$i]['sambapwdhistorylength'][0])) { |
| 577 |
$ret[$i]->pwdHistoryLength = intval($units[$i]['sambapwdhistorylength'][0]); |
| 578 |
} |
| 579 |
} |
| 580 |
return $ret; |
| 581 |
} |
| 582 |
|
| 583 |
/** |
| 584 |
* Represents a Samba 3 domain entry |
| 585 |
* |
| 586 |
* @package modules |
| 587 |
*/ |
| 588 |
class samba3domain { |
| 589 |
|
| 590 |
/** DN */ |
| 591 |
public ?string $dn = null; |
| 592 |
|
| 593 |
/** Domain name */ |
| 594 |
public ?string $name = null; |
| 595 |
|
| 596 |
/** Domain SID */ |
| 597 |
public ?string $SID = null; |
| 598 |
|
| 599 |
/** Next RID */ |
| 600 |
public ?int $nextRID = null; |
| 601 |
|
| 602 |
/** Next user RID */ |
| 603 |
public ?int $nextUserRID = null; |
| 604 |
|
| 605 |
/** Next group RID */ |
| 606 |
public ?int $nextGroupRID = null; |
| 607 |
|
| 608 |
/** RID base to calculate RIDs, default 1000 */ |
| 609 |
public int $RIDbase = 1000; |
| 610 |
|
| 611 |
/** seconds after the password can be changed */ |
| 612 |
public ?int $minPwdAge = null; |
| 613 |
|
| 614 |
/** seconds after the password must be changed */ |
| 615 |
public ?int $maxPwdAge = null; |
| 616 |
|
| 617 |
/** password history length */ |
| 618 |
public ?int $pwdHistoryLength = null; |
| 619 |
} |
| 620 |
|
| 621 |
/** |
| 622 |
* Checks if a given value matches the selected regular expression. |
| 623 |
* |
| 624 |
* @param string $argument value to check |
| 625 |
* @param string $regexp pattern name |
| 626 |
* @return boolean true if matches, otherwise false |
| 627 |
*/ |
| 628 |
function get_preg($argument, $regexp) { |
| 629 |
// First we check "positive" cases |
| 630 |
$pregexpr = ''; |
| 631 |
switch ($regexp) { |
| 632 |
case 'password': |
| 633 |
$pregexpr = '/^([[:alnum:]^ |#*,.;:_+!%&\/?{()}\[\]$§°@=-])*$/u'; |
| 634 |
break; |
| 635 |
case 'groupname': // all letters, numbers, space and ._- are allowed characters |
| 636 |
case 'username': |
| 637 |
case 'hostname': |
| 638 |
$pregexpr = '/^([[:alnum:]%#@. _$-])+$/u'; |
| 639 |
break; |
| 640 |
case 'krbUserName': |
| 641 |
$pregexpr = '/^([[:alnum:]#@\/. _$-])+$/u'; |
| 642 |
break; |
| 643 |
case 'hostObject': |
| 644 |
$pregexpr = '/^!?([[:alnum:]@. _$:*-])+$/u'; |
| 645 |
break; |
| 646 |
case 'usernameList': // comma separated list of usernames |
| 647 |
case 'groupnameList': // comma separated list of group names |
| 648 |
$pregexpr = '/^([[:alnum:]%#@. _-])+(,([[:alnum:]%#@. _-])+)*$/u'; |
| 649 |
break; |
| 650 |
case 'realname': // Allow all but \, <, >, =, $, ? |
| 651 |
case 'cn': |
| 652 |
$pregexpr = '/^[^\\\\<>=$?]+(\$)?$/'; |
| 653 |
break; |
| 654 |
case "telephone": // Allow letters, numbers, space, brackets, /-+. |
| 655 |
$pregexpr = '/^(\+)*([0-9a-zA-Z. ()\/-])*$/'; |
| 656 |
break; |
| 657 |
case "email": |
| 658 |
$pregexpr = '/^([0-9a-zA-Z\'!~#+*%$\/._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*$/'; |
| 659 |
break; |
| 660 |
case "emailWithName": |
| 661 |
$pregexpr = '/^([[:alnum:] \'!~#+*%$()_-])+ <([0-9a-zA-Z\'!~#+*%$\/._-])+[@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*>$/u'; |
| 662 |
break; |
| 663 |
case "mailLocalAddress": |
| 664 |
$pregexpr = '/^([0-9a-zA-Z+\\/._-])*([@]([0-9a-zA-Z-])+([.]([0-9a-zA-Z-])+)*)?$/'; |
| 665 |
break; |
| 666 |
case 'kolabEmailPrefix': |
| 667 |
$pregexpr = '/^([-])?([0-9a-zA-Z+\\/._-])*([@]([0-9a-zA-Z.-])*)?$/'; |
| 668 |
break; |
| 669 |
case "postalAddress": // Allow all but \, <, >, =, ? |
| 670 |
$pregexpr = '/^[^\\\<>=?]*$/'; |
| 671 |
break; |
| 672 |
case "postalCode": // Allow all but \, <, >, =, ? |
| 673 |
case "street": |
| 674 |
case "title": |
| 675 |
case "employeeType": |
| 676 |
case "businessCategory": |
| 677 |
$pregexpr = '/^[^\\\<>=$?]*$/'; |
| 678 |
break; |
| 679 |
case "homeDirectory": // Home path, /path/...... |
| 680 |
case "filePath": |
| 681 |
$pregexpr = '/^([\/]([[:alnum:]@$. _-])+)+(\/)?$/u'; |
| 682 |
break; |
| 683 |
case "digit": // Normal number |
| 684 |
$pregexpr = '/^[[:digit:]]*$/'; |
| 685 |
break; |
| 686 |
case "digitWithNegativeValues": // Normal number incl. negative values |
| 687 |
$pregexpr = '/^[-]?[[:digit:]]*$/'; |
| 688 |
break; |
| 689 |
case "float": // float value |
| 690 |
$pregexpr = '/^[[:digit:]]+(\\.[[:digit:]]+)?$/'; |
| 691 |
break; |
| 692 |
case "UNC": // UNC Path, e.g. \\server\share\folder\... |
| 693 |
$pregexpr = '/^((([\\\][\\\])|(%))([a-zA-Z0-9@%.-])+)([\\\]([[:alnum:]@%.$ _-])+)+$/u'; |
| 694 |
break; |
| 695 |
case "logonscript": // path to login-script. normal unix file |
| 696 |
$pregexpr = '/^(([\/\\\])*([[:alnum:]%. $_-])+([\/\\\]([[:alnum:]%. $_-])+)*((\\.bat)|(\\.cmd)|(\\.exe)|(\\.vbs)))*$/u'; |
| 697 |
break; |
| 698 |
case "workstations": // comma separated list with windows-hosts |
| 699 |
$pregexpr = '/^(([a-zA-Z0-9._-])+(,[a-zA-Z0-9._-])*)*$/'; |
| 700 |
break; |
| 701 |
case "domainname": // Windows Domainname |
| 702 |
$pregexpr = '/^([A-Za-z0-9._-])+$/'; |
| 703 |
break; |
| 704 |
case "unixhost": // Unix hosts |
| 705 |
$pregexpr = '/^([a-z0-9,.*_-])*$/'; |
| 706 |
break; |
| 707 |
case 'digit2': // Same as digit but also -1 |
| 708 |
$pregexpr = '/^(([-][1])|([[:digit:]]*))$/'; |
| 709 |
break; |
| 710 |
case 'gecos': |
| 711 |
$pregexpr = '/^[[:alnum:] ._-]+([,][[:alnum:] ._-]+)*$/u'; |
| 712 |
break; |
| 713 |
case 'macAddress': |
| 714 |
$pregexpr = '/^[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}$/'; |
| 715 |
break; |
| 716 |
case 'date': // 31-12-2012 |
| 717 |
$pregexpr = '/^((0?[1-9])|([1-2]\d)|30|31)-((0?[1-9])|(1[0-2]))-[1-3]\d\d\d$/'; |
| 718 |
break; |
| 719 |
case 'dateTime': |
| 720 |
$pregexpr = '/^[1-3]\d\d\d\-((0[1-9])|(1[0-2]))-((0[1-9])|([1-2]\d)|30|31) ((0\d)|([1]\d)|20|21|22|23):((0\d)|([1-5]\d)):((0\d)|([1-5]\d))$/'; |
| 721 |
break; |
| 722 |
case 'sambaLogonHours': |
| 723 |
$pregexpr = '/^[0-9a-fA-F]{42}$/'; |
| 724 |
break; |
| 725 |
case 'DNSname': // server.example.com |
| 726 |
$pregexpr = '/^[0-9a-zA-Z_-]+(\\.[0-9a-zA-Z_-]+)*$/'; |
| 727 |
break; |
| 728 |
case 'DNSnameWithSpecials': // server.example.com |
| 729 |
$pregexpr = '/^[0-9a-zA-Z*_-]+(\\.[0-9a-zA-Z_-]+)*$/'; |
| 730 |
break; |
| 731 |
case 'DNSnameAbsolute': // server.example.com. |
| 732 |
$pregexpr = '/^[0-9a-zA-Z_-]+(\\.[0-9a-zA-Z_-]+)*\\.$/'; |
| 733 |
break; |
| 734 |
case 'DNSnameRelativeOrAbsolute': // server.example.com. or server.example.com |
| 735 |
$pregexpr = '/^[0-9a-zA-Z_-]+(\\.[0-9a-zA-Z_-]+)*(\\.)?$/'; |
| 736 |
break; |
| 737 |
case 'nis_alias': |
| 738 |
$pregexpr = '/^([[:alnum:]@. _-])+$/u'; |
| 739 |
break; |
| 740 |
case 'nis_recipient': |
| 741 |
$pregexpr = '/^([[:alnum:]+@. _-])+$/u'; |
| 742 |
break; |
| 743 |
case 'country': // Allow all letters and space |
| 744 |
$pregexpr = '/^[[:alpha:]]([[:alpha:] ])+$/u'; |
| 745 |
break; |
| 746 |
case 'dn': // LDAP DN |
| 747 |
$pregexpr = '/^([^=,]+=[^=,]+)(,([^=,]+=[^=,]+))*$/'; |
| 748 |
break; |
| 749 |
case 'domainSID': // Samba domain SID |
| 750 |
$pregexpr = "/^S-\\d-\\d-\\d{2,2}-\\d+-\\d+-\\d+\$/"; |
| 751 |
break; |
| 752 |
case 'ip': // IP address |
| 753 |
$pregexpr = '/^\d{1,3}[.]\d{1,3}[.]\d{1,3}[.]\d{1,3}$/'; |
| 754 |
break; |
| 755 |
case 'ip6': // IPv6 address (only basic check) |
| 756 |
$pregexpr = '/^[0-9a-f:]+$/i'; |
| 757 |
break; |
| 758 |
case 'ascii': // ASCII |
| 759 |
$pregexpr = '/^[' . chr(1) . '-' . chr(128) . ']*$/'; |
| 760 |
break; |
| 761 |
case 'objectClass': |
| 762 |
$pregexpr = '/^[[:alnum:]_-]+$/'; |
| 763 |
break; |
| 764 |
case 'quotaNumber': |
| 765 |
$pregexpr = '/^[[:digit:]]+[KMGTkmgt]?$/'; |
| 766 |
break; |
| 767 |
case 'hostAndPort': |
| 768 |
$pregexpr = '/^[[:alnum:]._-]+:[[:digit:]]+$/'; |
| 769 |
break; |
| 770 |
case 'ldapDateAndTime': |
| 771 |
$pregexpr = '/^\d{14}Z$/'; |
| 772 |
break; |
| 773 |
case 'guacamoleProtocol': |
| 774 |
$pregexpr = '/^(rdp|vnc)$/'; |
| 775 |
break; |
| 776 |
} |
| 777 |
if (($pregexpr !== '') && preg_match($pregexpr, $argument)) { |
| 778 |
return true; |
| 779 |
} |
| 780 |
// Now we check "negative" cases, characters which are not allowed |
| 781 |
$pregexpr = ''; |
| 782 |
switch ($regexp) { |
| 783 |
case "!lower": |
| 784 |
$pregexpr = '/[[:lower:]]/'; |
| 785 |
break; |
| 786 |
case "!upper": |
| 787 |
$pregexpr = '/[[:upper:]]/'; |
| 788 |
break; |
| 789 |
case "!digit": |
| 790 |
$pregexpr = '/[[:digit:]]/'; |
| 791 |
break; |
| 792 |
} |
| 793 |
return ($pregexpr !== '') && !preg_match($pregexpr, $argument); |
| 794 |
} |
| 795 |
|
| 796 |
/** |
| 797 |
* Converts the comma escaping from Windows to OpenLDAP style. |
| 798 |
* |
| 799 |
* @param string $dn DN |
| 800 |
* @return string DN |
| 801 |
*/ |
| 802 |
function convertCommaEscaping(string $dn): string { |
| 803 |
return str_replace( |
| 804 |
['\\,'], |
| 805 |
['\\2C'], |
| 806 |
$dn); |
| 807 |
} |
| 808 |
|
| 809 |
/** |
| 810 |
* Connects to an LDAP server using the given URL. |
| 811 |
* |
| 812 |
* @param string $serverURL URL |
| 813 |
* @param bool $startTLS start TLS |
| 814 |
* @return Connection|null LDAP connection |
| 815 |
*/ |
| 816 |
function connectToLDAP(string $serverURL, bool $startTLS): ?Connection { |
| 817 |
logNewMessage(LOG_DEBUG, 'Connecting to LDAP server ' . $serverURL); |
| 818 |
$server = ldap_connect($serverURL); |
| 819 |
if ($server === false) { |
| 820 |
return null; |
| 821 |
} |
| 822 |
if (defined('LDAP_OPT_X_TLS_CACERTFILE')) { |
| 823 |
$cfgMain = new LAMCfgMain(); |
| 824 |
$certificates = $cfgMain->getSSLCaCertificates(); |
| 825 |
if (!empty($certificates)) { |
| 826 |
ldap_set_option($server, LDAP_OPT_X_TLS_CACERTFILE, $cfgMain->getSSLCaCertPath()); |
| 827 |
} |
| 828 |
} |
| 829 |
// use LDAPv3 |
| 830 |
ldap_set_option($server, LDAP_OPT_PROTOCOL_VERSION, 3); |
| 831 |
// start TLS if possible |
| 832 |
if ($startTLS) { |
| 833 |
ldap_start_tls($server); |
| 834 |
if (ldap_errno($server) !== 0) { |
| 835 |
ldap_close($server); |
| 836 |
logNewMessage(LOG_ERR, 'Unable to start TLS encryption. Please check if your server certificate is valid and if the LDAP server supports TLS at all.'); |
| 837 |
return null; |
| 838 |
} |
| 839 |
} |
| 840 |
return $server; |
| 841 |
} |
| 842 |
|
| 843 |
/** |
| 844 |
* This will search the given LDAP suffix for all entries which have the given attribute. |
| 845 |
* |
| 846 |
* @param string|null $name attribute name |
| 847 |
* @param string|null $value attribute value (may be null if $name is null) |
| 848 |
* @param string|null $objectClass object class |
| 849 |
* @param string[] $attributes list of attributes to return |
| 850 |
* @param string[] $scopes account types |
| 851 |
* @return array<string, string[]|string>[] list of found entries |
| 852 |
*/ |
| 853 |
function searchLDAPByAttribute(?string $name, ?string $value, ?string $objectClass, array $attributes, array $scopes): array { |
| 854 |
$return = []; |
| 855 |
// build filter |
| 856 |
$filter = ''; |
| 857 |
$filterParts = []; |
| 858 |
if ($name !== null) { |
| 859 |
$filterParts[] = '(' . $name . '=' . ldap_escape($value, '*', LDAP_ESCAPE_FILTER) . ')'; |
| 860 |
} |
| 861 |
if ($objectClass !== null) { |
| 862 |
$filterParts[] = '(objectClass=' . $objectClass . ')'; |
| 863 |
} |
| 864 |
if (count($filterParts) === 1) { |
| 865 |
$filter = $filterParts[0]; |
| 866 |
} |
| 867 |
elseif (count($filterParts) > 1) { |
| 868 |
$filter = '(& ' . implode(' ', $filterParts) . ')'; |
| 869 |
} |
| 870 |
$typeManager = new TypeManager(); |
| 871 |
$activeTypes = $typeManager->getConfiguredTypes(); |
| 872 |
foreach ($activeTypes as $type) { |
| 873 |
if (!in_array($type->getScope(), $scopes)) { |
| 874 |
continue; // skip non-active account types |
| 875 |
} |
| 876 |
// search LDAP |
| 877 |
$entries = searchLDAPPaged($_SESSION['ldap']->server(), $type->getSuffix(), |
| 878 |
$filter, $attributes, 0, $_SESSION['config']->get_searchLimit()); |
| 879 |
if (ldap_errno($_SESSION['ldap']->server()) === 4) { |
| 880 |
logNewMessage(LOG_WARNING, 'LDAP size limit exceeded. Please increase the limit on your server.'); |
| 881 |
} |
| 882 |
$return = array_merge($return, $entries); |
| 883 |
} |
| 884 |
return $return; |
| 885 |
} |
| 886 |
|
| 887 |
/** |
| 888 |
* This will search the given LDAP suffix for all entries which match the given filter. |
| 889 |
* |
| 890 |
* @param string $filter |
| 891 |
* @param string[] $attributes list of attributes to return |
| 892 |
* @param string[] $scopes account types |
| 893 |
* @param bool $attrsOnly get only attributes but no values (default: false) |
| 894 |
* @return array<string, string[]|string>[] list of found entries |
| 895 |
*/ |
| 896 |
function searchLDAPByFilter($filter, $attributes, $scopes, $attrsOnly = false): array { |
| 897 |
$return = []; |
| 898 |
$readAttributesOnly = 0; |
| 899 |
if ($attrsOnly) { |
| 900 |
$readAttributesOnly = 1; |
| 901 |
} |
| 902 |
$typeManager = new TypeManager(); |
| 903 |
$types = $typeManager->getConfiguredTypesForScopes($scopes); |
| 904 |
foreach ($types as $type) { |
| 905 |
$additionalFilter = $type->getAdditionalLdapFilter(); |
| 906 |
if (!empty($additionalFilter)) { |
| 907 |
if (!str_starts_with($additionalFilter, '(')) { |
| 908 |
$additionalFilter = '(' . $additionalFilter . ')'; |
| 909 |
} |
| 910 |
if (!str_starts_with($filter, '(')) { |
| 911 |
$filter = '(' . $filter . ')'; |
| 912 |
} |
| 913 |
$filter = '(&' . $additionalFilter . $filter . ')'; |
| 914 |
} |
| 915 |
// search LDAP |
| 916 |
$entries = searchLDAPPaged($_SESSION['ldap']->server(), $type->getSuffix(), |
| 917 |
$filter, $attributes, $readAttributesOnly, $_SESSION['config']->get_searchLimit()); |
| 918 |
if (ldap_errno($_SESSION['ldap']->server()) === 4) { |
| 919 |
logNewMessage(LOG_WARNING, 'LDAP size limit exceeded. Please increase the limit on your server.'); |
| 920 |
} |
| 921 |
$return = array_merge($return, $entries); |
| 922 |
} |
| 923 |
return $return; |
| 924 |
} |
| 925 |
|
| 926 |
/** |
| 927 |
* Runs an LDAP search. |
| 928 |
* |
| 929 |
* @param string $suffix LDAP suffix |
| 930 |
* @param string $filter filter |
| 931 |
* @param string[] $attributes list of attributes to return |
| 932 |
* @param int $limit result limit |
| 933 |
* @return array<string, string[]|string>[] list of found entries |
| 934 |
*/ |
| 935 |
function searchLDAP($suffix, $filter, $attributes, $limit = -1): array { |
| 936 |
if ($limit === -1) { |
| 937 |
$limit = empty($_SESSION['config']) ? 0 : $_SESSION['config']->get_searchLimit(); |
| 938 |
} |
| 939 |
$return = searchLDAPPaged(getLDAPServerHandle(), $suffix, $filter, $attributes, |
| 940 |
0, $limit); |
| 941 |
if (ldap_errno(getLDAPServerHandle()) === 4) { |
| 942 |
logNewMessage(LOG_WARNING, 'LDAP size limit exceeded. Please increase the limit on your server.'); |
| 943 |
} |
| 944 |
return $return; |
| 945 |
} |
| 946 |
|
| 947 |
/** |
| 948 |
* Returns the LDAP server handle. |
| 949 |
* |
| 950 |
* @return Connection LDAP handle |
| 951 |
*/ |
| 952 |
function getLDAPServerHandle() { |
| 953 |
if (!empty($_SESSION['ldap'])) { |
| 954 |
// admin pages |
| 955 |
return $_SESSION['ldap']->server(); |
| 956 |
} |
| 957 |
else { |
| 958 |
// self-service/white pages |
| 959 |
return $_SESSION['ldapHandle']->getServer(); |
| 960 |
} |
| 961 |
} |
| 962 |
|
| 963 |
/** |
| 964 |
* Runs an LDAP search and uses paging if configured. |
| 965 |
* |
| 966 |
* @param Connection $server LDAP connection handle |
| 967 |
* @param string $dn DN |
| 968 |
* @param string $filter filter |
| 969 |
* @param string[] $attributes attribute list |
| 970 |
* @param int $attrsOnly return only attribute names (1) or also the values (0) |
| 971 |
* @param int $limit size limit |
| 972 |
* @return array<string, string[]|string>[] results |
| 973 |
*/ |
| 974 |
function searchLDAPPaged($server, $dn, $filter, $attributes, $attrsOnly, $limit): array { |
| 975 |
if (empty($_SESSION['config']) || ($_SESSION['config']->getPagedResults() !== 'true')) { |
| 976 |
$sr = @ldap_search($server, $dn, $filter, $attributes, $attrsOnly, $limit, 0, LDAP_DEREF_NEVER, getCommonLdapControls()); |
| 977 |
if ($sr) { |
| 978 |
$entries = ldap_get_entries($server, $sr); |
| 979 |
if (!$entries) { |
| 980 |
return []; |
| 981 |
} |
| 982 |
cleanLDAPResult($entries); |
| 983 |
return $entries; |
| 984 |
} |
| 985 |
else { |
| 986 |
return []; |
| 987 |
} |
| 988 |
} |
| 989 |
$pageSize = 999; |
| 990 |
$cookie = ''; |
| 991 |
$return = []; |
| 992 |
do { |
| 993 |
$controls = [ |
| 994 |
[ |
| 995 |
'oid' => LDAP_CONTROL_PAGEDRESULTS, |
| 996 |
'value' => [ |
| 997 |
'size' => $pageSize, |
| 998 |
'cookie' => $cookie] |
| 999 |
] |
| 1000 |
]; |
| 1001 |
$commonControls = getCommonLdapControls(); |
| 1002 |
if ($commonControls !== null) { |
| 1003 |
$controls += $commonControls; |
| 1004 |
} |
| 1005 |
$sr = @ldap_search($server, $dn, $filter, $attributes, $attrsOnly, $limit, |
| 1006 |
0, LDAP_DEREF_NEVER, $controls); |
| 1007 |
if (!$sr) { |
| 1008 |
break; |
| 1009 |
} |
| 1010 |
$errorCode = 0; |
| 1011 |
$matchedDn = ''; |
| 1012 |
$errorMessage = ''; |
| 1013 |
$referrals = []; |
| 1014 |
$resultControls = []; |
| 1015 |
ldap_parse_result($server, $sr, $errorCode , $matchedDn , $errorMessage , $referrals, $resultControls); |
| 1016 |
$entries = ldap_get_entries($server, $sr); |
| 1017 |
if (!$entries) { |
| 1018 |
break; |
| 1019 |
} |
| 1020 |
$return = array_merge($return, $entries); |
| 1021 |
$cookie = $resultControls[LDAP_CONTROL_PAGEDRESULTS]['value']['cookie'] ?? ''; |
| 1022 |
} |
| 1023 |
while ($cookie != ''); |
| 1024 |
cleanLDAPResult($return); |
| 1025 |
return $return; |
| 1026 |
} |
| 1027 |
|
| 1028 |
/** |
| 1029 |
* Returns the given DN. |
| 1030 |
* |
| 1031 |
* @param string $dn DN |
| 1032 |
* @param string[] $attributes list of attributes to fetch |
| 1033 |
* @param Connection $handle LDAP handle (optional for admin interface pages) |
| 1034 |
* @return array<string, string[]|string>|null attributes or null if not found |
| 1035 |
*/ |
| 1036 |
function ldapGetDN($dn, $attributes = ['dn'], $handle = null): ?array { |
| 1037 |
if ($handle == null) { |
| 1038 |
$handle = getLDAPServerHandle(); |
| 1039 |
} |
| 1040 |
$return = null; |
| 1041 |
$sr = @ldap_read($handle, $dn, '(objectClass=*)', $attributes, 0, 0, 0, LDAP_DEREF_NEVER, getCommonLdapControls()); |
| 1042 |
if ($sr) { |
| 1043 |
$entries = ldap_get_entries($handle, $sr); |
| 1044 |
if ($entries) { |
| 1045 |
cleanLDAPResult($entries); |
| 1046 |
$return = $entries[0]; |
| 1047 |
} |
| 1048 |
@ldap_free_result($sr); |
| 1049 |
} |
| 1050 |
return $return; |
| 1051 |
} |
| 1052 |
|
| 1053 |
/** |
| 1054 |
* Returns the DN and children of a given DN. |
| 1055 |
* |
| 1056 |
* @param string $dn DN |
| 1057 |
* @param string $filter LDAP filter |
| 1058 |
* @param string[] $attributes list of attributes to fetch |
| 1059 |
* @param Connection|null $handle LDAP handle (optional for admin interface pages) |
| 1060 |
* @param int $limit result limit |
| 1061 |
* @return array<string, string[]|string>|null attributes or null if not found |
| 1062 |
*/ |
| 1063 |
function ldapListDN($dn, $filter = '(objectclass=*)', $attributes = ['dn'], $handle = null, $limit = -1) { |
| 1064 |
if ($limit === -1) { |
| 1065 |
$limit = empty($_SESSION['config']) ? 0 : $_SESSION['config']->get_searchLimit(); |
| 1066 |
} |
| 1067 |
if ($handle == null) { |
| 1068 |
$handle = $_SESSION['ldap']->server(); |
| 1069 |
} |
| 1070 |
$return = null; |
| 1071 |
$sr = @ldap_list($handle, $dn, $filter, $attributes, 0, $limit, 0, LDAP_DEREF_NEVER, getCommonLdapControls()); |
| 1072 |
if ($sr) { |
| 1073 |
$entries = ldap_get_entries($handle, $sr); |
| 1074 |
if ($entries) { |
| 1075 |
cleanLDAPResult($entries); |
| 1076 |
$return = $entries; |
| 1077 |
} |
| 1078 |
@ldap_free_result($sr); |
| 1079 |
} |
| 1080 |
return $return; |
| 1081 |
} |
| 1082 |
|
| 1083 |
/** |
| 1084 |
* Deletes a DN and all child entries. |
| 1085 |
* |
| 1086 |
* @param string|null $dn DN to delete |
| 1087 |
* @param boolean $recursive recursive delete also child entries |
| 1088 |
* @return string[][] error messages |
| 1089 |
*/ |
| 1090 |
function deleteDN($dn, $recursive): array { |
| 1091 |
$errors = []; |
| 1092 |
if (($dn === null) || ($dn === '')) { |
| 1093 |
$errors[] = ['ERROR', _('Entry does not exist')]; |
| 1094 |
return $errors; |
| 1095 |
} |
| 1096 |
if ($recursive) { |
| 1097 |
$sr = @ldap_list($_SESSION['ldap']->server(), $dn, '(objectClass=*)', ['dn'], 0, 0, 0, LDAP_DEREF_NEVER, getCommonLdapControls()); |
| 1098 |
if ($sr) { |
| 1099 |
$entries = ldap_get_entries($_SESSION['ldap']->server(), $sr); |
| 1100 |
cleanLDAPResult($entries); |
| 1101 |
for ($i = 0; $i < count($entries); $i++) { |
| 1102 |
// delete recursively |
| 1103 |
$subErrors = deleteDN($entries[$i]['dn'], $recursive); |
| 1104 |
for ($e = 0; $e < count($subErrors); $e++) { |
| 1105 |
$errors[] = $subErrors[$e]; |
| 1106 |
} |
| 1107 |
} |
| 1108 |
} |
| 1109 |
else { |
| 1110 |
$errors[] = ['ERROR', sprintf(_('Was unable to delete DN: %s.'), $dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]; |
| 1111 |
return $errors; |
| 1112 |
} |
| 1113 |
} |
| 1114 |
// delete parent DN |
| 1115 |
$success = @ldap_delete($_SESSION['ldap']->server(), $dn); |
| 1116 |
if (!$success) { |
| 1117 |
logNewMessage(LOG_ERR, 'Unable to delete DN: ' . $dn . ' (' . ldap_error($_SESSION['ldap']->server()) . ').'); |
| 1118 |
$errors[] = ['ERROR', sprintf(_('Was unable to delete DN: %s.'), $dn), getDefaultLDAPErrorString($_SESSION['ldap']->server())]; |
| 1119 |
} |
| 1120 |
else { |
| 1121 |
logNewMessage(LOG_NOTICE, 'Deleted DN: ' . $dn); |
| 1122 |
} |
| 1123 |
return $errors; |
| 1124 |
} |
| 1125 |
|
| 1126 |
/** |
| 1127 |
* Returns a list of LDAP controls for all LDAP calls. |
| 1128 |
* |
| 1129 |
* @return array<string, string>[]|null controls |
| 1130 |
*/ |
| 1131 |
function getCommonLdapControls(): ?array { |
| 1132 |
if (isset($_SESSION['config']) && ($_SESSION['config']->getAdShowDeleted() === 'true')) { |
| 1133 |
return [['oid' => '1.2.840.113556.1.4.417']]; |
| 1134 |
} |
| 1135 |
return null; |
| 1136 |
} |
| 1137 |
|
| 1138 |
/** |
| 1139 |
* Performs a recursive copy from old DN under target DN. |
| 1140 |
* |
| 1141 |
* @param string $oldDn old DN to copy |
| 1142 |
* @param string $targetDn copy nodes under this DN |
| 1143 |
* @throws LAMException error on copy |
| 1144 |
*/ |
| 1145 |
function copyDnRecursive(string $oldDn, string $targetDn): void { |
| 1146 |
$oldRdn = extractRDN($oldDn); |
| 1147 |
$newDn = $oldRdn . ',' . $targetDn; |
| 1148 |
logNewMessage(LOG_DEBUG, 'Copy DN ' . $oldDn . ' to ' . $newDn); |
| 1149 |
$attributes = ldapGetDN($oldDn, ['*']); |
| 1150 |
if (empty($attributes)) { |
| 1151 |
logNewMessage(LOG_ERR, sprintf(_("Unable to read %s."), unescapeLdapSpecialCharacters($oldDn))); |
| 1152 |
throw new LAMException(sprintf(_("Unable to read %s."), htmlspecialchars(unescapeLdapSpecialCharacters($oldDn)))); |
| 1153 |
} |
| 1154 |
unset($attributes['dn']); |
| 1155 |
$systemAttributesToSkip = ['iscriticalsystemobject', 'primarygroupid', 'samaccounttype', 'objectsid']; |
| 1156 |
foreach ($systemAttributesToSkip as $systemAttributeToSkip) { |
| 1157 |
if (isset($attributes[$systemAttributeToSkip])) { |
| 1158 |
unset($attributes[$systemAttributeToSkip]); |
| 1159 |
} |
| 1160 |
} |
| 1161 |
$success = ldap_add($_SESSION['ldap']->server(), $newDn, $attributes); |
| 1162 |
if (!$success) { |
| 1163 |
logNewMessage(LOG_ERR, sprintf(_('Was unable to create DN: %s.'), unescapeLdapSpecialCharacters($oldDn)) . ' ' . |
| 1164 |
getExtendedLDAPErrorMessage($_SESSION['ldap']->server())); |
| 1165 |
throw new LAMException(sprintf(_('Was unable to create DN: %s.'), htmlspecialchars(unescapeLdapSpecialCharacters($oldDn))), |
| 1166 |
getExtendedLDAPErrorMessage($_SESSION['ldap']->server())); |
| 1167 |
} |
| 1168 |
$children = ldapListDN($oldDn); |
| 1169 |
foreach ($children as $child) { |
| 1170 |
copyDnRecursive($child['dn'], $newDn); |
| 1171 |
} |
| 1172 |
} |
| 1173 |
|
| 1174 |
/** |
| 1175 |
* Moves an LDAP entry. |
| 1176 |
* |
| 1177 |
* @param string $oldDn old DN |
| 1178 |
* @param string $targetDn target container DN |
| 1179 |
* @throws LAMException error during move |
| 1180 |
*/ |
| 1181 |
function moveDn(string $oldDn, string $targetDn): void { |
| 1182 |
$deleteOldRdn = $_SESSION['ldap']->isActiveDirectory(); |
| 1183 |
$rdn = extractRDN($oldDn); |
| 1184 |
$success = ldap_rename($_SESSION['ldap']->server(), $oldDn, $rdn, $targetDn, $deleteOldRdn); |
| 1185 |
if (!$success) { |
| 1186 |
throw new LAMException(sprintf(_('Was unable to rename DN: %s.'), $oldDn), getDefaultLDAPErrorString($_SESSION['ldap']->server())); |
| 1187 |
} |
| 1188 |
} |
| 1189 |
|
| 1190 |
/** |
| 1191 |
* Returns the parameters for a StatusMessage of the last LDAP search. |
| 1192 |
* |
| 1193 |
* @return array<string|string[]>|null parameters for StatusMessage or null if all was ok |
| 1194 |
*/ |
| 1195 |
function getLastLDAPError(): ?array { |
| 1196 |
$errorNumber = ldap_errno($_SESSION["ldap"]->server()); |
| 1197 |
switch ($errorNumber) { |
| 1198 |
// all ok |
| 1199 |
case 0: |
| 1200 |
return null; |
| 1201 |
// size limit exceeded |
| 1202 |
case 4: |
| 1203 |
$error = ["WARN", _("LDAP sizelimit exceeded, not all entries are shown.")]; |
| 1204 |
if ($_SESSION['config']->get_searchLimit() == 0) { |
| 1205 |
// server limit exceeded |
| 1206 |
$error[] = _("See the manual for instructions to solve this problem."); |
| 1207 |
} |
| 1208 |
return $error; |
| 1209 |
// other errors |
| 1210 |
default: |
| 1211 |
return ["ERROR", _("LDAP search failed! Please check your preferences."), ldap_error($_SESSION["ldap"]->server())]; |
| 1212 |
} |
| 1213 |
} |
| 1214 |
|
| 1215 |
/** |
| 1216 |
* Cleans the result of an LDAP search. |
| 1217 |
* This will remove all 'count' entries and also all numeric array keys. |
| 1218 |
* |
| 1219 |
* @param array<string|int, mixed> $entries LDAP entries in format $entries[entry number][attribute name][attribute values] |
| 1220 |
*/ |
| 1221 |
function cleanLDAPResult(array &$entries): void { |
| 1222 |
if (isset($entries['count'])) { |
| 1223 |
unset($entries['count']); |
| 1224 |
} |
| 1225 |
// iterate over all results |
| 1226 |
$count = count($entries); |
| 1227 |
for ($e = 0; $e < $count; $e++) { |
| 1228 |
// remove 'count' entries and numerical entries |
| 1229 |
for ($i = 0; $i < $entries[$e]['count']; $i++) { |
| 1230 |
if (isset($entries[$e][$i])) { |
| 1231 |
unset($entries[$e][$i]); |
| 1232 |
} |
| 1233 |
} |
| 1234 |
unset($entries[$e]['count']); |
| 1235 |
$attrNames = array_keys($entries[$e]); |
| 1236 |
$attrCount = count($attrNames); |
| 1237 |
for ($i = 0; $i < $attrCount; $i++) { |
| 1238 |
if (is_array($entries[$e][$attrNames[$i]])) { |
| 1239 |
unset($entries[$e][$attrNames[$i]]['count']); |
| 1240 |
} |
| 1241 |
} |
| 1242 |
} |
| 1243 |
} |
| 1244 |
|
| 1245 |
/** |
| 1246 |
* Transforms a DN into a more user friendly format. |
| 1247 |
* E.g. "dc=company,dc=de" is transformed to "company > de". |
| 1248 |
* |
| 1249 |
* @param string $dn DN |
| 1250 |
* @return string transformed DN |
| 1251 |
*/ |
| 1252 |
function getAbstractDN($dn): string { |
| 1253 |
if ($dn == '') { |
| 1254 |
return ''; |
| 1255 |
} |
| 1256 |
$dn = str_replace('\\,', '\\2C', $dn); |
| 1257 |
if (!empty($_SESSION['config']) && !empty($_SESSION['config']->getHideDnPart())) { |
| 1258 |
$partToCut = ',' . $_SESSION['config']->getHideDnPart(); |
| 1259 |
$dn = str_replace($partToCut, '', $dn); |
| 1260 |
} |
| 1261 |
$parts = explode(',', $dn); |
| 1262 |
for ($i = 0; $i < count($parts); $i++) { |
| 1263 |
$subparts = explode('=', $parts[$i]); |
| 1264 |
if (count($subparts) === 2) { |
| 1265 |
$parts[$i] = $subparts[1]; |
| 1266 |
} |
| 1267 |
} |
| 1268 |
$abstractDn = implode(' ❭ ', $parts); |
| 1269 |
return unescapeLdapSpecialCharacters($abstractDn); |
| 1270 |
} |
| 1271 |
|
| 1272 |
/** |
| 1273 |
* Unescapes LDAP special characters for readability. |
| 1274 |
* |
| 1275 |
* @param string $dn escaped DN |
| 1276 |
* @return string unescaped DN |
| 1277 |
*/ |
| 1278 |
function unescapeLdapSpecialCharacters(string $dn): string { |
| 1279 |
return preg_replace_callback('/\\\([0-9A-Fa-f]{2})/', unescapeLdapSpecialCharactersCallback(...), $dn); |
| 1280 |
} |
| 1281 |
|
| 1282 |
/** |
| 1283 |
* Callback function for unescaping DN. |
| 1284 |
* |
| 1285 |
* @param array<int,string> $matches HEX value that was found |
| 1286 |
* @return string unescaped string |
| 1287 |
*/ |
| 1288 |
function unescapeLdapSpecialCharactersCallback(array $matches): string { |
| 1289 |
return chr(hexdec($matches[1])); |
| 1290 |
} |
| 1291 |
|
| 1292 |
/** |
| 1293 |
* Helper function to sort DNs. |
| 1294 |
* |
| 1295 |
* @param string $a first argument to compare |
| 1296 |
* @param string $b second argument to compare |
| 1297 |
* @return int 0 if equal, 1 if $a is greater, -1 if $b is greater |
| 1298 |
*/ |
| 1299 |
function compareDN($a, $b): int { |
| 1300 |
// split DNs |
| 1301 |
$array_a = explode(",", strtolower($a)); |
| 1302 |
$array_b = explode(",", strtolower($b)); |
| 1303 |
$len_a = count($array_a); |
| 1304 |
$len_b = count($array_b); |
| 1305 |
// check how many parts to compare |
| 1306 |
$len = min($len_a, $len_b); |
| 1307 |
// compare from last part on |
| 1308 |
for ($i = 0; $i < $len; $i++) { |
| 1309 |
// get parts to compare |
| 1310 |
$part_a = $array_a[$len_a - $i - 1]; |
| 1311 |
$part_a = explode('=', $part_a); |
| 1312 |
$part_a = $part_a[1] ?? $part_a[0]; |
| 1313 |
$part_b = $array_b[$len_b - $i - 1]; |
| 1314 |
$part_b = explode('=', $part_b); |
| 1315 |
$part_b = $part_b[1] ?? $part_b[0]; |
| 1316 |
// compare parts |
| 1317 |
if ($part_a === $part_b) { // part is identical |
| 1318 |
if ($i == ($len - 1)) { |
| 1319 |
return $len_a <=> $len_b; |
| 1320 |
} |
| 1321 |
} |
| 1322 |
else { |
| 1323 |
return strnatcasecmp($part_a, $part_b); |
| 1324 |
} |
| 1325 |
} |
| 1326 |
return -1; |
| 1327 |
} |
| 1328 |
|
| 1329 |
/** |
| 1330 |
* Helper function to sort LDAP entries by DN. |
| 1331 |
* |
| 1332 |
* @param array<string, string[]|string> $a first argument to compare |
| 1333 |
* @param array<string, string[]|string> $b second argument to compare |
| 1334 |
* @return int 0 if equal, 1 if $a is greater, -1 if $b is greater |
| 1335 |
*/ |
| 1336 |
function compareLDAPEntriesByDn(array $a, array $b): int { |
| 1337 |
if (!isset($a['dn']) || !isset($b['dn'])) { |
| 1338 |
return 0; |
| 1339 |
} |
| 1340 |
return compareDN($a['dn'], $b['dn']); |
| 1341 |
} |
| 1342 |
|
| 1343 |
/** |
| 1344 |
* Does a Base64 encoding that is URL safe. |
| 1345 |
* |
| 1346 |
* @param string $data input |
| 1347 |
* @return string encoded output |
| 1348 |
*/ |
| 1349 |
function lam_base64url_encode(string $data): string { |
| 1350 |
return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); |
| 1351 |
} |
| 1352 |
|
| 1353 |
/** |
| 1354 |
* Does a Base64 decoding that is URL safe. |
| 1355 |
* |
| 1356 |
* @param string $data encoded input |
| 1357 |
* @return string decoded output |
| 1358 |
*/ |
| 1359 |
function lam_base64url_decode(string $data): string { |
| 1360 |
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '='), true); |
| 1361 |
} |
| 1362 |
|
| 1363 |
|
| 1364 |
/** |
| 1365 |
* Formats an LDAP time string (e.g. from createTimestamp). |
| 1366 |
* |
| 1367 |
* @param String $time LDAP time value |
| 1368 |
* @return String formatted time |
| 1369 |
*/ |
| 1370 |
function formatLDAPTimestamp($time) { |
| 1371 |
$dateTime = parseLDAPTimestamp($time); |
| 1372 |
return $dateTime->format('d.m.Y H:i:s'); |
| 1373 |
} |
| 1374 |
|
| 1375 |
/** |
| 1376 |
* Parses an LDAP time stamp and returns a DateTime in current time zone. |
| 1377 |
* |
| 1378 |
* @param String $time LDAP time value |
| 1379 |
* @return DateTime time |
| 1380 |
*/ |
| 1381 |
function parseLDAPTimestamp($time) { |
| 1382 |
// Windows format: 20140118093807.0Z |
| 1383 |
// OpenLDAP format: 20140118093807Z |
| 1384 |
// cut off "Z" |
| 1385 |
$timeNumbers = substr($time, 0, -1); |
| 1386 |
// for Windows cut off ".0" |
| 1387 |
if (strpos($timeNumbers, '.') == (strlen($timeNumbers) - 2)) { |
| 1388 |
$timeNumbers = substr($timeNumbers, 0, -2); |
| 1389 |
} |
| 1390 |
$dateTime = DateTime::createFromFormat('YmdHis', $timeNumbers, new DateTimeZone('UTC')); |
| 1391 |
$dateTime->setTimezone(getTimeZone()); |
| 1392 |
return $dateTime; |
| 1393 |
} |
| 1394 |
|
| 1395 |
/** |
| 1396 |
* Simple function to obfuscate strings. |
| 1397 |
* |
| 1398 |
* @param string|null $text text to obfuscate |
| 1399 |
* @return string|null obfuscated text |
| 1400 |
*/ |
| 1401 |
function obfuscateText($text) { |
| 1402 |
if (($text === null) || ($text === '')) { |
| 1403 |
return $text; |
| 1404 |
} |
| 1405 |
return str_rot13(base64_encode('LAM_OBFUSCATE:' . $text)); |
| 1406 |
} |
| 1407 |
|
| 1408 |
/** |
| 1409 |
* Simple function to deobfuscate strings. |
| 1410 |
* |
| 1411 |
* @param string|null $text text to deobfuscate |
| 1412 |
* @return string|null deobfuscated text |
| 1413 |
*/ |
| 1414 |
function deobfuscateText($text) { |
| 1415 |
if (($text === null) || ($text === '')) { |
| 1416 |
return $text; |
| 1417 |
} |
| 1418 |
if (!isObfuscatedText($text)) { |
| 1419 |
return $text; |
| 1420 |
} |
| 1421 |
return str_replace('LAM_OBFUSCATE:', '', base64_decode(str_rot13($text))); |
| 1422 |
} |
| 1423 |
|
| 1424 |
/** |
| 1425 |
* Checks if the given text is obfuscated. |
| 1426 |
* |
| 1427 |
* @param string|null $text text to check |
| 1428 |
* @return bool obfuscated or not |
| 1429 |
*/ |
| 1430 |
function isObfuscatedText($text): bool { |
| 1431 |
if (($text === null) || ($text === '')) { |
| 1432 |
return false; |
| 1433 |
} |
| 1434 |
$deob = base64_decode(str_rot13($text)); |
| 1435 |
return (str_starts_with($deob, 'LAM_OBFUSCATE:')); |
| 1436 |
} |
| 1437 |
|
| 1438 |
/** |
| 1439 |
* Extracts the RDN attribute name from a given DN. |
| 1440 |
* |
| 1441 |
* @param string $dn DN |
| 1442 |
* @return string|null RDN attribute name |
| 1443 |
*/ |
| 1444 |
function extractRDNAttribute($dn) { |
| 1445 |
$rdn = extractRDN($dn); |
| 1446 |
if (empty($rdn)) { |
| 1447 |
return null; |
| 1448 |
} |
| 1449 |
$parts = explode("=", $rdn); |
| 1450 |
return $parts[0]; |
| 1451 |
} |
| 1452 |
|
| 1453 |
/** |
| 1454 |
* Extracts the RDN attribute value from a given DN. |
| 1455 |
* |
| 1456 |
* @param string $dn DN |
| 1457 |
* @return string|null RDN attribute value |
| 1458 |
*/ |
| 1459 |
function extractRDNValue($dn) { |
| 1460 |
$rdn = extractRDN($dn); |
| 1461 |
if (empty($rdn)) { |
| 1462 |
return null; |
| 1463 |
} |
| 1464 |
$parts = explode("=", $rdn); |
| 1465 |
return $parts[1]; |
| 1466 |
} |
| 1467 |
|
| 1468 |
/** |
| 1469 |
* Extracts the RDN part of the DN. |
| 1470 |
* |
| 1471 |
* @param string|null $dn DN |
| 1472 |
* @return string|null RDN part |
| 1473 |
*/ |
| 1474 |
function extractRDN(?string $dn): ?string { |
| 1475 |
if (empty($dn)) { |
| 1476 |
return null; |
| 1477 |
} |
| 1478 |
$dn = convertCommaEscaping($dn); |
| 1479 |
$parts = ldap_explode_dn($dn, 0); |
| 1480 |
if (empty($parts[0])) { |
| 1481 |
return null; |
| 1482 |
} |
| 1483 |
$rdn = unescapeLdapSpecialCharacters($parts[0]); |
| 1484 |
return str_replace(',', '\\2C', $rdn); |
| 1485 |
} |
| 1486 |
|
| 1487 |
/** |
| 1488 |
* Extracts the DN suffix from a given DN. |
| 1489 |
* E.g. ou=people,dc=test,dc=com will result in dc=test,dc=com. |
| 1490 |
* |
| 1491 |
* @param string|null $dn DN |
| 1492 |
* @return string|null DN suffix |
| 1493 |
*/ |
| 1494 |
function extractDNSuffix($dn) { |
| 1495 |
if ($dn === null) { |
| 1496 |
return null; |
| 1497 |
} |
| 1498 |
$dn = convertCommaEscaping($dn); |
| 1499 |
$parts = ldap_explode_dn($dn, 0); |
| 1500 |
if ($parts === false) { |
| 1501 |
return null; |
| 1502 |
} |
| 1503 |
unset($parts['count']); |
| 1504 |
array_shift($parts); |
| 1505 |
for ($i = 0; $i < count($parts); $i++) { |
| 1506 |
$parts[$i] = unescapeLdapSpecialCharacters($parts[$i]); |
| 1507 |
$parts[$i] = str_replace(',', '\\2C', $parts[$i]); |
| 1508 |
} |
| 1509 |
return implode(',', $parts); |
| 1510 |
} |
| 1511 |
|
| 1512 |
/** |
| 1513 |
* Checks if the SMTP connection with the given settings is fine. |
| 1514 |
* |
| 1515 |
* @param string $server SMTP server |
| 1516 |
* @param string $user user name |
| 1517 |
* @param string $password password |
| 1518 |
* @param string $encryption encryption type |
| 1519 |
* @throws LAMException error during SMTP connection |
| 1520 |
*/ |
| 1521 |
function testSmtpConnection(string $server, string $user, string $password, string $encryption): void { |
| 1522 |
include_once __DIR__ . '/3rdParty/composer/autoload.php'; |
| 1523 |
$mailer = new PHPMailer\PHPMailer\PHPMailer(true); |
| 1524 |
try { |
| 1525 |
$mailer->isSMTP(); |
| 1526 |
$serverParts = explode(':', $server); |
| 1527 |
$mailer->Host = $serverParts[0]; |
| 1528 |
$mailer->Port = (int) $serverParts[1]; |
| 1529 |
if (!empty($user)) { |
| 1530 |
$mailer->SMTPAuth = true; |
| 1531 |
$mailer->Username = $user; |
| 1532 |
$mailer->Password = $password; |
| 1533 |
} |
| 1534 |
$mailEncryption = $encryption; |
| 1535 |
if (empty($mailEncryption) || ($mailEncryption === LAMCfgMain::SMTP_TLS)) { |
| 1536 |
$mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; |
| 1537 |
} |
| 1538 |
elseif ($mailEncryption === LAMCfgMain::SMTP_SSL) { |
| 1539 |
$mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; |
| 1540 |
} |
| 1541 |
else { |
| 1542 |
$mailer->SMTPAutoTLS = false; |
| 1543 |
} |
| 1544 |
$mailer->CharSet = PHPMailer\PHPMailer\PHPMailer::CHARSET_UTF8; |
| 1545 |
$mailer->Timeout = 30; |
| 1546 |
$mailer->smtpConnect(); |
| 1547 |
} |
| 1548 |
catch (Exception $e) { |
| 1549 |
throw new LAMException(null, $e->getMessage(), $e); |
| 1550 |
} |
| 1551 |
} |
| 1552 |
|
| 1553 |
/** |
| 1554 |
* Sends the password mail. |
| 1555 |
* |
| 1556 |
* @param string $pwd new password |
| 1557 |
* @param array<string, string[]|string> $user LDAP attributes of user |
| 1558 |
* @param string|null $recipient recipient address (optional, $user['mail'][0] used by default) |
| 1559 |
* @return array<string|string[]>[] list of arrays that can be used to create status messages |
| 1560 |
*/ |
| 1561 |
function sendPasswordMail($pwd, $user, $recipient = null) { |
| 1562 |
$user = array_change_key_case($user); |
| 1563 |
// read mail data |
| 1564 |
$cfgMain = $_SESSION['cfgMain']; |
| 1565 |
$mailTo = null; |
| 1566 |
if (!empty($recipient)) { |
| 1567 |
$mailTo = $recipient; |
| 1568 |
} |
| 1569 |
elseif (!empty($user[$cfgMain->getMailAttribute()][0])) { |
| 1570 |
$mailTo = $user[$cfgMain->getMailAttribute()][0]; |
| 1571 |
} |
| 1572 |
if (empty($mailTo)) { |
| 1573 |
logNewMessage(LOG_ERR, 'Unable to send password mail, no TO address set.'); |
| 1574 |
return [ |
| 1575 |
['ERROR', _('Unable to send mail!')] |
| 1576 |
]; |
| 1577 |
} |
| 1578 |
$mailFrom = $_SESSION['config']->getLamProMailFrom(); |
| 1579 |
$mailReplyTo = $_SESSION['config']->getLamProMailReplyTo(); |
| 1580 |
$mailSubject = $_SESSION['config']->getLamProMailSubject(); |
| 1581 |
$mailText = $_SESSION['config']->getLamProMailText(); |
| 1582 |
$mailIsHTML = $_SESSION['config']->getLamProMailIsHTML(); |
| 1583 |
$subject = $mailSubject; |
| 1584 |
$body = $mailText; |
| 1585 |
$body = str_replace('@@newPassword@@', $pwd, $body); |
| 1586 |
$results = []; |
| 1587 |
$found = preg_match('/\@\@[^\@]+\@\@/', $body, $results); |
| 1588 |
while ($found == 1) { |
| 1589 |
$attr = str_replace('@', '', $results[0]); |
| 1590 |
$value = ''; |
| 1591 |
if (isset($user[strtolower($attr)][0])) { |
| 1592 |
$value = is_array($user[strtolower($attr)]) ? $user[strtolower($attr)][0] : $user[strtolower($attr)]; |
| 1593 |
} |
| 1594 |
$body = str_replace('@@' . $attr . '@@', $value, $body); |
| 1595 |
$found = preg_match('/\@\@[^\@]+\@\@/', $body, $results); |
| 1596 |
} |
| 1597 |
$success = sendEMail($mailTo, $subject, $body, $mailFrom, ($mailIsHTML == 'true'), $mailReplyTo); |
| 1598 |
if ($success) { |
| 1599 |
logNewMessage(LOG_DEBUG, 'Sent password mail to ' . $mailTo); |
| 1600 |
return [ |
| 1601 |
['INFO', sprintf(_('Mail successfully sent to %s.'), htmlspecialchars($mailTo))] |
| 1602 |
]; |
| 1603 |
} |
| 1604 |
else { |
| 1605 |
logNewMessage(LOG_ERR, 'Unable to send password mail to ' . htmlspecialchars($mailTo)); |
| 1606 |
return [ |
| 1607 |
['ERROR', _('Unable to send mail!')] |
| 1608 |
]; |
| 1609 |
} |
| 1610 |
} |
| 1611 |
|
| 1612 |
/** |
| 1613 |
* Sends out an email. |
| 1614 |
* |
| 1615 |
* @param string|string[] $to TO address(es) |
| 1616 |
* @param string $subject email subject |
| 1617 |
* @param string $text mail body (with \r\n EOL) |
| 1618 |
* @param string $from FROM address |
| 1619 |
* @param bool $isHTML HTML format |
| 1620 |
* @param string $replyTo REPLY-TO address (optional) |
| 1621 |
* @param string $cc CC address (optional) |
| 1622 |
* @param string $bcc BCC address (optional) |
| 1623 |
* @return bool successful |
| 1624 |
*/ |
| 1625 |
function sendEMail($to, $subject, $text, $from, $isHTML, $replyTo = null, $cc = null, $bcc = null): bool { |
| 1626 |
include_once __DIR__ . '/3rdParty/composer/autoload.php'; |
| 1627 |
$returnPath = empty($replyTo) ? $from : $replyTo; |
| 1628 |
$returnPathParsed = parseEmailAddress($returnPath); |
| 1629 |
logNewMessage(LOG_DEBUG, "Send mail from " . $from . " to " . print_r($to, true) . "\n" . $text); |
| 1630 |
$mailer = new PHPMailer\PHPMailer\PHPMailer(true); |
| 1631 |
try { |
| 1632 |
$cfgMain = $_SESSION['cfgMain']; |
| 1633 |
if (!empty($cfgMain->mailServer)) { |
| 1634 |
$mailer->isSMTP(); |
| 1635 |
$serverParts = explode(':', $cfgMain->mailServer); |
| 1636 |
$mailer->Host = $serverParts[0]; |
| 1637 |
$mailer->Port = (int) $serverParts[1]; |
| 1638 |
if (!empty($cfgMain->mailUser)) { |
| 1639 |
$mailer->SMTPAuth = true; |
| 1640 |
$mailer->Username = $cfgMain->mailUser; |
| 1641 |
$mailer->Password = $cfgMain->mailPassword; |
| 1642 |
} |
| 1643 |
$mailEncryption = $cfgMain->mailEncryption; |
| 1644 |
if (empty($mailEncryption) || ($mailEncryption === LAMCfgMain::SMTP_TLS)) { |
| 1645 |
$mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS; |
| 1646 |
} |
| 1647 |
elseif ($mailEncryption === LAMCfgMain::SMTP_SSL) { |
| 1648 |
$mailer->SMTPSecure = PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS; |
| 1649 |
} |
| 1650 |
else { |
| 1651 |
$mailer->SMTPAutoTLS = false; |
| 1652 |
} |
| 1653 |
} |
| 1654 |
$mailer->CharSet = PHPMailer\PHPMailer\PHPMailer::CHARSET_UTF8; |
| 1655 |
if (is_array($to)) { |
| 1656 |
foreach ($to as $toAddress) { |
| 1657 |
$mailer->addAddress($toAddress); |
| 1658 |
} |
| 1659 |
} |
| 1660 |
else { |
| 1661 |
$mailer->addAddress($to); |
| 1662 |
} |
| 1663 |
$mailer->Subject = $subject; |
| 1664 |
$mailer->Body = $text; |
| 1665 |
$mailer->Sender = $returnPathParsed['address']; |
| 1666 |
$fromParsed = parseEmailAddress($from); |
| 1667 |
$mailer->setFrom($fromParsed['address'], $fromParsed['name']); |
| 1668 |
$mailer->isHTML($isHTML); |
| 1669 |
if (!empty($replyTo)) { |
| 1670 |
$replyToParsed = parseEmailAddress($replyTo); |
| 1671 |
$mailer->addReplyTo($replyToParsed['address'], $replyToParsed['name']); |
| 1672 |
} |
| 1673 |
if (!empty($cc)) { |
| 1674 |
$ccParsed = parseEmailAddress($cc); |
| 1675 |
$mailer->addCC($ccParsed['address'], $ccParsed['name']); |
| 1676 |
} |
| 1677 |
if (!empty($bcc)) { |
| 1678 |
$bccParsed = parseEmailAddress($bcc); |
| 1679 |
$mailer->addBCC($bccParsed['address'], $bccParsed['name']); |
| 1680 |
} |
| 1681 |
$mailer->XMailer = 'LDAP Account Manager'; |
| 1682 |
$mailSentOk = $mailer->send(); |
| 1683 |
if (!$mailSentOk) { |
| 1684 |
logNewMessage(LOG_ERR, 'Mail sending failed: ' . $mailer->ErrorInfo); |
| 1685 |
} |
| 1686 |
else { |
| 1687 |
logNewMessage(LOG_DEBUG, 'Mail sent'); |
| 1688 |
} |
| 1689 |
return $mailSentOk; |
| 1690 |
} |
| 1691 |
catch (Exception $e) { |
| 1692 |
logNewMessage(LOG_ERR, 'Mail sending failed: ' . $e->getMessage()); |
| 1693 |
return false; |
| 1694 |
} |
| 1695 |
} |
| 1696 |
|
| 1697 |
/** |
| 1698 |
* Parses an email address text that optionally contains a display name. |
| 1699 |
* |
| 1700 |
* @param string $addressText address text (either plain email or with display name) |
| 1701 |
* @return array<string, string> parsed email address data ('address' => '[email protected]', 'name' => 'John Smith') |
| 1702 |
* @throws LAMException unknown email format |
| 1703 |
*/ |
| 1704 |
function parseEmailAddress(string $addressText): array { |
| 1705 |
$addressText = trim($addressText); |
| 1706 |
if (!str_contains($addressText, '>')) { |
| 1707 |
return [ |
| 1708 |
'address' => $addressText, |
| 1709 |
'name' => '', |
| 1710 |
]; |
| 1711 |
} |
| 1712 |
$matches = []; |
| 1713 |
if (preg_match('/"([^"]+)"\s*<([^<]+)>/', $addressText, $matches)) { |
| 1714 |
return [ |
| 1715 |
'address' => trim($matches[2]), |
| 1716 |
'name' => trim($matches[1]), |
| 1717 |
]; |
| 1718 |
} |
| 1719 |
elseif (preg_match('/\'([^\']+)\'\s*<([^<]+)>/', $addressText, $matches)) { |
| 1720 |
return [ |
| 1721 |
'address' => trim($matches[2]), |
| 1722 |
'name' => trim($matches[1]), |
| 1723 |
]; |
| 1724 |
} |
| 1725 |
elseif (preg_match('/([^"\']+)\s*<([^<]+)>/', $addressText, $matches)) { |
| 1726 |
return [ |
| 1727 |
'address' => trim($matches[2]), |
| 1728 |
'name' => trim($matches[1]), |
| 1729 |
]; |
| 1730 |
} |
| 1731 |
logNewMessage(LOG_ERR, 'Unable to parse email address: ' . $addressText); |
| 1732 |
throw new LAMException(null, _('Please enter a valid email address!')); |
| 1733 |
} |
| 1734 |
|
| 1735 |
/** |
| 1736 |
* Checks if an email address is safe for use on commandline |
| 1737 |
* |
| 1738 |
* @param string $address email address |
| 1739 |
* @return bool is safe |
| 1740 |
*/ |
| 1741 |
function isCommandlineSafeEmailAddress(string $address): bool { |
| 1742 |
$cmdEscaped = escapeshellcmd($address); |
| 1743 |
$argEscaped = escapeshellarg($address); |
| 1744 |
if (($address !== $cmdEscaped) || ("'$address'" !== $argEscaped)) { |
| 1745 |
return false; |
| 1746 |
} |
| 1747 |
$addressLength = strlen($address); |
| 1748 |
$allowedSpecialChars = ['@', '_', '-', '.']; |
| 1749 |
for ($i = 0; $i < $addressLength; $i++) { |
| 1750 |
$char = $address[$i]; |
| 1751 |
if (!ctype_alnum($char) && !in_array($char, $allowedSpecialChars)) { |
| 1752 |
return false; |
| 1753 |
} |
| 1754 |
} |
| 1755 |
return true; |
| 1756 |
} |
| 1757 |
|
| 1758 |
/** |
| 1759 |
* Sends the password SMS. |
| 1760 |
* |
| 1761 |
* @param string $pwd new password |
| 1762 |
* @param array<string, string[]|string> $user LDAP attributes of user |
| 1763 |
* @return array<string|string[]>[] list of arrays that can be used to create status messages |
| 1764 |
*/ |
| 1765 |
function sendPasswordSms(string $pwd, array $user): array { |
| 1766 |
$errors = []; |
| 1767 |
$phoneNumber = getSmsPhoneNumber($user); |
| 1768 |
include_once __DIR__ . '/plugins/sms/SmsService.inc'; |
| 1769 |
$smsService = new SmsService(); |
| 1770 |
try { |
| 1771 |
$smsService->sendSms(sprintf(_('Your new password: %s'), $pwd), $phoneNumber); |
| 1772 |
} |
| 1773 |
catch (LAMException $e) { |
| 1774 |
logNewMessage(LOG_ERR, 'SMS sending failed: ' . $e->getMessage()); |
| 1775 |
$errors[] = ['ERROR', _('Unable to send SMS.'), $e->getMessage()]; |
| 1776 |
} |
| 1777 |
return $errors; |
| 1778 |
} |
| 1779 |
|
| 1780 |
/** |
| 1781 |
* Sends an SMS test message. |
| 1782 |
* |
| 1783 |
* @param string $providerId SMS provider ID |
| 1784 |
* @param string|null $apiKey API key |
| 1785 |
* @param string|null $apiToken API token |
| 1786 |
* @param string|null $accountId account ID |
| 1787 |
* @param string|null $region region |
| 1788 |
* @param string|null $from from |
| 1789 |
* @param string|null $subject subject text |
| 1790 |
* @param string $number mobile phone number |
| 1791 |
* @throws LAMException error during SMS connection |
| 1792 |
*/ |
| 1793 |
function sendSmsTestMessage(string $providerId, ?string $apiKey, ?string $apiToken, ?string $accountId, |
| 1794 |
?string $region, ?string $from, ?string $subject, string $number): void { |
| 1795 |
include_once __DIR__ . '/plugins/sms/SmsService.inc'; |
| 1796 |
$smsService = new SmsService(); |
| 1797 |
try { |
| 1798 |
$smsService->sendSms(_('LAM test message'), $number, $providerId, $apiKey, $apiToken, $accountId, $region, $from, $subject); |
| 1799 |
} |
| 1800 |
catch (Exception $e) { |
| 1801 |
throw new LAMException(null, $e->getMessage(), $e); |
| 1802 |
} |
| 1803 |
} |
| 1804 |
|
| 1805 |
/** |
| 1806 |
* Returns the SMS phone number of a user. |
| 1807 |
* |
| 1808 |
* @param array<string, string[]|string> $attributes LDAP attributes |
| 1809 |
* @return string|null phone number if found |
| 1810 |
*/ |
| 1811 |
function getSmsPhoneNumber(array $attributes): ?string { |
| 1812 |
if (empty($_SESSION['cfgMain']->smsProvider)) { |
| 1813 |
return null; |
| 1814 |
} |
| 1815 |
$phoneAttributes = array_change_key_case($_SESSION['cfgMain']->getSmsAttributes()); |
| 1816 |
$attributes = array_change_key_case($attributes); |
| 1817 |
foreach ($phoneAttributes as $phoneAttribute) { |
| 1818 |
if (!empty($attributes[$phoneAttribute][0])) { |
| 1819 |
return $attributes[$phoneAttribute][0]; |
| 1820 |
} |
| 1821 |
} |
| 1822 |
return null; |
| 1823 |
} |
| 1824 |
|
| 1825 |
/** |
| 1826 |
* Caches module objects. |
| 1827 |
* This improves performance if the same module does not need to be created multiple times (calling get_metaData() each time). |
| 1828 |
* |
| 1829 |
* @author Roland Gruber |
| 1830 |
*/ |
| 1831 |
class moduleCache { |
| 1832 |
|
| 1833 |
/** @var array<string, object> module cache ("name:scope" => module) */ |
| 1834 |
private static array $cache = []; |
| 1835 |
|
| 1836 |
/** |
| 1837 |
* Returns a new/cached module with the given name and scope. |
| 1838 |
* |
| 1839 |
* @param string $name module name |
| 1840 |
* @param string|null $scope module scope (e.g. user) |
| 1841 |
* @return null|baseModule module object |
| 1842 |
*/ |
| 1843 |
public static function getModule($name, $scope): ?object { |
| 1844 |
if (!ScopeAndModuleValidation::isValidModuleName($name) |
| 1845 |
|| (!empty($scope) && !ScopeAndModuleValidation::isValidScopeName($scope))) { |
| 1846 |
return null; |
| 1847 |
} |
| 1848 |
if (!isset(self::$cache[$name . ':' . $scope])) { |
| 1849 |
if (!class_exists($name)) { |
| 1850 |
return null; |
| 1851 |
} |
| 1852 |
self::$cache[$name . ':' . $scope] = new $name($scope); |
| 1853 |
} |
| 1854 |
return self::$cache[$name . ':' . $scope]; |
| 1855 |
} |
| 1856 |
|
| 1857 |
} |
| 1858 |
|
| 1859 |
/** |
| 1860 |
* Returns a random number. |
| 1861 |
* |
| 1862 |
* @return int random number |
| 1863 |
*/ |
| 1864 |
function getRandomNumber(): int { |
| 1865 |
return abs(hexdec(bin2hex(openssl_random_pseudo_bytes(6)))); |
| 1866 |
} |
| 1867 |
|
| 1868 |
/** |
| 1869 |
* Connects to the LDAP server and extracts the certificates. |
| 1870 |
* |
| 1871 |
* @param String $server server name |
| 1872 |
* @param String $port server port |
| 1873 |
* @return mixed false on error and certificate if extracted successfully |
| 1874 |
*/ |
| 1875 |
function getLDAPSSLCertificate($server, $port) { |
| 1876 |
$stream = stream_context_create(["ssl" => ["capture_peer_cert_chain" => true, "verify_peer" => false, "allow_self_signed" => true]]); |
| 1877 |
$client = @stream_socket_client('ssl://' . $server . ':' . $port, $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $stream); |
| 1878 |
if (!$client) { |
| 1879 |
return false; |
| 1880 |
} |
| 1881 |
$context = stream_context_get_params($client); |
| 1882 |
if (!isset($context['options']['ssl']['peer_certificate_chain'])) { |
| 1883 |
return false; |
| 1884 |
} |
| 1885 |
$finalPEM = ''; |
| 1886 |
for ($i = 0; $i < count($context['options']['ssl']['peer_certificate_chain']); $i++) { |
| 1887 |
$cert = $context['options']['ssl']['peer_certificate_chain'][$i]; |
| 1888 |
$pemData = null; |
| 1889 |
$pemResult = @openssl_x509_export($cert, $pemData); |
| 1890 |
if ($pemResult) { |
| 1891 |
$finalPEM .= $pemData; |
| 1892 |
} |
| 1893 |
else { |
| 1894 |
return false; |
| 1895 |
} |
| 1896 |
} |
| 1897 |
return $finalPEM; |
| 1898 |
} |
| 1899 |
|
| 1900 |
/** |
| 1901 |
* Returns the extended LDAP error message if any. |
| 1902 |
* |
| 1903 |
* @param Connection $server LDAP server handle |
| 1904 |
* @return String error message |
| 1905 |
*/ |
| 1906 |
function getExtendedLDAPErrorMessage($server) { |
| 1907 |
$ldapMsg = null; |
| 1908 |
ldap_get_option($server, LDAP_OPT_ERROR_STRING, $ldapMsg); |
| 1909 |
if (empty($ldapMsg)) { |
| 1910 |
return ldap_error($server); |
| 1911 |
} |
| 1912 |
return $ldapMsg; |
| 1913 |
} |
| 1914 |
|
| 1915 |
/** |
| 1916 |
* Returns the default error message to display on the web page. |
| 1917 |
* HTML special characters are already escaped. |
| 1918 |
* |
| 1919 |
* @param Connection $server LDAP server handle |
| 1920 |
* @return String error message |
| 1921 |
*/ |
| 1922 |
function getDefaultLDAPErrorString($server) { |
| 1923 |
$extError = htmlspecialchars(getExtendedLDAPErrorMessage($server)); |
| 1924 |
// Active Directory message translations |
| 1925 |
if (str_contains($extError, 'DSID')) { |
| 1926 |
if (str_contains($extError, '5003')) { |
| 1927 |
logNewMessage(LOG_DEBUG, 'Password change failed because of ' . $extError); |
| 1928 |
$extError = _('Your password does not meet the password strength qualifications. Please retry with another one.'); |
| 1929 |
} |
| 1930 |
elseif (str_contains($extError, 'data 530,')) { |
| 1931 |
logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); |
| 1932 |
$extError = _('Logon not permitted at this time'); |
| 1933 |
} |
| 1934 |
elseif (str_contains($extError, 'data 532,')) { |
| 1935 |
logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); |
| 1936 |
$extError = _('Password expired'); |
| 1937 |
} |
| 1938 |
elseif (str_contains($extError, 'data 533,')) { |
| 1939 |
logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); |
| 1940 |
$extError = _('Account is deactivated'); |
| 1941 |
} |
| 1942 |
elseif (str_contains($extError, 'data 701,')) { |
| 1943 |
logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); |
| 1944 |
$extError = _('Account is expired'); |
| 1945 |
} |
| 1946 |
elseif (str_contains($extError, 'data 773,')) { |
| 1947 |
logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); |
| 1948 |
$extError = _('Password change required'); |
| 1949 |
} |
| 1950 |
elseif (str_contains($extError, 'data 775,')) { |
| 1951 |
logNewMessage(LOG_DEBUG, 'Login failed because of ' . $extError); |
| 1952 |
$extError = _('Account is locked'); |
| 1953 |
} |
| 1954 |
} |
| 1955 |
$genericErrorMessage = ldap_error($server); |
| 1956 |
$message = _('LDAP error, server says:') . ' ' . $genericErrorMessage; |
| 1957 |
if (!empty($extError) && ($genericErrorMessage !== $extError)) { |
| 1958 |
$message .= ' - ' . $extError; |
| 1959 |
} |
| 1960 |
return $message; |
| 1961 |
} |
| 1962 |
|
| 1963 |
/** |
| 1964 |
* Returns if the last LDAP error was due to expired password or forced password change (AD only). |
| 1965 |
* |
| 1966 |
* @param Connection $server LDAP handle |
| 1967 |
* @return bool password expired |
| 1968 |
*/ |
| 1969 |
function ldapIsPasswordExpired($server): bool { |
| 1970 |
$extError = htmlspecialchars(getExtendedLDAPErrorMessage($server)); |
| 1971 |
if (str_contains($extError, 'data 532,')) { |
| 1972 |
// password expired |
| 1973 |
return true; |
| 1974 |
} |
| 1975 |
elseif (str_contains($extError, 'data 773,')) { |
| 1976 |
// password change required |
| 1977 |
return true; |
| 1978 |
} |
| 1979 |
return false; |
| 1980 |
} |
| 1981 |
|
| 1982 |
/** |
| 1983 |
* Tries to get additional information why invalid credentials was returned. E.g. account is locked. |
| 1984 |
* |
| 1985 |
* @param LDAP\Connection $ldap LDAP object to connect for getting extra data |
| 1986 |
* @param string $userDn failed DN |
| 1987 |
* @return string extra message |
| 1988 |
*/ |
| 1989 |
function getExtraInvalidCredentialsMessage($ldap, $userDn) { |
| 1990 |
include_once __DIR__ . '/plugins/extendedInvalidCredentials/ExtraInvalidCredentials.inc'; |
| 1991 |
$extraInvalidCredentials = new ExtraInvalidCredentials(); |
| 1992 |
return $extraInvalidCredentials->getExtraMessage($ldap, $userDn); |
| 1993 |
} |
| 1994 |
|
| 1995 |
/** |
| 1996 |
* Returns the URL under which the page was loaded. |
| 1997 |
* This includes any GET parameters set. |
| 1998 |
* |
| 1999 |
* @param string $baseUrl base URL (e.g. http://www.example.com) |
| 2000 |
* @return string|null URL |
| 2001 |
*/ |
| 2002 |
function getCallingURL($baseUrl = ''): ?string { |
| 2003 |
$url = null; |
| 2004 |
if (!empty($baseUrl) && !empty($_SERVER['REQUEST_URI'])) { |
| 2005 |
$url = $baseUrl . $_SERVER['REQUEST_URI']; |
| 2006 |
} |
| 2007 |
elseif (!empty($_SERVER['REQUEST_URI']) && !empty($_SERVER['HTTP_HOST'])) { |
| 2008 |
$proto = 'http://'; |
| 2009 |
if (!empty($_SERVER['HTTPS']) && ($_SERVER['HTTPS'] != 'off')) { |
| 2010 |
$proto = 'https://'; |
| 2011 |
} |
| 2012 |
$url = $proto . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; |
| 2013 |
} |
| 2014 |
elseif (!empty($_SERVER['HTTP_REFERER'])) { |
| 2015 |
$url = $_SERVER['HTTP_REFERER']; |
| 2016 |
} |
| 2017 |
return $url; |
| 2018 |
} |
| 2019 |
|
| 2020 |
/** |
| 2021 |
* Returns the offset in hours from the configured time zone to GMT. |
| 2022 |
* |
| 2023 |
* @return float offset |
| 2024 |
*/ |
| 2025 |
function getTimeZoneOffsetHours() { |
| 2026 |
$dtz = getTimeZone(); |
| 2027 |
return round($dtz->getOffset(new DateTime('UTC')) / 3600); |
| 2028 |
} |
| 2029 |
|
| 2030 |
/** |
| 2031 |
* Returns the configured time zone. |
| 2032 |
* |
| 2033 |
* @return DateTimeZone time zone |
| 2034 |
*/ |
| 2035 |
function getTimeZone(): DateTimeZone { |
| 2036 |
$timeZoneName = 'UTC'; |
| 2037 |
if (!empty($_SESSION['config'])) { |
| 2038 |
$timeZoneName = $_SESSION['config']->getTimeZone(); |
| 2039 |
} |
| 2040 |
elseif (!empty($_SESSION['selfServiceProfile']->timeZone)) { |
| 2041 |
$timeZoneName = $_SESSION['selfServiceProfile']->timeZone; |
| 2042 |
} |
| 2043 |
return new DateTimeZone($timeZoneName); |
| 2044 |
} |
| 2045 |
|
| 2046 |
/** |
| 2047 |
* Returns the current time in formatted form. |
| 2048 |
* |
| 2049 |
* @param string $format format to use (e.g. 'Y-m-d H:i:s') |
| 2050 |
* @return string formatted value |
| 2051 |
*/ |
| 2052 |
function getFormattedTime(string $format): string { |
| 2053 |
$time = new DateTime('now', getTimeZone()); |
| 2054 |
return $time->format($format); |
| 2055 |
} |
| 2056 |
|
| 2057 |
/** |
| 2058 |
* Formats a number of seconds to a more human readable format with minutes, hours, etc. |
| 2059 |
* E.g. 70 seconds will return 1m10s. |
| 2060 |
* |
| 2061 |
* @param int|string $numSeconds number of seconds |
| 2062 |
* @return string formatted number |
| 2063 |
*/ |
| 2064 |
function formatSecondsToShortFormat($numSeconds) { |
| 2065 |
if (($numSeconds === '0') || ($numSeconds === 0)) { |
| 2066 |
return '0'; |
| 2067 |
} |
| 2068 |
if (empty($numSeconds)) { |
| 2069 |
return ''; |
| 2070 |
} |
| 2071 |
if (!is_numeric($numSeconds)) { |
| 2072 |
return $numSeconds; |
| 2073 |
} |
| 2074 |
$years = ''; |
| 2075 |
if ($numSeconds >= 31536000) { |
| 2076 |
$years = floor($numSeconds / 31536000); |
| 2077 |
$numSeconds -= $years * 31536000; |
| 2078 |
$years .= 'y'; |
| 2079 |
} |
| 2080 |
$seconds = $numSeconds % 60; |
| 2081 |
$seconds = ($seconds === 0) ? '' : $seconds . 's'; |
| 2082 |
$minutes = floor(($numSeconds % 3600) / 60); |
| 2083 |
$minutes = ($minutes == 0) ? '' : $minutes . 'm'; |
| 2084 |
$hours = floor(($numSeconds % 86400) / 3600); |
| 2085 |
$hours = ($hours == 0) ? '' : $hours . 'h'; |
| 2086 |
$days = floor(($numSeconds % 604800) / 86400); |
| 2087 |
$days = ($days == 0) ? '' : $days . 'd'; |
| 2088 |
$weeks = floor($numSeconds / 604800); |
| 2089 |
$weeks = ($weeks == 0) ? '' : $weeks . 'w'; |
| 2090 |
return $years . $weeks . $days . $hours . $minutes . $seconds; |
| 2091 |
} |
| 2092 |
|
| 2093 |
/** |
| 2094 |
* Unformats text like 1m10s back to number of seconds. |
| 2095 |
* |
| 2096 |
* @param string $text formatted text |
| 2097 |
* @return int|string number of seconds |
| 2098 |
*/ |
| 2099 |
function unformatShortFormatToSeconds($text) { |
| 2100 |
if (empty($text)) { |
| 2101 |
return $text; |
| 2102 |
} |
| 2103 |
$matches = []; |
| 2104 |
if (preg_match('/^((\d+)y)?((\d+)w)?((\d+)d)?((\d+)h)?((\d+)m)?((\d+)s)?$/', $text, $matches)) { |
| 2105 |
$newValue = 0; |
| 2106 |
if (!empty($matches[2])) { |
| 2107 |
$newValue += $matches[2] * 31536000; |
| 2108 |
} |
| 2109 |
if (!empty($matches[4])) { |
| 2110 |
$newValue += $matches[4] * 604800; |
| 2111 |
} |
| 2112 |
if (!empty($matches[6])) { |
| 2113 |
$newValue += $matches[6] * 86400; |
| 2114 |
} |
| 2115 |
if (!empty($matches[8])) { |
| 2116 |
$newValue += $matches[8] * 3600; |
| 2117 |
} |
| 2118 |
if (!empty($matches[10])) { |
| 2119 |
$newValue += $matches[10] * 60; |
| 2120 |
} |
| 2121 |
if (!empty($matches[12])) { |
| 2122 |
$newValue += $matches[12]; |
| 2123 |
} |
| 2124 |
return $newValue; |
| 2125 |
} |
| 2126 |
return $text; |
| 2127 |
} |
| 2128 |
|
| 2129 |
/** |
| 2130 |
* Checks if the user is logged in. Stops script execution if not. |
| 2131 |
* |
| 2132 |
* @param bool $check2ndFactor check if the 2nd factor was provided if required |
| 2133 |
*/ |
| 2134 |
function enforceUserIsLoggedIn($check2ndFactor = true): void { |
| 2135 |
if ((!isset($_SESSION['loggedIn']) || ($_SESSION['loggedIn'] !== true)) && empty($_SESSION['selfService_clientPassword']) && empty($_SESSION['whitePages_clientPassword'])) { |
| 2136 |
logNewMessage(LOG_WARNING, 'Detected unauthorized access to page that requires login: ' . $_SERVER["SCRIPT_FILENAME"]); |
| 2137 |
die(); |
| 2138 |
} |
| 2139 |
if ($check2ndFactor && isset($_SESSION['2factorRequired'])) { |
| 2140 |
logNewMessage(LOG_WARNING, 'Detected unauthorized access to page that requires login (2nd factor not provided): ' . $_SERVER["SCRIPT_FILENAME"]); |
| 2141 |
die(); |
| 2142 |
} |
| 2143 |
} |
| 2144 |
|
| 2145 |
/** |
| 2146 |
* Prints the content of the header part. |
| 2147 |
* |
| 2148 |
* @param string $title page title |
| 2149 |
* @param string $prefix prefix to LAM main folder (e.g. "..") |
| 2150 |
*/ |
| 2151 |
function printHeaderContents($title, $prefix): void { |
| 2152 |
echo '<meta name="viewport" content="width=device-width, initial-scale=1.0">'; |
| 2153 |
echo '<title>'; |
| 2154 |
echo $title; |
| 2155 |
echo "</title>\n"; |
| 2156 |
// include CSS files |
| 2157 |
$cssDirName = __DIR__ . '/../style'; |
| 2158 |
$cssDir = dir($cssDirName); |
| 2159 |
$cssFiles = []; |
| 2160 |
$cssEntry = $cssDir->read(); |
| 2161 |
while ($cssEntry !== false) { |
| 2162 |
if (str_ends_with($cssEntry, '.css')) { |
| 2163 |
$cssFiles[] = $cssEntry; |
| 2164 |
} |
| 2165 |
$cssEntry = $cssDir->read(); |
| 2166 |
} |
| 2167 |
sort($cssFiles); |
| 2168 |
foreach ($cssFiles as $cssEntry) { |
| 2169 |
echo "<link rel=\"stylesheet\" type=\"text/css\" href=\"$prefix/style/$cssEntry\">\n"; |
| 2170 |
} |
| 2171 |
echo '<link rel="shortcut icon" type="image/x-icon" href="' . $prefix . '/graphics/favicon.ico">'; |
| 2172 |
echo '<link rel="icon" href="' . $prefix . '/graphics/logo136.png">'; |
| 2173 |
} |
| 2174 |
|
| 2175 |
/** |
| 2176 |
* Prints script tags for all LAM JS files. |
| 2177 |
* |
| 2178 |
* @param string $prefix prefix to LAM main folder (e.g. "..") |
| 2179 |
*/ |
| 2180 |
function printJsIncludes(string $prefix): void { |
| 2181 |
$jsDirName = __DIR__ . '/../templates/lib'; |
| 2182 |
$jsDir = dir($jsDirName); |
| 2183 |
$jsFiles = []; |
| 2184 |
$jsEntry = $jsDir->read(); |
| 2185 |
while ($jsEntry !== false) { |
| 2186 |
if ((str_ends_with($jsEntry, '.js')) || (str_ends_with($jsEntry, '.php'))) { |
| 2187 |
$jsFiles[] = $jsEntry; |
| 2188 |
} |
| 2189 |
$jsEntry = $jsDir->read(); |
| 2190 |
} |
| 2191 |
sort($jsFiles); |
| 2192 |
foreach ($jsFiles as $jsEntry) { |
| 2193 |
echo "<script type=\"text/javascript\" src=\"$prefix/templates/lib/" . $jsEntry . "\"></script>\n"; |
| 2194 |
} |
| 2195 |
} |
| 2196 |
|
| 2197 |
/** |
| 2198 |
* Converts a UTF-8 string to UTF16LE. |
| 2199 |
* |
| 2200 |
* @param string|null $input UTF-8 value |
| 2201 |
* @return string|null converted value |
| 2202 |
*/ |
| 2203 |
function convertUtf8ToUtf16Le(?string $input): ?string { |
| 2204 |
if (($input === null) || ($input === '')) { |
| 2205 |
return $input; |
| 2206 |
} |
| 2207 |
$output = iconv('UTF-8', 'UTF-16LE', $input); |
| 2208 |
if ($output == '') { |
| 2209 |
$output = mb_convert_encoding($input, 'UTF-8', 'UTF-16LE'); |
| 2210 |
} |
| 2211 |
return $output; |
| 2212 |
} |
| 2213 |
|
| 2214 |
/** |
| 2215 |
* Returns the text with LAM and its version for header area. |
| 2216 |
* |
| 2217 |
* @return string LAM version text |
| 2218 |
*/ |
| 2219 |
function getLAMVersionText() { |
| 2220 |
$text = 'LDAP Account Manager'; |
| 2221 |
if (isLAMProVersion()) { |
| 2222 |
$text .= ' Pro'; |
| 2223 |
} |
| 2224 |
return $text . ' - ' . LAMVersion(); |
| 2225 |
} |
| 2226 |
|
| 2227 |
/** |
| 2228 |
* Returns if the given release is a developer version. |
| 2229 |
* |
| 2230 |
* @param string $version version |
| 2231 |
* @return bool is developer version |
| 2232 |
*/ |
| 2233 |
function isDeveloperVersion($version): bool { |
| 2234 |
return str_contains($version, 'DEV'); |
| 2235 |
} |
| 2236 |
|
| 2237 |
/** |
| 2238 |
* LAM exception with title and message. |
| 2239 |
* |
| 2240 |
* @author Roland Gruber |
| 2241 |
*/ |
| 2242 |
class LAMException extends Exception { |
| 2243 |
|
| 2244 |
private ?string $title; |
| 2245 |
|
| 2246 |
private ?int $ldapErrorCode; |
| 2247 |
|
| 2248 |
/** |
| 2249 |
* Constructor. |
| 2250 |
* |
| 2251 |
* @param string|null $title title |
| 2252 |
* @param string $message message (optional) |
| 2253 |
* @param Exception|null $cause (optional) |
| 2254 |
* @param int|null $ldapErrorCode original LDAP error code |
| 2255 |
*/ |
| 2256 |
public function __construct($title, $message = '', $cause = null, ?int $ldapErrorCode = null) { |
| 2257 |
parent::__construct($message, 0, $cause); |
| 2258 |
$this->title = $title; |
| 2259 |
$this->ldapErrorCode = $ldapErrorCode; |
| 2260 |
} |
| 2261 |
|
| 2262 |
/** |
| 2263 |
* Returns the message title. |
| 2264 |
* |
| 2265 |
* @return string|null title |
| 2266 |
*/ |
| 2267 |
public function getTitle(): ?string { |
| 2268 |
return $this->title; |
| 2269 |
} |
| 2270 |
|
| 2271 |
/** |
| 2272 |
* Returns the original LDAP error code. |
| 2273 |
* |
| 2274 |
* @return int|null error code |
| 2275 |
*/ |
| 2276 |
public function getLdapErrorCode() { |
| 2277 |
return $this->ldapErrorCode; |
| 2278 |
} |
| 2279 |
|
| 2280 |
} |
| 2281 |
|
| 2282 |
/** |
| 2283 |
* Color calculations |
| 2284 |
*/ |
| 2285 |
class LamColorUtil { |
| 2286 |
|
| 2287 |
/** |
| 2288 |
* Adjusts the brightness of the given hex color (e.g. #123456). |
| 2289 |
* |
| 2290 |
* @param string $color hex color (e.g. #123456) |
| 2291 |
* @param float $percentage percentage to darken (< 1 darkens, > 1 brightens) |
| 2292 |
* @return string darker color (e.g. #123456) |
| 2293 |
*/ |
| 2294 |
public static function adjustBrightness(string $color, float $percentage): string { |
| 2295 |
$color = self::parseColor($color); |
| 2296 |
// darken |
| 2297 |
$red = max(0, min(255, $color->red * $percentage)); |
| 2298 |
$green = max(0, min(255, $color->green * $percentage)); |
| 2299 |
$blue = max(0, min(255, $color->blue * $percentage)); |
| 2300 |
return sprintf("#%02x%02x%02x", $red, $green, $blue); |
| 2301 |
} |
| 2302 |
|
| 2303 |
/** |
| 2304 |
* Returns the text color that should be used for the given background color. |
| 2305 |
* |
| 2306 |
* @param string $backgroundColor background color (e.g. #123456) |
| 2307 |
* @return string text color (e.g. #000000) |
| 2308 |
*/ |
| 2309 |
public static function getTextColor(string $backgroundColor): string { |
| 2310 |
$color = self::parseColor($backgroundColor); |
| 2311 |
if (($color->red + $color->blue + $color->green) > (127 * 3)) { |
| 2312 |
return '#000000'; |
| 2313 |
} |
| 2314 |
return '#FFFFFF'; |
| 2315 |
} |
| 2316 |
|
| 2317 |
/** |
| 2318 |
* Parses a color value. |
| 2319 |
* |
| 2320 |
* @param string $color color |
| 2321 |
* @return LamColor color |
| 2322 |
*/ |
| 2323 |
public static function parseColor(string $color): LamColor { |
| 2324 |
$color = str_replace("#", '', $color); |
| 2325 |
$red = hexdec(substr($color, 0, 2)); |
| 2326 |
$green = hexdec(substr($color, 2, 2)); |
| 2327 |
$blue = hexdec(substr($color, 4, 2)); |
| 2328 |
return new LamColor($red, $green, $blue); |
| 2329 |
} |
| 2330 |
|
| 2331 |
} |
| 2332 |
|
| 2333 |
/** |
| 2334 |
* Color value. |
| 2335 |
*/ |
| 2336 |
class LamColor { |
| 2337 |
|
| 2338 |
public int $red; |
| 2339 |
public int $green; |
| 2340 |
public int $blue; |
| 2341 |
|
| 2342 |
/** |
| 2343 |
* @param int $red red |
| 2344 |
* @param int $green green |
| 2345 |
* @param int $blue blue |
| 2346 |
*/ |
| 2347 |
public function __construct(int $red, int $green, int $blue) { |
| 2348 |
$this->red = $red; |
| 2349 |
$this->green = $green; |
| 2350 |
$this->blue = $blue; |
| 2351 |
} |
| 2352 |
|
| 2353 |
} |