| 1 |
<?php |
| 2 |
/* |
| 3 |
|
| 4 |
This code is part of LDAP Account Manager (http://www.ldap-account-manager.org/) |
| 5 |
Copyright (C) 2006 - 2026 Roland Gruber |
| 6 |
|
| 7 |
This program is free software; you can redistribute it and/or modify |
| 8 |
it under the terms of the GNU General Public License as published by |
| 9 |
the Free Software Foundation; either version 2 of the License, or |
| 10 |
(at your option) any later version. |
| 11 |
|
| 12 |
This program is distributed in the hope that it will be useful, |
| 13 |
but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
GNU General Public License for more details. |
| 16 |
|
| 17 |
You should have received a copy of the GNU General Public License |
| 18 |
along with this program; if not, write to the Free Software |
| 19 |
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA |
| 20 |
|
| 21 |
*/ |
| 22 |
|
| 23 |
/** |
| 24 |
* This file includes functions to perform several security checks on each page load. |
| 25 |
* |
| 26 |
* @package lib |
| 27 |
* @author Roland Gruber |
| 28 |
*/ |
| 29 |
|
| 30 |
/** configuration options */ |
| 31 |
include_once(__DIR__ . '/config.inc'); |
| 32 |
/** ldap connection */ |
| 33 |
include_once(__DIR__ . '/ldap.inc'); |
| 34 |
/** common functions */ |
| 35 |
include_once(__DIR__ . '/account.inc'); |
| 36 |
|
| 37 |
// check client IP address |
| 38 |
checkClientIP(); |
| 39 |
|
| 40 |
setLAMHeaders(); |
| 41 |
|
| 42 |
/** |
| 43 |
* Starts a session and sets the cookie options. |
| 44 |
*/ |
| 45 |
function lam_start_session(): void { |
| 46 |
$cookieOptions = lamDefaultCookieOptions(); |
| 47 |
$cookieOptions['lifetime'] = 0; |
| 48 |
session_set_cookie_params($cookieOptions); |
| 49 |
session_start(); |
| 50 |
} |
| 51 |
|
| 52 |
/** |
| 53 |
* Returns the default cookie options. |
| 54 |
* |
| 55 |
* @return array<string, string|bool> cookie options |
| 56 |
*/ |
| 57 |
function lamDefaultCookieOptions(): array { |
| 58 |
$secureFlag = false; |
| 59 |
if (isset($_SERVER['HTTPS']) && strtolower($_SERVER['HTTPS']) === 'on') { |
| 60 |
$secureFlag = true; |
| 61 |
} |
| 62 |
return [ |
| 63 |
'path' => '/', |
| 64 |
'domain' => '', |
| 65 |
'secure' => $secureFlag, |
| 66 |
'httponly' => true, |
| 67 |
'samesite' => 'Lax' |
| 68 |
]; |
| 69 |
} |
| 70 |
|
| 71 |
/** |
| 72 |
* Starts a session and checks the environment. |
| 73 |
* The script is stopped if one of the checks fail (timeout redirection may be overridden). |
| 74 |
* |
| 75 |
* @param boolean $redirectToLogin redirect user to login page (default: true) |
| 76 |
* @param boolean $initSecureData init verification data like session ID and client IP (default: false) |
| 77 |
* @return boolean true if all ok, false if session expired |
| 78 |
*/ |
| 79 |
function startSecureSession($redirectToLogin = true, $initSecureData = false) { |
| 80 |
// start session |
| 81 |
if (isset($_SESSION)) { |
| 82 |
unset($_SESSION); |
| 83 |
} |
| 84 |
if (isFileBasedSession()) { |
| 85 |
$sessionDir = __DIR__ . "/../sess"; |
| 86 |
session_save_path($sessionDir); |
| 87 |
// enable garbage collection (fix for Debian based systems) |
| 88 |
if (@ini_get("session.gc_probability") == 0) { |
| 89 |
@ini_set("session.gc_probability", 1); |
| 90 |
} |
| 91 |
} |
| 92 |
lam_start_session(); |
| 93 |
// init secure data if needed |
| 94 |
if ($initSecureData && !isset($_SESSION["sec_session_id"])) { |
| 95 |
$_SESSION["sec_session_id"] = session_id(); |
| 96 |
$_SESSION["sec_client_ip"] = $_SERVER['REMOTE_ADDR']; |
| 97 |
$_SESSION['sec_sessionTime'] = time(); |
| 98 |
$_SESSION['cfgMain'] = new LAMCfgMain(); |
| 99 |
} |
| 100 |
// set error reporting |
| 101 |
if (empty($_SESSION['cfgMain']) || ($_SESSION['cfgMain']->errorReporting == LAMCfgMain::ERROR_REPORTING_DEFAULT)) { |
| 102 |
ini_set('error_reporting', (E_ALL & ~E_NOTICE)); |
| 103 |
} |
| 104 |
elseif ($_SESSION['cfgMain']->errorReporting == LAMCfgMain::ERROR_REPORTING_ALL) { |
| 105 |
ini_set('error_reporting', E_ALL); |
| 106 |
ini_set('display_errors', 'On'); |
| 107 |
} |
| 108 |
// check session id |
| 109 |
if (!isset($_SESSION["sec_session_id"]) || ($_SESSION["sec_session_id"] != session_id())) { |
| 110 |
// session id is invalid |
| 111 |
logNewMessage(LOG_WARNING, "Invalid session ID, access denied (" . getClientIPForLogging() . ")"); |
| 112 |
if ($redirectToLogin) { |
| 113 |
logoffAndBackToLoginPage(); |
| 114 |
} |
| 115 |
else { |
| 116 |
die(); |
| 117 |
} |
| 118 |
} |
| 119 |
// check if client IP has not changed |
| 120 |
if (!isset($_SESSION["sec_client_ip"]) || ($_SESSION["sec_client_ip"] != $_SERVER['REMOTE_ADDR'])) { |
| 121 |
// IP is invalid |
| 122 |
logNewMessage(LOG_WARNING, "Client IP changed, access denied (" . getClientIPForLogging() . ")"); |
| 123 |
if ($redirectToLogin) { |
| 124 |
logoffAndBackToLoginPage(); |
| 125 |
} |
| 126 |
else { |
| 127 |
die(); |
| 128 |
} |
| 129 |
} |
| 130 |
// check if session time has not expired |
| 131 |
if (($_SESSION['sec_sessionTime'] + (60 * $_SESSION['cfgMain']->sessionTimeout)) > time()) { |
| 132 |
// ok, update time |
| 133 |
$_SESSION['sec_sessionTime'] = time(); |
| 134 |
} |
| 135 |
elseif ($redirectToLogin) { |
| 136 |
// session expired, logoff user |
| 137 |
logoffAndBackToLoginPage(); |
| 138 |
} |
| 139 |
else { |
| 140 |
return false; |
| 141 |
} |
| 142 |
setSSLCaCert(); |
| 143 |
return true; |
| 144 |
} |
| 145 |
|
| 146 |
/** |
| 147 |
* Returns if the session uses files storage. |
| 148 |
* |
| 149 |
* @return bool file based session |
| 150 |
*/ |
| 151 |
function isFileBasedSession(): bool { |
| 152 |
return ((session_module_name() !== false) && (strtolower(session_module_name()) === 'files')); |
| 153 |
} |
| 154 |
|
| 155 |
/** |
| 156 |
* Checks if the client's IP address is on the list of allowed IPs. |
| 157 |
* The script is stopped if the host is not valid. |
| 158 |
*/ |
| 159 |
function checkClientIP(): void { |
| 160 |
$cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); |
| 161 |
$allowedHosts = $cfg->allowedHosts; |
| 162 |
$url = getCallingURL(); |
| 163 |
if (($url !== null) && |
| 164 |
((str_contains($url, '/selfService/selfService')) |
| 165 |
|| ((str_contains($url, '/misc/ajax.php?')) && str_contains($url, 'selfservice=1')))) { |
| 166 |
// self-service pages have separate IP list |
| 167 |
$allowedHosts = $cfg->allowedHostsSelfService; |
| 168 |
} |
| 169 |
// skip test if no hosts are defined |
| 170 |
if (empty($allowedHosts) || empty($_SERVER['REMOTE_ADDR'])) { |
| 171 |
return; |
| 172 |
} |
| 173 |
$allowedHosts = explode(",", $allowedHosts); |
| 174 |
$grantAccess = false; |
| 175 |
for ($i = 0; $i < count($allowedHosts); $i++) { |
| 176 |
$host = $allowedHosts[$i]; |
| 177 |
$ipRegex = '/^[0-9a-z\\.:\\*]+$/i'; |
| 178 |
if (!preg_match($ipRegex, $host)) { |
| 179 |
continue; |
| 180 |
} |
| 181 |
$hostRegex = str_replace(".", "\\.", $host); |
| 182 |
$hostRegex = '/^' . str_replace("*", ".*", $hostRegex) . '$/'; |
| 183 |
$clientIP = $_SERVER['REMOTE_ADDR']; |
| 184 |
if (preg_match($hostRegex, $clientIP)) { |
| 185 |
// client is allowed to access LAM |
| 186 |
$grantAccess = true; |
| 187 |
} |
| 188 |
} |
| 189 |
// stop script is client may not access LAM |
| 190 |
if (!$grantAccess) { |
| 191 |
logNewMessage(LOG_WARNING, "Invalid client IP, access denied (" . getClientIPForLogging() . ")"); |
| 192 |
die(); |
| 193 |
} |
| 194 |
} |
| 195 |
|
| 196 |
/** |
| 197 |
* Logs off the user and displays the login page. |
| 198 |
* |
| 199 |
*/ |
| 200 |
function logoffAndBackToLoginPage(): void { |
| 201 |
// log message |
| 202 |
if (isset($_SESSION['ldap'])) { |
| 203 |
$ldapUser = $_SESSION['ldap']->getUserName(); |
| 204 |
logNewMessage(LOG_WARNING, 'Session of user ' . $ldapUser . ' expired.'); |
| 205 |
// close LDAP connection |
| 206 |
@$_SESSION["ldap"]->destroy(); |
| 207 |
} |
| 208 |
elseif (isset($_SESSION['selfService_clientDN']) || (str_contains($_SERVER['REQUEST_URI'], '/selfService/'))) { |
| 209 |
logNewMessage(LOG_WARNING, 'Self-service session of DN ' . lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService') . ' expired.'); |
| 210 |
} |
| 211 |
// delete key and iv in cookie |
| 212 |
$cookieOptions = lamDefaultCookieOptions(); |
| 213 |
$cookieOptions['expires'] = 0; |
| 214 |
setcookie("Key", "", $cookieOptions); |
| 215 |
setcookie("IV", "", $cookieOptions); |
| 216 |
// link back to login page |
| 217 |
$paths = ['./', '../', '../../', '../../../', '../../../../']; |
| 218 |
$page = 'login.php'; |
| 219 |
$pageSuffix = '?expired=yes'; |
| 220 |
if (isset($_SESSION['selfService_clientDN']) || (str_contains($_SERVER['REQUEST_URI'], '/selfService/'))) { |
| 221 |
$scope = $_GET['scope']; |
| 222 |
$name = $_GET['name']; |
| 223 |
if (!preg_match('/^[0-9a-zA-Z _-]+$/', $scope) || !preg_match('/^[0-9a-zA-Z _-]+$/', $name)) { |
| 224 |
logNewMessage(LOG_ERR, 'GET parameters invalid: ' . $name . ' ' . $scope); |
| 225 |
die(); |
| 226 |
} |
| 227 |
$page = 'selfServiceLogin.php'; |
| 228 |
$pageSuffix = '?expired=yes&scope=' . $scope . '&name=' . $name; |
| 229 |
} |
| 230 |
elseif (isset($_SESSION['whitePages_clientDN']) || (str_contains($_SERVER['REQUEST_URI'], '/whitePages/'))) { |
| 231 |
$name = $_GET['name']; |
| 232 |
if (!preg_match('/^[0-9a-zA-Z _-]+$/', $name)) { |
| 233 |
logNewMessage(LOG_ERR, 'GET parameters invalid: ' . $name); |
| 234 |
die(); |
| 235 |
} |
| 236 |
$page = 'whitePagesLogin.php'; |
| 237 |
$pageSuffix = '?expired=yes&name=' . $name; |
| 238 |
} |
| 239 |
for ($i = 0; $i < count($paths); $i++) { |
| 240 |
if (file_exists($paths[$i] . $page)) { |
| 241 |
$page = $paths[$i] . $page; |
| 242 |
break; |
| 243 |
} |
| 244 |
} |
| 245 |
$page .= $pageSuffix; |
| 246 |
echo $_SESSION['header']; |
| 247 |
echo "<title></title>\n"; |
| 248 |
echo "</head>\n"; |
| 249 |
echo "<body>\n"; |
| 250 |
// print JavaScript refresh |
| 251 |
echo "<script type=\"text/javascript\">\n"; |
| 252 |
echo "top.location.href = \"" . $page . "\";\n"; |
| 253 |
echo "</script>\n"; |
| 254 |
// print the link if refresh does not work |
| 255 |
echo "<p>\n"; |
| 256 |
echo "<a target=\"_top\" href=\"" . $page . "\">" . _("Your session expired, click here to go back to the login page.") . "</a>\n"; |
| 257 |
echo "</p>\n"; |
| 258 |
echo "</body>\n"; |
| 259 |
echo "</html>\n"; |
| 260 |
// destroy session |
| 261 |
session_destroy(); |
| 262 |
unset($_SESSION); |
| 263 |
die(); |
| 264 |
} |
| 265 |
|
| 266 |
/** |
| 267 |
* Returns if debug messages are to be logged. |
| 268 |
* |
| 269 |
* @return bool debug enabled |
| 270 |
*/ |
| 271 |
function isDebugLoggingEnabled(): bool { |
| 272 |
$cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); |
| 273 |
return $cfg->logLevel >= LOG_DEBUG; |
| 274 |
} |
| 275 |
|
| 276 |
/** |
| 277 |
* Puts a new message in the log file. |
| 278 |
* |
| 279 |
* @param int $level log level (LOG_DEBUG, LOG_NOTICE, LOG_WARNING, LOG_ERR) |
| 280 |
* @param string $message log message |
| 281 |
*/ |
| 282 |
function logNewMessage($level, $message): void { |
| 283 |
$possibleLevels = [ |
| 284 |
LOG_DEBUG => 'DEBUG', |
| 285 |
LOG_NOTICE => 'NOTICE', |
| 286 |
LOG_WARNING => 'WARNING', |
| 287 |
LOG_ERR => 'ERROR']; |
| 288 |
if (!in_array($level, array_keys($possibleLevels))) { |
| 289 |
StatusMessage('ERROR', 'Invalid log level!', htmlspecialchars((string) $level)); |
| 290 |
return; |
| 291 |
} |
| 292 |
if (isset($_SESSION['cfgMain'])) { |
| 293 |
$cfg = $_SESSION['cfgMain']; |
| 294 |
} |
| 295 |
else { |
| 296 |
$cfg = new LAMCfgMain(); |
| 297 |
$_SESSION['cfgMain'] = $cfg; |
| 298 |
} |
| 299 |
// check if logging is disabled |
| 300 |
if (($cfg->logDestination == 'NONE') |
| 301 |
// check if log level is high enough |
| 302 |
|| ($cfg->logLevel < $level)) { |
| 303 |
return; |
| 304 |
} |
| 305 |
// ok to log, build log message |
| 306 |
$prefix = "LDAP Account Manager (" . session_id() . ' - ' . getClientIPForLogging() . ' - ' . getLamLdapUser() . ") - " . $possibleLevels[$level] . ": "; |
| 307 |
$message = $prefix . $message; |
| 308 |
// Syslog logging |
| 309 |
if ($cfg->logDestination == 'SYSLOG') { |
| 310 |
syslog($level, str_replace(["\n", "\r"], ['', ''], $message)); |
| 311 |
} |
| 312 |
// remote logging |
| 313 |
elseif (str_starts_with($cfg->logDestination, 'REMOTE')) { |
| 314 |
lamLogRemoteMessage($level, $message, $cfg); |
| 315 |
} |
| 316 |
// log to file |
| 317 |
elseif (LAMCfgMain::isValidLogFilename($cfg->logDestination)) { |
| 318 |
@touch($cfg->logDestination); |
| 319 |
if (is_writable($cfg->logDestination)) { |
| 320 |
$file = fopen($cfg->logDestination, 'a'); |
| 321 |
if ($file) { |
| 322 |
$timeZone = 'UTC'; |
| 323 |
$sysTimeZone = @date_default_timezone_get(); |
| 324 |
if (!empty($sysTimeZone)) { |
| 325 |
$timeZone = $sysTimeZone; |
| 326 |
} |
| 327 |
$time = new DateTime('now', new DateTimeZone($timeZone)); |
| 328 |
fwrite($file, $time->format('Y-m-d H:i:s') . ': ' . $message . "\n"); |
| 329 |
fclose($file); |
| 330 |
} |
| 331 |
} |
| 332 |
} |
| 333 |
} |
| 334 |
|
| 335 |
/** |
| 336 |
* Checks if write access to LDAP is allowed. |
| 337 |
* |
| 338 |
* @param String $scope account type (e.g. user) |
| 339 |
* @return boolean true, if allowed |
| 340 |
*/ |
| 341 |
function checkIfWriteAccessIsAllowed($scope = null) { |
| 342 |
if (!isset($_SESSION['config'])) { |
| 343 |
return false; |
| 344 |
} |
| 345 |
if ($_SESSION['config']->getAccessLevel() >= LAMConfig::ACCESS_ALL) { |
| 346 |
$typeSettings = $_SESSION['config']->get_typeSettings(); |
| 347 |
if (($scope == null) |
| 348 |
// check if write for this type is allowed |
| 349 |
|| !isset($typeSettings['readOnly_' . $scope]) |
| 350 |
|| !$typeSettings['readOnly_' . $scope]) { |
| 351 |
return true; |
| 352 |
} |
| 353 |
} |
| 354 |
return false; |
| 355 |
} |
| 356 |
|
| 357 |
/** |
| 358 |
* Checks if passwords may be changed. |
| 359 |
* |
| 360 |
* @return boolean true, if allowed |
| 361 |
*/ |
| 362 |
function checkIfPasswordChangeIsAllowed() { |
| 363 |
if (!isset($_SESSION['config'])) { |
| 364 |
return false; |
| 365 |
} |
| 366 |
return $_SESSION['config']->getAccessLevel() >= LAMConfig::ACCESS_PASSWORD_CHANGE; |
| 367 |
} |
| 368 |
|
| 369 |
/** |
| 370 |
* Checks if it is allowed to create new LDAP entries of the given type. |
| 371 |
* This also checks if general write access is enabled. |
| 372 |
* |
| 373 |
* @param String $scope account type (e.g. 'user') |
| 374 |
* @return boolean true, if new entries are allowed |
| 375 |
*/ |
| 376 |
function checkIfNewEntriesAreAllowed($scope) { |
| 377 |
if (!isLAMProVersion()) { |
| 378 |
return true; |
| 379 |
} |
| 380 |
if (!isset($_SESSION['config']) || empty($scope)) { |
| 381 |
return false; |
| 382 |
} |
| 383 |
$typeSettings = $_SESSION['config']->get_typeSettings(); |
| 384 |
if (isset($typeSettings['hideNewButton_' . $scope]) && $typeSettings['hideNewButton_' . $scope]) { |
| 385 |
return false; |
| 386 |
} |
| 387 |
return checkIfWriteAccessIsAllowed(); |
| 388 |
} |
| 389 |
|
| 390 |
/** |
| 391 |
* Checks if it is allowed to delete LDAP entries of the given type. |
| 392 |
* |
| 393 |
* @param String $scope account type (e.g. 'user') |
| 394 |
* @return boolean true, if entries may be deleted |
| 395 |
*/ |
| 396 |
function checkIfDeleteEntriesIsAllowed($scope) { |
| 397 |
if (!isLAMProVersion()) { |
| 398 |
return true; |
| 399 |
} |
| 400 |
if (!isset($_SESSION['config']) || empty($scope)) { |
| 401 |
return false; |
| 402 |
} |
| 403 |
$typeSettings = $_SESSION['config']->get_typeSettings(); |
| 404 |
if (isset($typeSettings['hideDeleteButton_' . $scope]) && $typeSettings['hideDeleteButton_' . $scope]) { |
| 405 |
return false; |
| 406 |
} |
| 407 |
return checkIfWriteAccessIsAllowed(); |
| 408 |
} |
| 409 |
|
| 410 |
/** |
| 411 |
* Checks if the password fulfills the password policies. |
| 412 |
* |
| 413 |
* @param string $password password |
| 414 |
* @param string|string[]|null $userNames user name(s) |
| 415 |
* @param string[] $otherUserAttrs user's first/last name |
| 416 |
* @return PasswordStrengthResult result |
| 417 |
*/ |
| 418 |
function checkPasswordStrength($password, $userNames, $otherUserAttrs): PasswordStrengthResult { |
| 419 |
if (($userNames !== null) && !is_array($userNames)) { |
| 420 |
$userNames = [$userNames]; |
| 421 |
} |
| 422 |
if ($password == null) { |
| 423 |
$password = ""; |
| 424 |
} |
| 425 |
$cfg = $_SESSION['cfgMain'] ?? new LAMCfgMain(); |
| 426 |
$result = new PasswordStrengthResult(); |
| 427 |
$result->setCharacterClassesRulesCount($cfg->checkedRulesCount); |
| 428 |
// check length |
| 429 |
$minLength = $cfg->passwordMinLength; |
| 430 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinLength())) { |
| 431 |
$minLength = intval($_SESSION['config']->getPwdPolicyMinLength()); |
| 432 |
} |
| 433 |
if (strlen($password) < $minLength) { |
| 434 |
$result->setLengthOk(false, $minLength); |
| 435 |
} |
| 436 |
else { |
| 437 |
$result->setLengthOk(true, $minLength); |
| 438 |
} |
| 439 |
// get number of characters per character class |
| 440 |
$lower = 0; |
| 441 |
$upper = 0; |
| 442 |
$numeric = 0; |
| 443 |
$symbols = 0; |
| 444 |
for ($i = 0; $i < strlen($password); $i++) { |
| 445 |
if (preg_match("/[a-z]/", $password[$i])) { |
| 446 |
$lower++; |
| 447 |
} |
| 448 |
if (preg_match("/[A-Z]/", $password[$i])) { |
| 449 |
$upper++; |
| 450 |
} |
| 451 |
if (preg_match("/\\d/", $password[$i])) { |
| 452 |
$numeric++; |
| 453 |
} |
| 454 |
if (preg_match("/[^a-z0-9]/i", $password[$i])) { |
| 455 |
$symbols++; |
| 456 |
} |
| 457 |
} |
| 458 |
$rulesMatched = 0; |
| 459 |
// check lower-case |
| 460 |
$minLower = $cfg->passwordMinLower; |
| 461 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getpwdPolicyMinLowercase())) { |
| 462 |
$minLower = intval($_SESSION['config']->getpwdPolicyMinLowercase()); |
| 463 |
} |
| 464 |
if ($lower < $minLower) { |
| 465 |
$result->setLowerCaseCountOk(false, $minLower); |
| 466 |
if ($cfg->checkedRulesCount == -1) { |
| 467 |
$result->setCharacterClassesRulesCountOk(false); |
| 468 |
} |
| 469 |
} |
| 470 |
else { |
| 471 |
$result->setLowerCaseCountOk(true, $minLower); |
| 472 |
$rulesMatched++; |
| 473 |
} |
| 474 |
// check upper-case |
| 475 |
$minUpper = $cfg->passwordMinUpper; |
| 476 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinUppercase())) { |
| 477 |
$minUpper = $_SESSION['config']->getPwdPolicyMinUppercase(); |
| 478 |
} |
| 479 |
if ($upper < $minUpper) { |
| 480 |
$result->setUpperCaseCountOk(false, $minUpper); |
| 481 |
if ($cfg->checkedRulesCount == -1) { |
| 482 |
$result->setCharacterClassesRulesCountOk(false); |
| 483 |
} |
| 484 |
} |
| 485 |
else { |
| 486 |
$result->setUpperCaseCountOk(true, $minUpper); |
| 487 |
$rulesMatched++; |
| 488 |
} |
| 489 |
// check numeric |
| 490 |
$minNumeric = $cfg->passwordMinNumeric; |
| 491 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinNumeric())) { |
| 492 |
$minNumeric = $_SESSION['config']->getPwdPolicyMinNumeric(); |
| 493 |
} |
| 494 |
if ($numeric < $minNumeric) { |
| 495 |
$result->setDigitCountOk(false, $minNumeric); |
| 496 |
if ($cfg->checkedRulesCount == -1) { |
| 497 |
$result->setCharacterClassesRulesCountOk(false); |
| 498 |
} |
| 499 |
} |
| 500 |
else { |
| 501 |
$result->setDigitCountOk(true, $minNumeric); |
| 502 |
$rulesMatched++; |
| 503 |
} |
| 504 |
// check symbols |
| 505 |
$minSymbols = $cfg->passwordMinSymbol; |
| 506 |
if (isset($_SESSION['config']) && is_numeric($_SESSION['config']->getPwdPolicyMinSymbolic())) { |
| 507 |
$minSymbols = $_SESSION['config']->getPwdPolicyMinSymbolic(); |
| 508 |
} |
| 509 |
if ($symbols < $minSymbols) { |
| 510 |
$result->setSymbolCountOk(false, $minSymbols); |
| 511 |
if ($cfg->checkedRulesCount == -1) { |
| 512 |
$result->setCharacterClassesRulesCountOk(false); |
| 513 |
} |
| 514 |
} |
| 515 |
else { |
| 516 |
$result->setSymbolCountOk(true, $minSymbols); |
| 517 |
$rulesMatched++; |
| 518 |
} |
| 519 |
// check classes |
| 520 |
$classes = getNumberOfCharacterClasses($password); |
| 521 |
if ($classes < $cfg->passwordMinClasses) { |
| 522 |
$result->setCharacterClassesCountOk(false, $cfg->passwordMinClasses); |
| 523 |
if ($cfg->checkedRulesCount == -1) { |
| 524 |
$result->setCharacterClassesRulesCountOk(false); |
| 525 |
} |
| 526 |
} |
| 527 |
else { |
| 528 |
$result->setCharacterClassesCountOk(true, $cfg->passwordMinClasses); |
| 529 |
$rulesMatched++; |
| 530 |
} |
| 531 |
// check rules count |
| 532 |
if (($cfg->checkedRulesCount != -1) && ($rulesMatched < $cfg->checkedRulesCount)) { |
| 533 |
$result->setCharacterClassesRulesCountOk(false); |
| 534 |
} |
| 535 |
$pwdLow = strtolower($password); |
| 536 |
// check user name |
| 537 |
if (($cfg->passwordMustNotContainUser == 'true') && !empty($userNames)) { |
| 538 |
foreach ($userNames as $userName) { |
| 539 |
$userLow = strtolower($userName); |
| 540 |
if (str_contains($pwdLow, $userLow)) { |
| 541 |
$result->setPasswordContainsUsername(true); |
| 542 |
break; |
| 543 |
} |
| 544 |
} |
| 545 |
} |
| 546 |
// check part of user name and additional attributes |
| 547 |
if (($cfg->passwordMustNotContain3Chars == 'true') && !empty($userNames)) { |
| 548 |
// check if contains part of user name |
| 549 |
foreach ($userNames as $userName) { |
| 550 |
if (strlen($userName) > 2) { |
| 551 |
$userLow = strtolower($userName); |
| 552 |
for ($i = 0; $i < strlen($userLow) - 3; $i++) { |
| 553 |
$part = substr($userLow, 0, 3); |
| 554 |
if (str_contains($pwdLow, $part)) { |
| 555 |
$result->setPasswordContainsPartialUsername(true); |
| 556 |
break; |
| 557 |
} |
| 558 |
} |
| 559 |
} |
| 560 |
} |
| 561 |
} |
| 562 |
if (($cfg->passwordMustNotContain3Chars == 'true') && !empty($otherUserAttrs)) { |
| 563 |
// check other attributes |
| 564 |
foreach ($otherUserAttrs as $other) { |
| 565 |
$low = strtolower($other); |
| 566 |
for ($i = 0; $i < strlen($low) - 3; $i++) { |
| 567 |
$part = substr($low, 0, 3); |
| 568 |
if (str_contains($pwdLow, $part)) { |
| 569 |
$result->setPasswordContainsPartialAttributes(true); |
| 570 |
break; |
| 571 |
} |
| 572 |
} |
| 573 |
} |
| 574 |
} |
| 575 |
// check external password service |
| 576 |
if (!checkPwdWithExternalPasswordService($cfg, $password)) { |
| 577 |
$result->setExternalPasswordCheckFailed(true); |
| 578 |
} |
| 579 |
return $result; |
| 580 |
} |
| 581 |
|
| 582 |
/** |
| 583 |
* Result of the password strength check. |
| 584 |
*/ |
| 585 |
class PasswordStrengthResult { |
| 586 |
|
| 587 |
private bool $lengthOk = false; |
| 588 |
private int $minLength = 0; |
| 589 |
private bool $lowerCaseCountOk = false; |
| 590 |
private int $lowerCaseMinimumCount = 0; |
| 591 |
private bool $upperCaseCountOk = false; |
| 592 |
private int $upperCaseMinimumCount = 0; |
| 593 |
private bool $digitCountOk = false; |
| 594 |
private int $digitMinimumCount = 0; |
| 595 |
private bool $symbolCountOk = false; |
| 596 |
private int $symbolMinimumCount = 0; |
| 597 |
private bool $characterClassesCountOk = false; |
| 598 |
private int $characterClassesMinimumCount = 0; |
| 599 |
private bool $characterClassesRulesCountOk = true; |
| 600 |
private int $characterClassesRulesCount = -1; |
| 601 |
private bool $passwordContainsUsername = false; |
| 602 |
private bool $passwordContainsPartialUsername = false; |
| 603 |
private bool $passwordContainsPartialAttributes = false; |
| 604 |
private bool $externalPasswordCheckFailed = false; |
| 605 |
|
| 606 |
/** |
| 607 |
* Returns if the password is valid. |
| 608 |
* |
| 609 |
* @return bool is valid |
| 610 |
*/ |
| 611 |
public function isValid(): bool { |
| 612 |
if ($this->characterClassesRulesCount === -1) { |
| 613 |
$characterRulesCheckOk = $this->lowerCaseCountOk |
| 614 |
&& $this->upperCaseCountOk |
| 615 |
&& $this->digitCountOk |
| 616 |
&& $this->symbolCountOk |
| 617 |
&& $this->characterClassesCountOk; |
| 618 |
} |
| 619 |
else { |
| 620 |
$characterRulesCheckOk = $this->characterClassesRulesCountOk; |
| 621 |
} |
| 622 |
return $this->lengthOk |
| 623 |
&& $characterRulesCheckOk |
| 624 |
&& !$this->passwordContainsUsername |
| 625 |
&& !$this->passwordContainsPartialUsername |
| 626 |
&& !$this->passwordContainsPartialAttributes |
| 627 |
&& !$this->externalPasswordCheckFailed; |
| 628 |
} |
| 629 |
|
| 630 |
/** |
| 631 |
* Returns details about failed rules. |
| 632 |
* |
| 633 |
* @return string[] issues |
| 634 |
*/ |
| 635 |
public function getIssues(): array { |
| 636 |
$details = []; |
| 637 |
if (!$this->lengthOk) { |
| 638 |
$details[] = [sprintf(_('The password must contain at least %s characters.'), $this->minLength)]; |
| 639 |
} |
| 640 |
if (($this->characterClassesRulesCount === -1) || !$this->characterClassesRulesCountOk) { |
| 641 |
if (!$this->lowerCaseCountOk) { |
| 642 |
$details[] = [sprintf(_('The password must contain at least %s lower-case characters.'), $this->lowerCaseMinimumCount)]; |
| 643 |
} |
| 644 |
if (!$this->upperCaseCountOk) { |
| 645 |
$details[] = [sprintf(_('The password must contain at least %s upper-case characters.'), $this->upperCaseMinimumCount)]; |
| 646 |
} |
| 647 |
if (!$this->digitCountOk) { |
| 648 |
$details[] = [sprintf(_('The password must contain at least %s numeric characters.'), $this->digitMinimumCount)]; |
| 649 |
} |
| 650 |
if (!$this->symbolCountOk) { |
| 651 |
$details[] = [sprintf(_('The password must contain at least %s symbolic characters.'), $this->symbolMinimumCount)]; |
| 652 |
} |
| 653 |
if (!$this->characterClassesCountOk) { |
| 654 |
$details[] = [sprintf(_('The password must contain at least %s different character classes.'), $this->characterClassesMinimumCount)]; |
| 655 |
} |
| 656 |
} |
| 657 |
if ($this->passwordContainsUsername) { |
| 658 |
$details[] = [_('The password must not contain the username.')]; |
| 659 |
} |
| 660 |
elseif ($this->passwordContainsPartialUsername) { |
| 661 |
$details[] = [_('The password must not contain parts of the username.')]; |
| 662 |
} |
| 663 |
if ($this->passwordContainsPartialAttributes) { |
| 664 |
$details[] = [_('The password must not contain parts of the account\'s attributes.')]; |
| 665 |
} |
| 666 |
if ($this->externalPasswordCheckFailed) { |
| 667 |
$details[] = [_('The password is known to be insecure.')]; |
| 668 |
} |
| 669 |
return $details; |
| 670 |
} |
| 671 |
|
| 672 |
/** |
| 673 |
* Returns the error message or null if valid. |
| 674 |
* |
| 675 |
* @return string|null message |
| 676 |
*/ |
| 677 |
public function getTextMessage(): ?string { |
| 678 |
if (!$this->lengthOk) { |
| 679 |
return sprintf(_('The password is too short. You have to enter at least %s characters.'), $this->minLength); |
| 680 |
} |
| 681 |
if ($this->characterClassesRulesCount === -1) { |
| 682 |
if (!$this->lowerCaseCountOk) { |
| 683 |
return sprintf(_('The password is too weak. You have to enter at least %s lower-case characters.'), $this->lowerCaseMinimumCount); |
| 684 |
} |
| 685 |
if (!$this->upperCaseCountOk) { |
| 686 |
return sprintf(_('The password is too weak. You have to enter at least %s upper-case characters.'), $this->upperCaseMinimumCount); |
| 687 |
} |
| 688 |
if (!$this->digitCountOk) { |
| 689 |
return sprintf(_('The password is too weak. You have to enter at least %s numeric characters.'), $this->digitMinimumCount); |
| 690 |
} |
| 691 |
if (!$this->symbolCountOk) { |
| 692 |
return sprintf(_('The password is too weak. You have to enter at least %s symbolic characters.'), $this->symbolMinimumCount); |
| 693 |
} |
| 694 |
if (!$this->characterClassesCountOk) { |
| 695 |
return sprintf(_('The password is too weak. You have to enter at least %s different character classes (upper/lower-case, numbers and symbols).'), $this->characterClassesMinimumCount); |
| 696 |
} |
| 697 |
} |
| 698 |
if (!$this->characterClassesRulesCountOk) { |
| 699 |
return sprintf(_('The password is too weak. It needs to match at least %s password complexity rules.'), $this->characterClassesRulesCount); |
| 700 |
} |
| 701 |
if ($this->passwordContainsUsername) { |
| 702 |
return _('The password is too weak. You may not use the user name as part of the password.'); |
| 703 |
} |
| 704 |
if ($this->passwordContainsPartialUsername) { |
| 705 |
return _('The password is too weak. You may not use parts of the user name for the password.'); |
| 706 |
} |
| 707 |
if ($this->passwordContainsPartialAttributes) { |
| 708 |
return _('The password is too weak. You may not use parts of user attributes for the password.'); |
| 709 |
} |
| 710 |
if ($this->externalPasswordCheckFailed) { |
| 711 |
return _('Your selected password is known to be insecure.'); |
| 712 |
} |
| 713 |
return null; |
| 714 |
} |
| 715 |
|
| 716 |
/** |
| 717 |
* Sets if the length check is ok. |
| 718 |
* |
| 719 |
* @param bool $isOk ok |
| 720 |
* @param int $minLength minimum length |
| 721 |
*/ |
| 722 |
public function setLengthOk(bool $isOk, int $minLength): void { |
| 723 |
$this->lengthOk = $isOk; |
| 724 |
$this->minLength = $minLength; |
| 725 |
} |
| 726 |
|
| 727 |
/** |
| 728 |
* Sets the number of character class checks to fulfill. |
| 729 |
* |
| 730 |
* @param int $characterClassesRulesCount count |
| 731 |
*/ |
| 732 |
public function setCharacterClassesRulesCount(int $characterClassesRulesCount): void { |
| 733 |
$this->characterClassesRulesCount = $characterClassesRulesCount; |
| 734 |
} |
| 735 |
|
| 736 |
/** |
| 737 |
* Sets if the number of character class checks is fulfilled. |
| 738 |
* |
| 739 |
* @param bool $characterClassesRulesCountOk ok |
| 740 |
*/ |
| 741 |
public function setCharacterClassesRulesCountOk(bool $characterClassesRulesCountOk): void { |
| 742 |
$this->characterClassesRulesCountOk = $characterClassesRulesCountOk; |
| 743 |
} |
| 744 |
|
| 745 |
/** |
| 746 |
* The number of character classes is ok. |
| 747 |
* |
| 748 |
* @param bool $characterClassesCountOk ok |
| 749 |
* @param int $characterClassesMinimumCount count |
| 750 |
*/ |
| 751 |
public function setCharacterClassesCountOk(bool $characterClassesCountOk, int $characterClassesMinimumCount): void { |
| 752 |
$this->characterClassesCountOk = $characterClassesCountOk; |
| 753 |
$this->characterClassesMinimumCount = $characterClassesMinimumCount; |
| 754 |
} |
| 755 |
|
| 756 |
/** |
| 757 |
* Sets if the number of digits is ok. |
| 758 |
* |
| 759 |
* @param bool $digitCountOk ok |
| 760 |
* @param int $digitMinimumCount count |
| 761 |
*/ |
| 762 |
public function setDigitCountOk(bool $digitCountOk, int $digitMinimumCount): void { |
| 763 |
$this->digitCountOk = $digitCountOk; |
| 764 |
$this->digitMinimumCount = $digitMinimumCount; |
| 765 |
} |
| 766 |
|
| 767 |
/** |
| 768 |
* Sets if the number of lower-case characters is ok. |
| 769 |
* |
| 770 |
* @param bool $lowerCaseCountOk ok |
| 771 |
* @param int $lowerCaseMinimumCount count |
| 772 |
*/ |
| 773 |
public function setLowerCaseCountOk(bool $lowerCaseCountOk, int $lowerCaseMinimumCount): void { |
| 774 |
$this->lowerCaseCountOk = $lowerCaseCountOk; |
| 775 |
$this->lowerCaseMinimumCount = $lowerCaseMinimumCount; |
| 776 |
} |
| 777 |
|
| 778 |
/** |
| 779 |
* Sets if the number of symbolic characters is ok. |
| 780 |
* |
| 781 |
* @param bool $symbolCountOk ok |
| 782 |
* @param int $symbolMinimumCount count |
| 783 |
*/ |
| 784 |
public function setSymbolCountOk(bool $symbolCountOk, int $symbolMinimumCount): void { |
| 785 |
$this->symbolCountOk = $symbolCountOk; |
| 786 |
$this->symbolMinimumCount = $symbolMinimumCount; |
| 787 |
} |
| 788 |
|
| 789 |
/** |
| 790 |
* Sets if the number of upper-case characters is ok. |
| 791 |
* |
| 792 |
* @param bool $upperCaseCountOk ok |
| 793 |
* @param int $upperCaseMinimumCount count |
| 794 |
*/ |
| 795 |
public function setUpperCaseCountOk(bool $upperCaseCountOk, int $upperCaseMinimumCount): void { |
| 796 |
$this->upperCaseCountOk = $upperCaseCountOk; |
| 797 |
$this->upperCaseMinimumCount = $upperCaseMinimumCount; |
| 798 |
} |
| 799 |
|
| 800 |
/** |
| 801 |
* Sets if the password contains the username. |
| 802 |
* |
| 803 |
* @param bool $passwordContainsUsername invalid value found |
| 804 |
*/ |
| 805 |
public function setPasswordContainsUsername(bool $passwordContainsUsername): void { |
| 806 |
$this->passwordContainsUsername = $passwordContainsUsername; |
| 807 |
} |
| 808 |
|
| 809 |
/** |
| 810 |
* Sets if the password contains a part of the username. |
| 811 |
* |
| 812 |
* @param bool $passwordContainsPartialUsername invalid value found |
| 813 |
*/ |
| 814 |
public function setPasswordContainsPartialUsername(bool $passwordContainsPartialUsername): void { |
| 815 |
$this->passwordContainsPartialUsername = $passwordContainsPartialUsername; |
| 816 |
} |
| 817 |
|
| 818 |
/** |
| 819 |
* Sets if the password contains a part of the user attributes. |
| 820 |
* |
| 821 |
* @param bool $passwordContainsPartialAttributes invalid value found |
| 822 |
*/ |
| 823 |
public function setPasswordContainsPartialAttributes(bool $passwordContainsPartialAttributes): void { |
| 824 |
$this->passwordContainsPartialAttributes = $passwordContainsPartialAttributes; |
| 825 |
} |
| 826 |
|
| 827 |
/** |
| 828 |
* Sets if the external password check failed. |
| 829 |
* |
| 830 |
* @param bool $externalPasswordCheckFailed failed |
| 831 |
*/ |
| 832 |
public function setExternalPasswordCheckFailed(bool $externalPasswordCheckFailed): void { |
| 833 |
$this->externalPasswordCheckFailed = $externalPasswordCheckFailed; |
| 834 |
} |
| 835 |
|
| 836 |
} |
| 837 |
|
| 838 |
/** |
| 839 |
* Checks the password against the external password service. |
| 840 |
* |
| 841 |
* @param LAMCfgMain $cfg main configuration |
| 842 |
* @param string $password password |
| 843 |
* @return boolean password accepted as secure |
| 844 |
*/ |
| 845 |
function checkPwdWithExternalPasswordService($cfg, $password) { |
| 846 |
if (!function_exists('curl_init') || empty($cfg->externalPwdCheckUrl)) { |
| 847 |
return true; |
| 848 |
} |
| 849 |
$sha1 = sha1($password); |
| 850 |
$sha1Prefix = substr($sha1, 0, 5); |
| 851 |
$sha1Suffix = substr($sha1, 5); |
| 852 |
$curl = curl_init(); |
| 853 |
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); |
| 854 |
$url = $cfg->externalPwdCheckUrl; |
| 855 |
$url = str_replace('{SHA1PREFIX}', $sha1Prefix, $url); |
| 856 |
curl_setopt($curl, CURLOPT_URL, $url); |
| 857 |
$results = curl_exec($curl); |
| 858 |
$code = curl_errno($curl); |
| 859 |
if ($code !== 0) { |
| 860 |
logNewMessage(LOG_ERR, 'Error calling the external password service at ' . $url |
| 861 |
. '. ' . curl_error($curl)); |
| 862 |
return true; |
| 863 |
} |
| 864 |
if (empty($results)) { |
| 865 |
return true; |
| 866 |
} |
| 867 |
$results = explode("\n", $results); |
| 868 |
foreach ($results as $result) { |
| 869 |
if (stripos($result, $sha1Suffix . ':') !== false) { |
| 870 |
return false; |
| 871 |
} |
| 872 |
} |
| 873 |
return true; |
| 874 |
} |
| 875 |
|
| 876 |
/** |
| 877 |
* Checks if the given tool is active. |
| 878 |
* Otherwise, an error message is logged and the execution is stopped (die()). |
| 879 |
* |
| 880 |
* @param String $tool tool class name (e.g. toolFileUpload) |
| 881 |
*/ |
| 882 |
function checkIfToolIsActive($tool): void { |
| 883 |
// check if hidden by config |
| 884 |
if (!$_SESSION['config']->isToolActive($tool)) { |
| 885 |
logNewMessage(LOG_ERR, 'Unauthorized access to tool ' . $tool . ' denied.'); |
| 886 |
die(); |
| 887 |
} |
| 888 |
} |
| 889 |
|
| 890 |
/** |
| 891 |
* Returns if the user is logged in. |
| 892 |
* |
| 893 |
* @return boolean is logged in |
| 894 |
*/ |
| 895 |
function isLoggedIn() { |
| 896 |
return (isset($_SESSION['loggedIn']) && ($_SESSION['loggedIn'] === true)); |
| 897 |
} |
| 898 |
|
| 899 |
/** |
| 900 |
* Returns the client IP and comma separated proxy IPs if any (HTTP_X_FORWARDED_FOR, HTTP_X_REAL_IP). |
| 901 |
* |
| 902 |
* @return String client IP (e.g. 10.10.10.10,11.11.11.11) |
| 903 |
*/ |
| 904 |
function getClientIPForLogging() { |
| 905 |
$ip = empty($_SERVER['REMOTE_ADDR']) ? '' : $_SERVER['REMOTE_ADDR']; |
| 906 |
if (!empty($_SERVER['HTTP_X_FORWARDED_FOR']) && (strlen($_SERVER['HTTP_X_FORWARDED_FOR']) < 100)) { |
| 907 |
$ip .= ',' . $_SERVER['HTTP_X_FORWARDED_FOR']; |
| 908 |
} |
| 909 |
if (!empty($_SERVER['HTTP_X_REAL_IP']) && (strlen($_SERVER['HTTP_X_REAL_IP']) < 100)) { |
| 910 |
$ip .= ',' . $_SERVER['HTTP_X_REAL_IP']; |
| 911 |
} |
| 912 |
return $ip; |
| 913 |
} |
| 914 |
|
| 915 |
/** |
| 916 |
* Returns the login dn of the current user. |
| 917 |
* |
| 918 |
* @return string user DN |
| 919 |
*/ |
| 920 |
function getLamLdapUser() { |
| 921 |
if (isset($_SESSION['ldap'])) { |
| 922 |
return $_SESSION['ldap']->getUserName(); |
| 923 |
} |
| 924 |
elseif (isset($_SESSION['selfService_clientDN'])) { |
| 925 |
return lamDecrypt($_SESSION['selfService_clientDN'], 'SelfService'); |
| 926 |
} |
| 927 |
return ''; |
| 928 |
} |
| 929 |
|
| 930 |
/** |
| 931 |
* Adds a security token to the session to prevent CSRF attacks. |
| 932 |
* |
| 933 |
* @param boolean $overwrite overwrite existing token |
| 934 |
*/ |
| 935 |
function addSecurityTokenToSession($overwrite = true): void { |
| 936 |
if (!empty($_SESSION[getSecurityTokenName()]) && !$overwrite) { |
| 937 |
return; |
| 938 |
} |
| 939 |
$_SESSION[getSecurityTokenName()] = generateRandomPassword(40); |
| 940 |
} |
| 941 |
|
| 942 |
/** |
| 943 |
* Checks if the security token from SESSION matches POST data. |
| 944 |
*/ |
| 945 |
function validateSecurityToken(): void { |
| 946 |
if (empty($_POST)) { |
| 947 |
return; |
| 948 |
} |
| 949 |
if (empty($_POST[getSecurityTokenName()]) || ($_POST[getSecurityTokenName()] != $_SESSION[getSecurityTokenName()])) { |
| 950 |
logNewMessage(LOG_ERR, 'Security token does not match POST data.'); |
| 951 |
die(); |
| 952 |
} |
| 953 |
} |
| 954 |
|
| 955 |
/** |
| 956 |
* Adds a hidden input field to the given meta HTML table. |
| 957 |
* Should be used to add token at the end of table. |
| 958 |
* |
| 959 |
* @param htmlTable|htmlGroup|htmlResponsiveRow $container table |
| 960 |
*/ |
| 961 |
function addSecurityTokenToMetaHTML($container): void { |
| 962 |
$token = new htmlHiddenInput(getSecurityTokenName(), $_SESSION[getSecurityTokenName()]); |
| 963 |
if ($container instanceof htmlResponsiveRow) { |
| 964 |
$container->add($token); |
| 965 |
return; |
| 966 |
} |
| 967 |
$container->addElement($token, true); |
| 968 |
} |
| 969 |
|
| 970 |
/** |
| 971 |
* Returns the name of the security token parameter. |
| 972 |
* |
| 973 |
* @return String name |
| 974 |
*/ |
| 975 |
function getSecurityTokenName() { |
| 976 |
return 'sec_token'; |
| 977 |
} |
| 978 |
|
| 979 |
/** |
| 980 |
* Returns the value of the security token parameter. |
| 981 |
* |
| 982 |
* @return String value |
| 983 |
*/ |
| 984 |
function getSecurityTokenValue() { |
| 985 |
return $_SESSION[getSecurityTokenName()]; |
| 986 |
} |
| 987 |
|
| 988 |
/** |
| 989 |
* Sets the X-Frame-Options and Content-Security-Policy header to prevent clickjacking. |
| 990 |
*/ |
| 991 |
function setLAMHeaders(): void { |
| 992 |
if (!headers_sent()) { |
| 993 |
header('X-Frame-Options: sameorigin'); |
| 994 |
header('Content-Security-Policy: frame-ancestors \'self\'; form-action \'self\'; base-uri \'none\'; object-src \'none\'; frame-src \'self\' https://www.google.com/recaptcha/ https://hcaptcha.com https://*.hcaptcha.com https://api.friendlycaptcha.com; worker-src \'self\' blob:'); |
| 995 |
header('X-Content-Type-Options: nosniff'); |
| 996 |
header('X-XSS-Protection: 1; mode=block'); |
| 997 |
header("Feature-Policy: ambient-light-sensor 'none'; autoplay 'none'; accelerometer 'none'; camera 'none'; encrypted-media 'none'; fullscreen 'self'; geolocation 'none'; gyroscope 'none'; magnetometer 'none'; microphone 'none'; midi 'none'; payment 'none'; picture-in-picture 'none'; speaker 'none'; sync-xhr 'self'; usb 'none'; vr 'none'"); |
| 998 |
} |
| 999 |
} |
| 1000 |
|
| 1001 |
/** |
| 1002 |
* Encrypts a string |
| 1003 |
* |
| 1004 |
* @param string $data string to encrypt |
| 1005 |
* @param string $prefix prefix for cookie names |
| 1006 |
* @return string encrypted string |
| 1007 |
*/ |
| 1008 |
function lamEncrypt($data, $prefix = '') { |
| 1009 |
if (empty($_COOKIE[$prefix . "IV"])) { |
| 1010 |
return $data; |
| 1011 |
} |
| 1012 |
// read key and iv from cookie |
| 1013 |
$iv = base64_decode($_COOKIE[$prefix . "IV"]); |
| 1014 |
$key = base64_decode($_COOKIE[$prefix . "Key"]); |
| 1015 |
// encrypt string |
| 1016 |
return openssl_encrypt(base64_encode($data), lamEncryptionAlgo(), $key, 0, $iv); |
| 1017 |
} |
| 1018 |
|
| 1019 |
/** |
| 1020 |
* Decrypts a string |
| 1021 |
* |
| 1022 |
* @param string $data string to decrypt |
| 1023 |
* @param string $prefix prefix for cookie names |
| 1024 |
* @return string decrypted string |
| 1025 |
*/ |
| 1026 |
function lamDecrypt($data, $prefix = '') { |
| 1027 |
if (empty($_COOKIE[$prefix . "IV"])) { |
| 1028 |
return $data; |
| 1029 |
} |
| 1030 |
// read key and iv from cookie |
| 1031 |
$iv = base64_decode($_COOKIE[$prefix . "IV"]); |
| 1032 |
$key = base64_decode($_COOKIE[$prefix . "Key"]); |
| 1033 |
// decrypt string |
| 1034 |
$ret = openssl_decrypt($data, lamEncryptionAlgo(), $key, 0, $iv); |
| 1035 |
return base64_decode(str_replace(chr(00), "", $ret)); |
| 1036 |
} |
| 1037 |
|
| 1038 |
/** |
| 1039 |
* Returns the encryption algorithm to use. |
| 1040 |
* |
| 1041 |
* @return string algorithm name |
| 1042 |
*/ |
| 1043 |
function lamEncryptionAlgo() { |
| 1044 |
$possibleAlgos = openssl_get_cipher_methods(); |
| 1045 |
if (in_array('AES-256-CTR', $possibleAlgos)) { |
| 1046 |
return 'AES-256-CTR'; |
| 1047 |
} |
| 1048 |
elseif (in_array('AES-256-CBC', $possibleAlgos)) { |
| 1049 |
return 'AES-256-CBC'; |
| 1050 |
} |
| 1051 |
return 'AES256'; |
| 1052 |
} |
| 1053 |
|
| 1054 |
/** |
| 1055 |
* Logs a message to a remote logging service. |
| 1056 |
* |
| 1057 |
* @param int $level log level |
| 1058 |
* @param string $message log message |
| 1059 |
* @param LAMCfgMain $cfgMain main configuration |
| 1060 |
*/ |
| 1061 |
function lamLogRemoteMessage($level, $message, $cfgMain): void { |
| 1062 |
include_once __DIR__ . '/3rdParty/composer/autoload.php'; |
| 1063 |
$remoteParts = explode(':', $cfgMain->logDestination); |
| 1064 |
$server = $remoteParts[1]; |
| 1065 |
$port = intval($remoteParts[2]); |
| 1066 |
$output = "%channel%.%level_name%: %message%"; |
| 1067 |
$formatter = new Monolog\Formatter\LineFormatter($output); |
| 1068 |
$logger = new Monolog\Logger('lam'); |
| 1069 |
$syslogHandler = new Monolog\Handler\SyslogUdpHandler($server, $port); |
| 1070 |
$syslogHandler->setFormatter($formatter); |
| 1071 |
$logger->pushHandler($syslogHandler); |
| 1072 |
switch ($level) { |
| 1073 |
case LOG_DEBUG: |
| 1074 |
$logger->debug($message); |
| 1075 |
break; |
| 1076 |
case LOG_NOTICE: |
| 1077 |
$logger->notice($message); |
| 1078 |
break; |
| 1079 |
case LOG_WARNING: |
| 1080 |
$logger->warning($message); |
| 1081 |
break; |
| 1082 |
case LOG_ERR: |
| 1083 |
$logger->error($message); |
| 1084 |
break; |
| 1085 |
} |
| 1086 |
} |
| 1087 |
|
| 1088 |
/** |
| 1089 |
* Manages temporary files. |
| 1090 |
*/ |
| 1091 |
class LamTemporaryFilesManager { |
| 1092 |
|
| 1093 |
private const SESSION_KEY = 'sec_registered_tmp_files'; |
| 1094 |
|
| 1095 |
/** |
| 1096 |
* Creates a temporary file and registers it for the current session. |
| 1097 |
* |
| 1098 |
* @param string $extension file extension (including ".", e.g. ".svg") |
| 1099 |
* @param string $prefix file prefix (default: empty) |
| 1100 |
* @return string file name |
| 1101 |
* @throws LAMException unable to create temporary file |
| 1102 |
*/ |
| 1103 |
public function registerTemporaryFile(string $extension, string $prefix = ''): string { |
| 1104 |
$fileName = $prefix . time() . generateRandomText() . $extension; |
| 1105 |
if (!$this->isValidFileName($fileName)) { |
| 1106 |
throw new LAMException(_('Unable to create temporary file.')); |
| 1107 |
} |
| 1108 |
$path = __DIR__ . '/../tmp/' . $fileName; |
| 1109 |
$handle = @fopen($path, "wb"); |
| 1110 |
if ($handle) { |
| 1111 |
@chmod($path, 0600); |
| 1112 |
fclose($handle); |
| 1113 |
$_SESSION[self::SESSION_KEY][] = $fileName; |
| 1114 |
return $fileName; |
| 1115 |
} |
| 1116 |
throw new LAMException(_('Unable to create temporary file.')); |
| 1117 |
} |
| 1118 |
|
| 1119 |
/** |
| 1120 |
* Opens a temporary file for reading. |
| 1121 |
* |
| 1122 |
* @param string $fileName file name |
| 1123 |
* @return resource file handle |
| 1124 |
* @throws LAMException unable to open file |
| 1125 |
*/ |
| 1126 |
public function openTemporaryFileForRead(string $fileName) { |
| 1127 |
if (!$this->isRegisteredFile($fileName)) { |
| 1128 |
throw new LAMException(_('Unable to read file.')); |
| 1129 |
} |
| 1130 |
$path = $this->getFileSystemPath($fileName); |
| 1131 |
$handle = @fopen($path, "r"); |
| 1132 |
if ($handle) { |
| 1133 |
return $handle; |
| 1134 |
} |
| 1135 |
throw new LAMException(_('Unable to read file.')); |
| 1136 |
} |
| 1137 |
|
| 1138 |
/** |
| 1139 |
* Opens a temporary file for writing. |
| 1140 |
* |
| 1141 |
* @param string $fileName file name |
| 1142 |
* @return resource file handle |
| 1143 |
* @throws LAMException unable to open file |
| 1144 |
*/ |
| 1145 |
public function openTemporaryFileForWrite(string $fileName) { |
| 1146 |
if (!$this->isRegisteredFile($fileName)) { |
| 1147 |
throw new LAMException(_('Unable to read file.')); |
| 1148 |
} |
| 1149 |
$path = $this->getFileSystemPath($fileName); |
| 1150 |
$handle = @fopen($path, "wb"); |
| 1151 |
if ($handle) { |
| 1152 |
return $handle; |
| 1153 |
} |
| 1154 |
throw new LAMException(_('Unable to read file.')); |
| 1155 |
} |
| 1156 |
|
| 1157 |
/** |
| 1158 |
* Checks if the given file name is valid and registered. |
| 1159 |
* |
| 1160 |
* @param string $fileName file name |
| 1161 |
* @return bool is valid |
| 1162 |
*/ |
| 1163 |
public function isRegisteredFile(string $fileName): bool { |
| 1164 |
return $this->isValidFileName($fileName) |
| 1165 |
&& !empty($_SESSION[self::SESSION_KEY]) |
| 1166 |
&& in_array($fileName, $_SESSION[self::SESSION_KEY]); |
| 1167 |
} |
| 1168 |
|
| 1169 |
/** |
| 1170 |
* Checks if the given file name contains no special characters. |
| 1171 |
* |
| 1172 |
* @param string $fileName file name |
| 1173 |
* @return bool is valid |
| 1174 |
*/ |
| 1175 |
private function isValidFileName(string $fileName): bool { |
| 1176 |
return preg_match('/^[a-zA-Z0-9\\._-]+$/', $fileName); |
| 1177 |
} |
| 1178 |
|
| 1179 |
/** |
| 1180 |
* Returns the download link to a file. |
| 1181 |
* |
| 1182 |
* @param string $fileName file name |
| 1183 |
* @param string $prefix prefix to folder "templates" (e.g. "../../" if called from templates/config/sub, default: "../") |
| 1184 |
* @return string download link |
| 1185 |
* @throws LAMException error reading file |
| 1186 |
*/ |
| 1187 |
public function getDownloadLink(string $fileName, string $prefix = '../'): string { |
| 1188 |
if (!$this->isRegisteredFile($fileName)) { |
| 1189 |
throw new LAMException(_('Unable to read file.')); |
| 1190 |
} |
| 1191 |
$selfServicePart = isSelfService() ? '&selfservice=true' : ''; |
| 1192 |
return $prefix . 'misc/download.php?file=' . $fileName . '&download=true' . $selfServicePart; |
| 1193 |
} |
| 1194 |
|
| 1195 |
/** |
| 1196 |
* Returns the plain link to a file. |
| 1197 |
* |
| 1198 |
* @param string $fileName file name |
| 1199 |
* @param string $prefix prefix to folder "templates" (e.g. "../../" if called from templates/config/sub, default: "../") |
| 1200 |
* @return string download link |
| 1201 |
* @throws LAMException error reading file |
| 1202 |
*/ |
| 1203 |
public function getResourceLink(string $fileName, string $prefix = '../'): string { |
| 1204 |
if (!$this->isRegisteredFile($fileName)) { |
| 1205 |
throw new LAMException(_('Unable to read file.')); |
| 1206 |
} |
| 1207 |
$selfServicePart = isSelfService() ? '&selfservice=true' : ''; |
| 1208 |
return $prefix . 'misc/download.php?file=' . $fileName . $selfServicePart; |
| 1209 |
} |
| 1210 |
|
| 1211 |
/** |
| 1212 |
* Returns if the extension is acceptable to be injected as resource on the page. |
| 1213 |
* |
| 1214 |
* @param string $extension extension (e.g. jpg) |
| 1215 |
* @return bool is acceptable |
| 1216 |
*/ |
| 1217 |
public function isAcceptableResourceLinkExtension(string $extension): bool { |
| 1218 |
return in_array_ignore_case($extension, ['jpg', 'jpeg', 'gif', 'png', 'pdf']); |
| 1219 |
} |
| 1220 |
|
| 1221 |
/** |
| 1222 |
* Deletes all registered files of the user. |
| 1223 |
*/ |
| 1224 |
public function deleteAllRegisteredFiles(): void { |
| 1225 |
if (empty($_SESSION[self::SESSION_KEY])) { |
| 1226 |
return; |
| 1227 |
} |
| 1228 |
foreach ($_SESSION[self::SESSION_KEY] as $fileName) { |
| 1229 |
if (!$this->isValidFileName($fileName)) { |
| 1230 |
continue; |
| 1231 |
} |
| 1232 |
$path = $this->getFileSystemPath($fileName); |
| 1233 |
if (file_exists($path)) { |
| 1234 |
unlink($path); |
| 1235 |
} |
| 1236 |
} |
| 1237 |
unset($_SESSION[self::SESSION_KEY]); |
| 1238 |
} |
| 1239 |
|
| 1240 |
/** |
| 1241 |
* Returns the raw path on file system. |
| 1242 |
* Only to be used if download/resource link cannot be used. |
| 1243 |
* |
| 1244 |
* @param string $fileName file name |
| 1245 |
* @return string path on file system |
| 1246 |
* @throws LAMException |
| 1247 |
*/ |
| 1248 |
public function getFileSystemPath(string $fileName): string { |
| 1249 |
if (!$this->isValidFileName($fileName) || !$this->isRegisteredFile($fileName)) { |
| 1250 |
throw new LAMException(_('Unable to read file.')); |
| 1251 |
} |
| 1252 |
return __DIR__ . '/../tmp/' . $fileName; |
| 1253 |
} |
| 1254 |
|
| 1255 |
} |
| 1256 |
|